diff --git a/.gitignore b/.gitignore index 1760b790d8515..1b07ae5c5817a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,42 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# Azure Tooling # +node_modules + +# Eclipse # +*.pydevproject +.project +.metadata +bin/** +tmp/** +tmp/**/* +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# Other Tooling # .classpath .project target -node_modules .idea *.iml + +# Mac OS # +.DS_Store +.DS_Store? + +# Windows # +Thumbs.db \ No newline at end of file diff --git a/ChangeLog.txt b/ChangeLog.txt index 034592cc26044..d0d8f8f005b4d 100644 --- a/ChangeLog.txt +++ b/ChangeLog.txt @@ -1,3 +1,7 @@ +2014.04.2 Version 0.5.0 + * Add multiple service management modules + * Split the SDK into multiple sub-modules + 2013.09.30 Version 0.4.6 * Allow users to set the client-request-id for better tracking/debugging of storage requests. This is set on the OperationContext. * Prevent a potential arithmetic overflow while calculating the exponential retry back-off interval in storage. diff --git a/README.md b/README.md index 93e0046cec226..b5c98c31e1b32 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -#Windows Azure SDK for Java +#Microsoft Azure SDK for Java -This project provides a client library in Java that makes it easy to consume Windows Azure services. For documentation please see the [Windows Azure Java Developer Center](http://www.windowsazure.com/en-us/develop/java/). +This project provides a client library in Java that makes it easy to consume Microsoft Azure services. For documentation please see the [Microsoft Azure Java Developer Center](http://azure.microsoft.com/en-us/develop/java/). #Features @@ -38,10 +38,14 @@ This project provides a client library in Java that makes it easy to consume Win * Add/Get job notifications * Create/Read/Update/Delete notification endpoints * Service Management - * Manage affinity groups + * Compute Management + * Web Site Management + * Virtual Network Management + * Storage Management + * Sql Database Management * Service Runtime * Retrieve information about the state of your Azure Compute instances - + #Getting Started @@ -50,7 +54,7 @@ This project provides a client library in Java that makes it easy to consume Win To get the source code of the SDK via git just type: - git clone git://github.com/WindowsAzure/azure-sdk-for-java.git + git clone git://github.com/Azure/azure-sdk-for-java.git cd ./azure-sdk-for-java/microsoft-azure-api/ mvn compile @@ -71,19 +75,19 @@ within your project you can also have them installed by the Java package manager * Java 1.6 * (Optional) Maven - + ##Usage -To use this SDK to call Windows Azure services, you need to first create an -account. To host your Java code in Windows Azure, you additionally need to download -the full Windows Azure SDK for Java - which includes packaging, emulation, and +To use this SDK to call Microsoft Azure services, you need to first create an +account. To host your Java code in Microsoft Azure, you additionally need to download +the full Microsoft Azure SDK for Java - which includes packaging, emulation, and deployment tools. ##Code Sample The following is a quick example on how to set up a Azure blob using the API -and uploading a file to it. For additional information on using the client libraries to access Azure services see the How To guides listed [here](http://www.windowsazure.com/en-us/develop/java/). +and uploading a file to it. For additional information on using the client libraries to access Azure services see the How To guides listed [here](http://azure.microsoft.com/en-us/develop/java/). ```java import java.io.*; @@ -92,63 +96,63 @@ import com.microsoft.windowsazure.services.core.storage.*; import com.microsoft.windowsazure.services.blob.client.*; public class BlobSample { - public static final String storageConnectionString = - "DefaultEndpointsProtocol=http;" - + "AccountName=your_account_name;" - + "AccountKey= your_account_key"; - - public static void main(String[] args) { - try { - CloudStorageAccount account; - CloudBlobClient serviceClient; - CloudBlobContainer container; - CloudBlockBlob blob; - - account = CloudStorageAccount.parse(storageConnectionString); - serviceClient = account.createCloudBlobClient(); - // Container name must be lower case. - container = serviceClient.getContainerReference("blobsample"); - container.createIfNotExist(); - - // Set anonymous access on the container. - BlobContainerPermissions containerPermissions; - containerPermissions = new BlobContainerPermissions(); - container.uploadPermissions(containerPermissions); - - // Upload an image file. - blob = container.getBlockBlobReference("image1.jpg"); - File fileReference = new File("c:\\myimages\\image1.jpg"); - blob.upload(new FileInputStream(fileReference), fileReference.length()); - } catch (FileNotFoundException fileNotFoundException) { - System.out.print("FileNotFoundException encountered: "); - System.out.println(fileNotFoundException.getMessage()); - System.exit(-1); - } catch (StorageException storageException) { - System.out.print("StorageException encountered: "); - System.out.println(storageException.getMessage()); - System.exit(-1); - } catch (Exception e) { - System.out.print("Exception encountered: "); - System.out.println(e.getMessage()); - System.exit(-1); - } - - } + public static final String storageConnectionString = + "DefaultEndpointsProtocol=http;" + + "AccountName=your_account_name;" + + "AccountKey= your_account_key"; + + public static void main(String[] args) { + try { + CloudStorageAccount account; + CloudBlobClient serviceClient; + CloudBlobContainer container; + CloudBlockBlob blob; + + account = CloudStorageAccount.parse(storageConnectionString); + serviceClient = account.createCloudBlobClient(); + // Container name must be lower case. + container = serviceClient.getContainerReference("blobsample"); + container.createIfNotExist(); + + // Set anonymous access on the container. + BlobContainerPermissions containerPermissions; + containerPermissions = new BlobContainerPermissions(); + container.uploadPermissions(containerPermissions); + + // Upload an image file. + blob = container.getBlockBlobReference("image1.jpg"); + File fileReference = new File("c:\\myimages\\image1.jpg"); + blob.upload(new FileInputStream(fileReference), fileReference.length()); + } catch (FileNotFoundException fileNotFoundException) { + System.out.print("FileNotFoundException encountered: "); + System.out.println(fileNotFoundException.getMessage()); + System.exit(-1); + } catch (StorageException storageException) { + System.out.print("StorageException encountered: "); + System.out.println(storageException.getMessage()); + System.exit(-1); + } catch (Exception e) { + System.out.print("Exception encountered: "); + System.out.println(e.getMessage()); + System.exit(-1); + } + + } } ``` #Need Help? -Be sure to check out the Windows Azure [Developer Forums on Stack Overflow](http://go.microsoft.com/fwlink/?LinkId=234489) if you have trouble with the provided code. +Be sure to check out the Microsoft Azure [Developer Forums on Stack Overflow](http://go.microsoft.com/fwlink/?LinkId=234489) if you have trouble with the provided code. #Contribute Code or Provide Feedback -If you would like to become an active contributor to this project please follow the instructions provided in [Windows Azure Projects Contribution Guidelines](http://windowsazure.github.com/guidelines.html). +If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](http://azure.github.com/guidelines.html). -If you encounter any bugs with the library please file an issue in the [Issues](https://github.com/WindowsAzure/azure-sdk-for-java/issues) section of the project. +If you encounter any bugs with the library please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-java/issues) section of the project. #Learn More -* [Windows Azure Java Developer Center](http://www.windowsazure.com/en-us/develop/java/) +* [Microsoft Azure Java Developer Center](http://azure.microsoft.com/en-us/develop/java/) * [JavaDocs](http://dl.windowsazure.com/javadoc/) diff --git a/core-test/pom.xml b/core-test/pom.xml new file mode 100644 index 0000000000000..78100f8a60d89 --- /dev/null +++ b/core-test/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-core-test + jar + + Microsoft Azure Core Test Client API + API for Testing Microsoft Azure Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + ${project.groupId} + microsoft-azure-api-management + 0.5.0 + + + ${project.groupId} + microsoft-azure-api-management-websites + 0.5.0 + + + ${project.groupId} + microsoft-azure-api-management-storage + 0.5.0 + + + ${project.groupId} + microsoft-azure-api-management-sql + 0.5.0 + + + + info.cukes + cucumber-java + test + + + info.cukes + cucumber-junit + test + + + diff --git a/core-test/src/test/java/com/microsoft/windowsazure/ManagementResourceStepdefs.java b/core-test/src/test/java/com/microsoft/windowsazure/ManagementResourceStepdefs.java new file mode 100644 index 0000000000000..c16257e3a9a99 --- /dev/null +++ b/core-test/src/test/java/com/microsoft/windowsazure/ManagementResourceStepdefs.java @@ -0,0 +1,693 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Random; + +import org.junit.Assert; + +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; + +import cucumber.api.java.en.And; +import cucumber.api.java.en.Given; +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; + +/** + * The Class ManagementResourceStepdefs. + */ +public class ManagementResourceStepdefs { + /** The objects. */ + private HashMap objects = new HashMap(); + + /** The random. */ + private static Random random = new Random(); + + /** + * I_create_a_character_random_string_with_name. + * + * @param length the length + * @param name the name + * @param prefix the prefix + */ + @And("^I create a \"([^\"]*)\" character random String with name \"([^\"]*)\" and prefix \"([^\"]*)\"$") + public void i_create_a_character_random_string_with_name(int length, String name, String prefix) { + StringBuilder stringBuilder = new StringBuilder(length); + for (int i=0; i serviceClass = Class.forName("com.microsoft.windowsazure.management.ManagementService"); + Method method = serviceClass.getMethod("create", Configuration.class); + objects.put(name, method.invoke(null, createConfiguration())); + } + else if (objectType.equals("WebSiteManagementClient")) { + Class serviceClass = Class.forName("com.microsoft.windowsazure.management.websites.WebSiteManagementService"); + Method method = serviceClass.getMethod("create", Configuration.class); + objects.put(name, method.invoke(null, createConfiguration())); + } + else if (objectType.equals("StorageManagementClient")) { + Class serviceClass = Class.forName("com.microsoft.windowsazure.management.storage.StorageManagementService"); + Method method = serviceClass.getMethod("create", Configuration.class); + objects.put(name, method.invoke(null, createConfiguration())); + } + else if (objectType.equals("SqlManagementClient")) { + Class serviceClass = Class.forName("com.microsoft.windowsazure.management.sql.SqlManagementService"); + Method method = serviceClass.getMethod("create", Configuration.class); + objects.put(name, method.invoke(null, createConfiguration())); + } + else { + Class objectClass = TextUtility.getJavaType(objectType); + objects.put(name, objectClass.newInstance()); + } + } + + /** + * Set_property_obj. + * + * @param propertyName the property name + * @param propertyObj the property obj + * @param propertyType the property type + * @throws ClassNotFoundException the class not found exception + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + @Given("^set \"([^\"]*)\" with \"([^\"]*)\" of type \"([^\"]*)\"$") + public void set_property_obj(String propertyName, String propertyObj, String propertyType) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + String[] parts = propertyName.split("\\."); + Object object = getObject(parts); + if (parts.length > 1) { + Method method = object.getClass().getMethod("set" + TextUtility.ToPascalCase(parts[parts.length - 1]), TextUtility.getJavaType(propertyType)); + method.invoke(object, objects.get(propertyObj)); + } + else { + objects.put(propertyName, objects.get(propertyObj)); + } + } + + /** + * Set_property. + * + * @param propertyName the property name + * @param propertyValue the property value + * @param propertyType the property type + * @throws ClassNotFoundException the class not found exception + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + @Given("^set \"([^\"]*)\" with value \"([^\"]*)\" of type \"([^\"]*)\"$") + public void set_property(String propertyName, String propertyValue, String propertyType) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + String[] parts = propertyName.split("\\."); + Object object = getObject(parts); + if (parts.length > 1) { + Method method = object.getClass().getMethod("set" + TextUtility.ToPascalCase(parts[parts.length - 1]), TextUtility.getJavaType(propertyType)); + method.invoke(object, TextUtility.convertStringTo(propertyValue, propertyType)); + } + else { + objects.put(propertyName, TextUtility.convertStringTo(propertyValue, propertyType)); + } + } + + /** + * Set_property_from_path. + * + * @param propertyName the property name + * @param valuePath the value path + * @param propertyType the property type + * @throws ClassNotFoundException the class not found exception + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + @Given("^set \"([^\"]*)\" with value from path \"([^\"]*)\" of type \"([^\"]*)\"$") + public void set_property_from_path(String propertyName, String valuePath, String propertyType) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + String[] propertyParts = valuePath.split("\\."); + Object propertyObject = getObject(propertyParts); + + Object propertyValue = getPropertyValue(propertyObject, propertyParts[propertyParts.length - 1]); + + String[] parts = propertyName.split("\\."); + Object object = getObject(parts); + if (parts.length > 1) { + Method method = object.getClass().getMethod("set" + TextUtility.ToPascalCase(parts[parts.length - 1]), TextUtility.getJavaType(propertyType)); + method.invoke(object, propertyValue); + } + else { + objects.put(propertyName, propertyValue); + } + } + + /** + * Set_value_where_equals. + * + * @param objectName the object name + * @param path the path + * @param propertyPath the property path + * @param propertyType the property type + * @param value the value + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @And("^set \"([^\"]*)\" with value from list \"([^\"]*)\" where \"([^\"]*)\" of type \"([^\"]*)\" equals \"([^\"]*)\"$") + public void set_value_where_equals(String objectName, String path, String propertyPath, String propertyType, String value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = path.split("\\."); + Object parent = getObject(parts); + ArrayList arrayObject = (ArrayList) getPropertyValue(parent, parts[parts.length - 1]); + + for (int i = 0; i < arrayObject.size(); i++) { + String[] propertyParts = propertyPath.split("\\."); + Object propertyParent = getObject(arrayObject.get(i), propertyParts); + Object propertyValue = getPropertyValue(propertyParent, propertyParts[propertyParts.length - 1]); + if (propertyValue.equals(TextUtility.convertStringTo(value, propertyType))) { + objects.put(objectName, arrayObject.get(i)); + return; + } + } + + throw new NullPointerException(); + } + + /** + * Set_value_where_equals_parameter. + * + * @param objectName the object name + * @param path the path + * @param propertyPath the property path + * @param propertyType the property type + * @param parameterName the parameter name + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @And("^set \"([^\"]*)\" with value from list \"([^\"]*)\" where \"([^\"]*)\" of type \"([^\"]*)\" equals parameter \"([^\"]*)\"$") + public void set_value_where_equals_parameter(String objectName, String path, String propertyPath, String propertyType, String parameterName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = path.split("\\."); + Object parent = getObject(parts); + ArrayList arrayObject = (ArrayList) getPropertyValue(parent, parts[parts.length - 1]); + Object value = objects.get(parameterName); + for (int i = 0; i < arrayObject.size(); i++) { + String[] propertyParts = propertyPath.split("\\."); + Object propertyParent = getObject(arrayObject.get(i), propertyParts); + Object propertyValue = getPropertyValue(propertyParent, propertyParts[propertyParts.length - 1]); + if (propertyValue.equals(value)) { + objects.put(objectName, arrayObject.get(i)); + return; + } + } + + throw new NullPointerException(); + } + + /** + * Gets the property value. + * + * @param parent the parent + * @param propertyName the property name + * @return the property value + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + private Object getPropertyValue(Object parent, String propertyName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method method; + if (propertyName.toLowerCase().equals("length")) { + method = parent.getClass().getMethod("size"); + } + else { + method = parent.getClass().getMethod("get" + TextUtility.ToPascalCase(propertyName)); + } + + return method.invoke(parent); + } + + /** + * And_get_property_equals. + * + * @param propertyType the property type + * @param propertyName the property name + * @param propertyValue the property value + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @And("^property with type \"([^\"]*)\" and path \"([^\"]*)\" should equal \"([^\"]*)\"$") + public void and_get_property_equals(String propertyType, String propertyName, String propertyValue) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = propertyName.split("\\."); + Object object = getObject(parts); + + Object result = getPropertyValue(object, parts[parts.length - 1]); + + // Assert + Assert.assertEquals(TextUtility.convertStringTo(propertyValue, propertyType), result); + } + + @And("^property with type \"([^\"]*)\" and path \"([^\"]*)\" should equal parameter \"([^\"]*)\"$") + public void and_get_property_equals_parameters(String propertyType, String propertyName, String parameterName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = propertyName.split("\\."); + Object object = getObject(parts); + + Object result = getPropertyValue(object, parts[parts.length - 1]); + + Object parameterValue = objects.get(parameterName); + // Assert + Assert.assertEquals(parameterValue, result); + } + + /** + * And_get_property_not_equals. + * + * @param propertyType the property type + * @param propertyName the property name + * @param propertyValue the property value + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @And("^property with type \"([^\"]*)\" and path \"([^\"]*)\" should not equal \"([^\"]*)\"$") + public void and_get_property_not_equals(String propertyType, String propertyName, String propertyValue) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = propertyName.split("\\."); + Object object = getObject(parts); + + Method method = object.getClass().getMethod("get" + TextUtility.ToPascalCase(parts[parts.length - 1])); + Object result = method.invoke(object); + + // Assert + Assert.assertNotEquals(TextUtility.convertStringTo(propertyValue, propertyType), result); + } + + /** + * When_invoke_with_parameter_value_get_result. + * + * @param methodName the method name + * @param parameterValue the parameter value + * @param parameterType the parameter type + * @param resultName the result name + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameter value \"([^\"]*)\" of type \"([^\"]*)\" I get the result into \"([^\"]*)\"$") + public void when_invoke_with_parameter_value_get_result(String methodName, String parameterValue, String parameterType, String resultName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + objects.put(resultName, when_invoke_with_parameter_converted_value(methodName, TextUtility.convertStringTo(parameterValue, parameterType), parameterType)); + } + + /** + * When_invoke_with_parameter_get_result. + * + * @param methodName the method name + * @param parameterName the parameter name + * @param resultName the result name + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameter \"([^\"]*)\" I get the result into \"([^\"]*)\"$") + public void when_invoke_with_parameter_get_result(String methodName, String parameterName, String resultName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + Object parameter = objects.get(parameterName); + objects.put(resultName, when_invoke_with_parameter_converted_value(methodName, parameter, parameter.getClass().getName())); + } + + /** + * When_invoke_get_result. + * + * @param methodName the method name + * @param resultName the result name + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + @When("^I invoke \"([^\"]*)\" I get the result into \"([^\"]*)\"$") + public void when_invoke_get_result(String methodName, String resultName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + objects.put(resultName, when_invoke(methodName)); + } + + /** + * When_invoke. + * + * @param methodName the method name + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + @When("^I invoke \"([^\"]*)\"$") + public Object when_invoke(String methodName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + String[] parts = methodName.split("\\."); + Object object = getObject(parts); + + Method method = object.getClass().getMethod(TextUtility.ToCamelCase(parts[parts.length - 1])); + return method.invoke(object); + } + + /** + * When_invoke_with_parameter_values. + * + * @param methodName the method name + * @param parameter1 the parameter1 + * @param parameter1Type the parameter1 type + * @param parameter2 the parameter2 + * @param parameter2Type the parameter2 type + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + public Object when_invoke_with_parameter_values(String methodName, Object parameter1, String parameter1Type, Object parameter2, String parameter2Type) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = methodName.split("\\."); + Object object = getObject(parts); + + Method method = object.getClass().getMethod(TextUtility.ToCamelCase(parts[parts.length - 1]), TextUtility.getJavaType(parameter1Type), TextUtility.getJavaType(parameter2Type)); + return method.invoke(object, parameter1, parameter2); + } + + public Object when_invoke_with_parameter_values(String methodName, Object parameter1, String parameter1Type, Object parameter2, String parameter2Type, Object parameter3, String parameter3Type) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = methodName.split("\\."); + Object object = getObject(parts); + + Method method = object.getClass().getMethod(TextUtility.ToCamelCase(parts[parts.length - 1]), TextUtility.getJavaType(parameter1Type), TextUtility.getJavaType(parameter2Type), TextUtility.getJavaType(parameter3Type)); + return method.invoke(object, parameter1, parameter2, parameter3); + } + + /** + * When_invoke_with_parameter_values_string. + * + * @param methodName the method name + * @param parameter1 the parameter1 + * @param parameter1Type the parameter1 type + * @param parameter2 the parameter2 + * @param parameter2Type the parameter2 type + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameter values \"([^\"]*)\" of type \"([^\"]*)\" and \"([^\"]*)\" of type \"([^\"]*)\"$") + public Object when_invoke_with_parameter_values_string(String methodName, String parameter1, String parameter1Type, String parameter2, String parameter2Type) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + return when_invoke_with_parameter_values(methodName, TextUtility.convertStringTo(parameter1, parameter1Type), parameter1Type, TextUtility.convertStringTo(parameter2, parameter2Type), parameter2Type); + } + + /** + * When_invoke_with_parameter_value. + * + * @param methodName the method name + * @param parameterValue the parameter value + * @param parameterType the parameter type + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameter value \"([^\"]*)\" of type \"([^\"]*)\"$") + public Object when_invoke_with_parameter_value(String methodName, String parameterValue, String parameterType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + return when_invoke_with_parameter_converted_value(methodName, TextUtility.convertStringTo(parameterValue, parameterType), parameterType); + } + + /** + * When_invoke_with_parameter_converted_value. + * + * @param methodName the method name + * @param parameterValue the parameter value + * @param parameterType the parameter type + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + public Object when_invoke_with_parameter_converted_value(String methodName, Object parameterValue, String parameterType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts = methodName.split("\\."); + Object object = getObject(parts); + + Method method = object.getClass().getMethod(TextUtility.ToCamelCase(parts[parts.length - 1]), TextUtility.getJavaType(parameterType)); + return method.invoke(object, parameterValue); + } + + /** + * When_invoke_with_parameter. + * + * @param methodName the method name + * @param parameterName the parameter name + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameter \"([^\"]*)\"$") + public Object when_invoke_with_parameter(String methodName, String parameterName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + Object parameter = objects.get(parameterName); + return when_invoke_with_parameter_converted_value(methodName, parameter, parameter.getClass().getName()); + } + + /** + * When_invoke_with_parameter. + * + * @param methodName the method name + * @param parameter1Name the parameter1 name + * @param parameter2Name the parameter2 name + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameters \"([^\"]*)\" and \"([^\"]*)\"$") + public Object when_invoke_with_parameter(String methodName, String parameter1Name, String parameter2Name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts1 = parameter1Name.split("\\."); + Object parameter1 = getObject(parts1); + + String[] parts2 = parameter2Name.split("\\."); + Object parameter2 = getObject(parts2); + + return when_invoke_with_parameter_values(methodName, parameter1, parameter1.getClass().getName(), parameter2, parameter2.getClass().getName()); + } + + /** + * When_invoke_with_parameter. + * + * @param methodName the method name + * @param parameter1Name the parameter1 name + * @param parameter2Name the parameter2 name + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameters \"([^\"]*)\" and \"([^\"]*)\" and \"([^\"]*)\"$") + public Object when_invoke_with_parameter(String methodName, String parameter1Name, String parameter2Name, String parameter3Name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + String[] parts1 = parameter1Name.split("\\."); + Object parameter1 = getObject(parts1); + + String[] parts2 = parameter2Name.split("\\."); + Object parameter2 = getObject(parts2); + + String[] parts3 = parameter3Name.split("\\."); + Object parameter3 = getObject(parts3); + + return when_invoke_with_parameter_values(methodName, parameter1, parameter1.getClass().getName(), parameter2, parameter2.getClass().getName(), parameter3, parameter3.getClass().getName()); + } + + /** + * When_invoke_with_parameters_get_result. + * + * @param methodName the method name + * @param parameter1Name the parameter1 name + * @param parameter2Name the parameter2 name + * @param resultName the result name + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @When("^I invoke \"([^\"]*)\" with parameters \"([^\"]*)\" and \"([^\"]*)\" I get the result into \"([^\"]*)\"$") + public void when_invoke_with_parameters_get_result(String methodName, String parameter1Name, String parameter2Name, String resultName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + objects.put(resultName, when_invoke_with_parameter(methodName, parameter1Name, parameter2Name)); + } + + /** + * Then_invoke_with_parameter_of_type. + * + * @param methodName the method name + * @param parameter the parameter + * @param parameterType the parameter type + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws SecurityException the security exception + * @throws ClassNotFoundException the class not found exception + */ + @Then("^invoke \"([^\"]*)\" with parameter \"([^\"]*)\" of type \"([^\"]*)\"$") + public Object then_invoke_with_parameter_of_type(String methodName, Object parameter, String parameterType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, SecurityException, ClassNotFoundException { + String[] parts = methodName.split("\\."); + Object object = getObject(parts); + Object parameterObject = objects.get(parameter); + Method method = object.getClass().getMethod(TextUtility.ToCamelCase(parts[parts.length - 1]), TextUtility.getJavaType(parameterType)); + return method.invoke(object, parameterObject); + } + + /** + * Then_invoke_with_parameter_value. + * + * @param methodName the method name + * @param parameter the parameter + * @param parameterType the parameter type + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @Then("^invoke \"([^\"]*)\" with parameter value \"([^\"]*)\" of type \"([^\"]*)\"$") + public Object then_invoke_with_parameter_value(String methodName, Object parameter, String parameterType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + return when_invoke_with_parameter_converted_value(methodName, parameter, parameterType); + } + + /** + * I_invoke_with_parameter_values_of_type_and_of_type_ i_get_the_result_into. + * + * @param methodName the method name + * @param parameter1 the parameter1 + * @param parameter1Type the parameter1 type + * @param parameter2 the parameter2 + * @param parameter2Type the parameter2 type + * @param resultName the result name + * @throws Throwable the throwable + */ + @When("^I invoke \"([^\"]*)\" with parameter values \"([^\"]*)\" of type \"([^\"]*)\" and \"([^\"]*)\" of type \"([^\"]*)\" I get the result into \"([^\"]*)\"$") + public void I_invoke_with_parameter_values_of_type_and_of_type_I_get_the_result_into(String methodName, String parameter1, String parameter1Type, String parameter2, String parameter2Type, String resultName) throws Throwable { + objects.put(resultName, when_invoke_with_parameter_values(methodName, TextUtility.convertStringTo(parameter1, parameter1Type), parameter1Type, TextUtility.convertStringTo(parameter2, parameter2Type), parameter2Type)); + } + + /** + * Then_invoke_with_parameter_values. + * + * @param methodName the method name + * @param parameter1 the parameter1 + * @param parameter1Type the parameter1 type + * @param parameter2 the parameter2 + * @param parameter2Type the parameter2 type + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + */ + @Then("^invoke \"([^\"]*)\" with parameter values \"([^\"]*)\" of type \"([^\"]*)\" and \"([^\"]*)\" of type \"([^\"]*)\"$") + public Object then_invoke_with_parameter_values(String methodName, Object parameter1, String parameter1Type, Object parameter2, String parameter2Type) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException { + return when_invoke_with_parameter_values(methodName, parameter1, parameter1Type, parameter2, parameter2Type); + } + + /** + * Gets the object. + * + * @param parts the parts + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + private Object getObject(String[] parts) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + if (objects.containsKey(parts[0])) { + Object object = objects.get(parts[0]); + + String[] memberParts = Arrays.copyOfRange(parts, 1, parts.length); + return getObject(object, memberParts); + } + + return null; + } + + /** + * Gets the object. + * + * @param parent the parent + * @param parts the parts + * @return the object + * @throws NoSuchMethodException the no such method exception + * @throws InvocationTargetException the invocation target exception + * @throws IllegalAccessException the illegal access exception + */ + private Object getObject(Object parent, String[] parts) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + for (int i = 0; i < (parts.length - 1); i++) { + if (parts[i].endsWith("]")) { + String propertyName = parts[i].substring(0, parts[i].lastIndexOf("[")); + Method method = parent.getClass().getMethod("get" + TextUtility.ToPascalCase(propertyName)); + parent = method.invoke(parent); + + int index = Integer.parseInt(parts[i].substring(parts[i].lastIndexOf("[") + 1, parts[i].length() - 1)); + Method indexMethod = parent.getClass().getMethod("get", int.class); + parent = indexMethod.invoke(parent, index); + } + else { + Method method = parent.getClass().getMethod("get" + TextUtility.ToPascalCase(parts[i])); + parent = method.invoke(parent); + } + } + + return parent; + } + + /** + * Creates the configuration. + * + * @return the configuration + * @throws Exception the exception + */ + protected static Configuration createConfiguration() throws Exception { + String baseUri = System.getenv(ManagementConfiguration.URI); + return ManagementConfiguration.configure( + baseUri != null ? new URI(baseUri) : null, + System.getenv(ManagementConfiguration.SUBSCRIPTION_ID), + System.getenv(ManagementConfiguration.KEYSTORE_PATH), + System.getenv(ManagementConfiguration.KEYSTORE_PASSWORD), + KeyStoreType.fromString(System.getenv(ManagementConfiguration.KEYSTORE_TYPE)) + ); + } +} \ No newline at end of file diff --git a/core-test/src/test/java/com/microsoft/windowsazure/RunCukesTest.java b/core-test/src/test/java/com/microsoft/windowsazure/RunCukesTest.java new file mode 100644 index 0000000000000..e6f4dd10363d3 --- /dev/null +++ b/core-test/src/test/java/com/microsoft/windowsazure/RunCukesTest.java @@ -0,0 +1,26 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure; + +import cucumber.api.junit.Cucumber; +import cucumber.api.CucumberOptions; + +import org.junit.runner.RunWith; + +@RunWith(Cucumber.class) +@CucumberOptions(format = {"html:target/cucumber-html-report", "json:target/cucumber-json-report.json"}) +public class RunCukesTest { +} \ No newline at end of file diff --git a/core-test/src/test/java/com/microsoft/windowsazure/TextUtility.java b/core-test/src/test/java/com/microsoft/windowsazure/TextUtility.java new file mode 100644 index 0000000000000..91b823482ea2d --- /dev/null +++ b/core-test/src/test/java/com/microsoft/windowsazure/TextUtility.java @@ -0,0 +1,105 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Calendar; + +import javax.xml.bind.DatatypeConverter; + +import com.microsoft.windowsazure.management.websites.models.WebSiteCreateParameters; + +public final class TextUtility +{ + public static String ToPascalCase(String input) + { + return input.substring(0, 1).toUpperCase() + + input.substring(1); + } + + public static String ToCamelCase(String input) + { + return input.substring(0, 1).toLowerCase() + + input.substring(1); + } + + public static Object convertStringTo(String input, String type) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException + { + if (input.equals("null")) + { + return null; + } + + if (type.equals("System.Int32")) + { + return DatatypeConverter.parseInt(input); + } + else if (type.equals("System.String")) + { + return input; + } + else if (type.equals("System.DateTime")) + { + if (input.equals("DateTime.Now")) + { + return Calendar.getInstance(); + } + + return DatatypeConverter.parseDateTime(input); + } + else if (Enum.class.isAssignableFrom(getJavaType(type))) + { + Class enumType = getJavaType(type); + Method method = enumType.getMethod("valueOf", String.class); + return method.invoke(null, input); + } + else + { + throw new UnsupportedOperationException(); + } + } + + public static Class getJavaType(String csharpType) throws ClassNotFoundException + { + if (csharpType.equals("System.Int32")) + { + return int.class; + } + else if (csharpType.equals("System.String")) + { + return String.class; + } + else if (csharpType.equals("System.DateTime")) + { + return Calendar.class; + } + else if (csharpType.equals("Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteCreateParameters.WebSpaceDetails")) + { + return WebSiteCreateParameters.WebSpaceDetails.class; + } + else + { + return Class.forName(csharpType + .replace("Microsoft.WindowsAzure.Management", + "com.microsoft.windowsazure.management") + .replace(".Models", ".models") + .replace(".WebSites.", ".websites.") + .replace(".Sql.", ".sql.") + .replace(".Storage.", ".storage.")); + } + } +} diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/affinitygroups.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/affinitygroups.feature new file mode 100644 index 0000000000000..19529d7726e4a --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/affinitygroups.feature @@ -0,0 +1,41 @@ +Feature: Affinity groups should work + +Background: + Given I create a "ManagementClient" with name "management" + +Scenario: Create an AffinityGroup + Given I create a "Microsoft.WindowsAzure.Management.Models.AffinityGroupCreateParameters" with name "parameters" + And I create a "10" character random String with name "testAffinityGroupName1" and prefix "azure-java-test-" + And set "parameters.Name" with "testAffinityGroupName1" of type "System.String" + And set "parameters.Location" with value "West US" of type "System.String" + And set "parameters.Label" with value "Great AF" of type "System.String" + When I invoke "management.AffinityGroupsOperations.Create" with parameter "parameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "201" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + Then invoke "management.AffinityGroupsOperations.Delete" with parameter "testAffinityGroupName1" of type "System.String" + +Scenario: Get an AffinityGroup + Given I create a "Microsoft.WindowsAzure.Management.Models.AffinityGroupCreateParameters" with name "parameters" + And I create a "10" character random String with name "testAffinityGroupName2" and prefix "azure-java-test-" + And set "parameters.Name" with "testAffinityGroupName2" of type "System.String" + And set "parameters.Location" with value "West US" of type "System.String" + And set "parameters.Label" with value "Great AF2" of type "System.String" + And I invoke "management.AffinityGroupsOperations.Create" with parameter "parameters" + When I invoke "management.AffinityGroupsOperations.Get" with parameter value "AF2" of type "System.String" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + Then invoke "management.AffinityGroupsOperations.Delete" with parameter "testAffinityGroupName2" of type "System.String" + +Scenario: List AffinityGroups + Given I create a "Microsoft.WindowsAzure.Management.Models.AffinityGroupCreateParameters" with name "parameters" + And I create a "10" character random String with name "testAffinityGroupName3" and prefix "azure-java-test-" + And set "parameters.Name" with "testAffinityGroupName3" of type "System.String" + And set "parameters.Location" with value "West US" of type "System.String" + And set "parameters.Label" with value "Great AF3" of type "System.String" + And I invoke "management.AffinityGroupsOperations.Create" with parameter "parameters" + When I invoke "management.AffinityGroupsOperations.List" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element" with value from list "operationResponse.AffinityGroups" where "Name" of type "System.String" equals "AF3" + And property with type "System.String" and path "element.Name" should equal "AF3" + Then invoke "management.AffinityGroupsOperations.Delete" with parameter "testAffinityGroupName3" of type "System.String" \ No newline at end of file diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/certificates.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/certificates.feature new file mode 100644 index 0000000000000..7db12600fc7b0 --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/certificates.feature @@ -0,0 +1,9 @@ +Feature: Management Certificates should work + +Background: + Given I create a "ManagementClient" with name "management" + +Scenario: Get a Certificate + When I invoke "management.ManagementCertificatesOperations.Get" with parameter value "00EC75B90F4F59F172C3C321C150FE7E79FC29AB" of type "System.String" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" \ No newline at end of file diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/locations.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/locations.feature new file mode 100644 index 0000000000000..5ecef17e5660f --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/locations.feature @@ -0,0 +1,13 @@ +Feature: Locations should work + +Background: + Given I create a "ManagementClient" with name "management" + +Scenario: List Locations + When I invoke "management.LocationsOperations.List" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element1" with value from list "operationResponse.Locations" where "Name" of type "System.String" equals "Southeast Asia" + And property with type "System.String" and path "element1.Name" should equal "Southeast Asia" + And set "element2" with value from list "operationResponse.Locations" where "Name" of type "System.String" equals "East Asia" + And property with type "System.String" and path "element2.Name" should equal "East Asia" \ No newline at end of file diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/sql/sql.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/sql/sql.feature new file mode 100644 index 0000000000000..bc9a155ae557f --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/sql/sql.feature @@ -0,0 +1,47 @@ +Feature: SqlServer should work + +Background: + Given I create a "SqlManagementClient" with name "management" + +Scenario: Create SQL Server + Given I create a "Microsoft.WindowsAzure.Management.Sql.Models.ServerCreateParameters" with name "parameters" + And set "parameters.Location" with value "West US" of type "System.String" + And set "parameters.AdministratorPassword" with value "TestPassword12!" of type "System.String" + And set "parameters.AdministratorUserName" with value "testadministrator" of type "System.String" + And I invoke "management.ServersOperations.Create" with parameter "parameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "201" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + +Scenario: List SQL Server + When I invoke "management.ServersOperations.List" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element1" with value from list "operationResponse.Servers" where "Location" of type "System.String" equals "West US" + +Scenario: Create SQL Database + Given I invoke "management.ServersOperations.List" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element1" with value from list "operationResponse.Servers" where "Location" of type "System.String" equals "West US" + And set "serverName" with value from path "element1.Name" of type "System.String" + When I create a "Microsoft.WindowsAzure.Management.Sql.Models.DatabaseCreateParameters" with name "parameters" + And set "parameters.MaximumDatabaseSizeInGB" with value "1" of type "System.Int32" + And set "parameters.Name" with value "expecteddatabasename" of type "System.String" + And set "parameters.CollationName" with value "SQL_Latin1_General_CP1_CI_AS" of type "System.String" + And set "parameters.Edition" with value "Web" of type "System.String" + And I invoke "management.DatabasesOperations.Create" with parameters "serverName" and "parameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "201" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + +Scenario: Delete SQL Server + Given I invoke "management.ServersOperations.List" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element1" with value from list "operationResponse.Servers" where "Location" of type "System.String" equals "West US" + And set "serverName" with value from path "element1.Name" of type "System.String" + And I create a "System.String" with name "param1" + And set "param1" with value "expecteddatabasename" of type "System.String" + When I invoke "management.DatabasesOperations.Delete" with parameters "serverName" and "param1" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + \ No newline at end of file diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/storage/storageservice.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/storage/storageservice.feature new file mode 100644 index 0000000000000..647a063286ce6 --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/storage/storageservice.feature @@ -0,0 +1,40 @@ +Feature: Managing Storage accounts + +Background: + Given I create a "StorageManagementClient" with name "management" + +Scenario: Create, List and Delete a storage account + Given I create a "Microsoft.WindowsAzure.Management.Storage.Models.StorageAccountCreateParameters" with name "parameters" + And I create a "10" character random String with name "testStorageAccountName1" and prefix "azurejavatest" + And set "parameters.Name" with "testStorageAccountName1" of type "System.String" + And set "parameters.Location" with value "West US" of type "System.String" + And set "parameters.Description" with value "Hi there" of type "System.String" + And set "parameters.Label" with value "Great St account" of type "System.String" + When I invoke "management.StorageAccountsOperations.Create" with parameter "parameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + +Scenario: List a storage account + Given I create a "Microsoft.WindowsAzure.Management.Storage.Models.StorageAccountCreateParameters" with name "parameters" + And I create a "10" character random String with name "testStorageAccountName2" and prefix "azurejavatest" + And set "parameters.Name" with "testStorageAccountName2" of type "System.String" + And set "parameters.Location" with value "West US" of type "System.String" + And set "parameters.Description" with value "Hi there" of type "System.String" + And set "parameters.Label" with value "Great St account" of type "System.String" + When I invoke "management.StorageAccountsOperations.Create" with parameter "parameters" I get the result into "operationResponse" + When I invoke "management.StorageAccountsOperations.List" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element" with value from list "operationResponse.StorageAccounts" where "Name" of type "System.String" equals parameter "testStorageAccountName2" + And property with type "System.String" and path "element.Name" should equal parameter "testStorageAccountName2" + +Scenario: Delete storage account + Given I create a "Microsoft.WindowsAzure.Management.Storage.Models.StorageAccountCreateParameters" with name "parameters" + And I create a "10" character random String with name "testStorageAccountName3" and prefix "azurejavatest" + And set "parameters.Name" with "testStorageAccountName3" of type "System.String" + And set "parameters.Location" with value "West US" of type "System.String" + And set "parameters.Description" with value "Hi there" of type "System.String" + And set "parameters.Label" with value "Great St account" of type "System.String" + When I invoke "management.StorageAccountsOperations.Create" with parameter "parameters" I get the result into "operationResponse" + When I invoke "management.StorageAccountsOperations.Delete" with parameter "testStorageAccountName3" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" \ No newline at end of file diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/subscriptions.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/subscriptions.feature new file mode 100644 index 0000000000000..2ae1bfb73b821 --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/subscriptions.feature @@ -0,0 +1,12 @@ +Feature: Subscriptions should work + +Background: + Given I create a "ManagementClient" with name "management" + +Scenario: List subscription operations with start and end time + Given I create a "Microsoft.WindowsAzure.Management.Models.SubscriptionListOperationsParameters" with name "parameters" + And set "parameters.StartTime" with value "DateTime.Now" of type "System.DateTime" + And set "parameters.EndTime" with value "DateTime.Now" of type "System.DateTime" + When I invoke "management.SubscriptionsOperations.ListOperations" with parameter "parameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" \ No newline at end of file diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/serverfarm.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/serverfarm.feature new file mode 100644 index 0000000000000..68fd521b64f6e --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/serverfarm.feature @@ -0,0 +1,24 @@ +Feature: ServerFarm should work + +Background: + Given I create a "WebSiteManagementClient" with name "management" + +Scenario: Create Server Farm + Given I create a "Microsoft.WindowsAzure.Management.WebSites.Models.ServerFarmCreateParameters" with name "parameters" + And set "parameters.NumberOfWorkers" with value "1" of type "System.Int32" + And set "parameters.WorkerSize" with value "Small" of type "Microsoft.WindowsAzure.Management.WebSites.Models.ServerFarmWorkerSize" + And I create a "System.String" with name "param1" + And set "param1" with value "eastuswebspace" of type "System.String" + And I invoke "management.ServerFarmsOperations.Create" with parameters "param1" and "parameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + +Scenario: List Server Farm + When I invoke "management.ServerFarmsOperations.List" with parameter value "eastuswebspace" of type "System.String" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + +Scenario: Delete Server Farm + When I invoke "management.ServerFarmsOperations.Delete" with parameter value "eastuswebspace" of type "System.String" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/website.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/website.feature new file mode 100644 index 0000000000000..af11ca684520f --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/website.feature @@ -0,0 +1,40 @@ +Feature: WebSite should work + +Background: + Given I create a "WebSiteManagementClient" with name "management" + +Scenario: Create WebSite + Given I create a "Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteCreateParameters" with name "parameters" + And set "webspace" with value "eastuswebspace" of type "System.String" + And I create a "10" character random String with name "testWebSiteName1" and prefix "azurejavatest" + And set "parameters.Name" with "testWebSiteName1" of type "System.String" + And set "parameters.WebSpaceName" with value "eastuswebspace" of type "System.String" + And I create a "Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteCreateParameters.WebSpaceDetails" with name "webSpaceObj" + And set "webSpaceObj.Name" with value "eastuswebspace" of type "System.String" + And set "webSpaceObj.GeoRegion" with value "East US" of type "System.String" + And set "webSpaceObj.Plan" with value "VirtualDedicatedPlan" of type "System.String" + And set "parameters.WebSpace" with "webSpaceObj" of type "Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteCreateParameters.WebSpaceDetails" + And I create a "System.String" with name "param1" + And set "param1" with value "eastuswebspace" of type "System.String" + And I invoke "management.WebSitesOperations.Create" with parameters "param1" and "parameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And I create a "Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteDeleteParameters" with name "deleteParameters" + When I invoke "management.WebSitesOperations.Delete" with parameters "webspace" and "testWebSiteName1" and "deleteParameters" + +Scenario: List websites + When I invoke "management.WebSpacesOperations.ListWebSites" with parameter values "eastuswebspace" of type "System.String" and "null" of type "Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteListParameters" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element1" with value from list "operationResponse.WebSites" where "Name" of type "System.String" equals "newtstsite" + And property with type "System.String" and path "element1.Name" should equal "newtstsite" + +Scenario: Create repository + When I invoke "management.WebSitesOperations.CreateRepository" with parameter values "eastuswebspace" of type "System.String" and "newtstsite" of type "System.String" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + +Scenario: Generate password + When I invoke "management.WebSitesOperations.GeneratePassword" with parameter values "eastuswebspace" of type "System.String" and "newtstsite" of type "System.String" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" diff --git a/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/webspace.feature b/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/webspace.feature new file mode 100644 index 0000000000000..4e27290d5efbd --- /dev/null +++ b/core-test/src/test/resources/com/microsoft/windowsazure/management/websites/webspace.feature @@ -0,0 +1,12 @@ +Feature: WebSpace should work + +Background: + Given I create a "WebSiteManagementClient" with name "management" + +Scenario: List webspaces + When I invoke "management.WebSpacesOperations.List" I get the result into "operationResponse" + Then property with type "System.Int32" and path "operationResponse.StatusCode" should equal "200" + And property with type "System.String" and path "operationResponse.RequestId" should not equal "null" + And set "element1" with value from list "operationResponse.WebSpaces" where "GeoRegion" of type "System.String" equals "East US" + And property with type "System.String" and path "element1.GeoRegion" should equal "East US" + And property with type "System.String" and path "element1.Name" should equal "destanko-EastUSwebspace" diff --git a/core/pom.xml b/core/pom.xml new file mode 100644 index 0000000000000..16ca199a30500 --- /dev/null +++ b/core/pom.xml @@ -0,0 +1,223 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-core + jar + + Microsoft Azure Core Client API + API for Microsoft Azure Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + + + + microsoft + Microsoft + + + + + + org.apache.httpcomponents + httpclient + + + javax.xml.bind + jaxb-api + provided + + + javax.mail + mail + + + javax.inject + javax.inject + + + com.sun.jersey + jersey-client + + + com.sun.jersey + jersey-json + + + org.bouncycastle + bcprov-jdk16 + + + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+ + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.apache.maven.plugins + maven-help-plugin + [2.1.1,) + + evaluate + + + + + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.4.3 + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + **/Test*.java + **/*Test.java + **/*Tests.java + **/*TestCase.java + + + + + +
+ + + + org.codehaus.mojo + emma-maven-plugin + 1.0-alpha-3 + true + + + org.codehaus.mojo + surefire-report-maven-plugin + 2.0-beta-1 + true + + + +
diff --git a/core/src/main/java/com/microsoft/windowsazure/Configuration.java b/core/src/main/java/com/microsoft/windowsazure/Configuration.java new file mode 100644 index 0000000000000..101722a62328f --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/Configuration.java @@ -0,0 +1,135 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.DefaultBuilder; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class Configuration { + /** + * Property name for socket connection timeout used by services created with + * this configuration. + */ + public static final String PROPERTY_CONNECT_TIMEOUT = "com.microsoft.windowsazure.Configuration.connectTimeout"; + + /** + * Property name for socket read timeout used by services created with this + * configuration. + */ + public static final String PROPERTY_READ_TIMEOUT = "com.microsoft.windowsazure.Configuration.readTimeout"; + + /** + * Property name to control if HTTP logging to console is on or off. If + * property is set, logging is on, regardless of value. + */ + public static final String PROPERTY_LOG_HTTP_REQUESTS = "com.microsoft.windowsazure.Configuration.logHttpRequests"; + + /** + * The configuration instance. + */ + private static Configuration instance; + + /** + * The configuration properties. + */ + private final Map properties; + + /** + * The builder. + */ + private final Builder builder; + + private static Log log = LogFactory.getLog(Configuration.class); + + public Configuration() { + this.properties = new HashMap(); + this.builder = DefaultBuilder.create(); + } + + public Configuration(Builder builder) { + this.properties = new HashMap(); + this.builder = builder; + } + + public static Configuration getInstance() { + if (instance == null) { + try { + instance = Configuration.load(); + } catch (IOException e) { + log.error( + "Unable to load META-INF/com.microsoft.windowsazure.properties", + e); + instance = new Configuration(); + } + } + return instance; + } + + public static void setInstance(final Configuration configuration) { + Configuration.instance = configuration; + } + + public static Configuration load() throws IOException { + final Configuration config = new Configuration(); + + final InputStream stream = Thread + .currentThread() + .getContextClassLoader() + .getResourceAsStream( + "META-INF/com.microsoft.windowsazure.properties"); + if (stream != null) { + final Properties properties = new Properties(); + properties.load(stream); + for (Map.Entry key : properties.entrySet()) { + config.setProperty(key.getKey().toString(), key.getValue()); + } + } + + return config; + } + + public T create(Class service) { + return builder.build("", service, service, properties); + } + + public T create(String profile, Class service) { + return builder.build(profile, service, service, properties); + } + + public Builder getBuilder() { + return builder; + } + + public Object getProperty(String name) { + return properties.get(name); + } + + public void setProperty(String name, Object value) { + properties.put(name, value); + } + + public Map getProperties() { + return properties; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ConfigurationException.java b/core/src/main/java/com/microsoft/windowsazure/ConfigurationException.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ConfigurationException.java rename to core/src/main/java/com/microsoft/windowsazure/ConfigurationException.java index b1787a6663277..5ff9a673a09d8 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ConfigurationException.java +++ b/core/src/main/java/com/microsoft/windowsazure/ConfigurationException.java @@ -12,7 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core; + +package com.microsoft.windowsazure; public class ConfigurationException extends RuntimeException { @@ -32,5 +33,4 @@ public ConfigurationException(Throwable cause) { public ConfigurationException(String message, Throwable cause) { super(message, cause); } - } diff --git a/core/src/main/java/com/microsoft/windowsazure/core/Builder.java b/core/src/main/java/com/microsoft/windowsazure/core/Builder.java new file mode 100644 index 0000000000000..b9b1607be79b4 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/Builder.java @@ -0,0 +1,48 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core; + +import java.util.Map; + +public interface Builder { + + T build(String profile, Class service, Class instance, + Map properties); + + public interface Factory { + T create(String profile, Class service, Builder builder, + Map properties); + } + + public interface Alteration { + T alter(String profile, T instance, Builder builder, + Map properties); + } + + public interface Registry { + Registry add(Class service); + + Registry add(Class service, Class implementation); + + Registry add(Factory factory); + + void alter(Class service, Class instance, + Alteration alteration); + } + + public interface Exports { + void register(Registry registry); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/DefaultBuilder.java b/core/src/main/java/com/microsoft/windowsazure/core/DefaultBuilder.java new file mode 100644 index 0000000000000..a48e58d34e976 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/DefaultBuilder.java @@ -0,0 +1,230 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core; + +import com.microsoft.windowsazure.ConfigurationException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; + +import javax.inject.Inject; +import javax.inject.Named; + +public class DefaultBuilder implements Builder, Builder.Registry { + private Map, Factory> factories; + private Map, Map, List>>> alterations; + + public DefaultBuilder() { + factories = new HashMap, Factory>(); + alterations = new HashMap, Map, List>>>(); + } + + public static DefaultBuilder create() { + DefaultBuilder builder = new DefaultBuilder(); + + for (Builder.Exports exports : ServiceLoader + .load(Builder.Exports.class)) { + exports.register(builder); + } + + return builder; + } + + void addFactory(Class service, Factory factory) { + factories.put(service, factory); + } + + @Override + public Builder.Registry add(Class service) { + return add(service, service); + } + + Constructor findInjectConstructor(Class implementation) { + + Constructor withInject = null; + Constructor withoutInject = null; + int count = 0; + + for (Constructor ctor : implementation.getConstructors()) { + if (ctor.getAnnotation(Inject.class) != null) { + if (withInject != null) { + throw new RuntimeException( + "Class must not have multple @Inject annotations: " + + implementation.getName()); + } + withInject = ctor; + } else { + ++count; + withoutInject = ctor; + } + } + if (withInject != null) { + return withInject; + } + if (count != 1) { + throw new RuntimeException( + "Class without @Inject annotation must have one constructor: " + + implementation.getName()); + } + return withoutInject; + } + + @Override + public Builder.Registry add(Class service, + final Class implementation) { + final Constructor ctor = findInjectConstructor(implementation); + final Class[] parameterTypes = ctor.getParameterTypes(); + final Annotation[][] parameterAnnotations = ctor + .getParameterAnnotations(); + + addFactory(service, new Builder.Factory() { + @Override + @SuppressWarnings("unchecked") + public T create(String profile, Class service, + Builder builder, Map properties) { + Object[] initializationArguments = new Object[parameterTypes.length]; + for (int i = 0; i != parameterTypes.length; ++i) { + + boolean located = false; + + String named = findNamedAnnotation(parameterAnnotations[i]); + String fullName = dotCombine(profile, named); + + boolean probeProperties = fullName != null + && fullName != ""; + int startingIndex = 0; + while (!located && probeProperties) { + String nameProbe = fullName.substring(startingIndex); + if (!located && named != null + && properties.containsKey(nameProbe)) { + located = true; + if (parameterTypes[i] == String.class) { + initializationArguments[i] = properties + .get(nameProbe); + } else { + initializationArguments[i] = builder.build(fullName, + service, parameterTypes[i], properties); + } + } else { + startingIndex = fullName + .indexOf('.', startingIndex) + 1; + if (startingIndex == 0) { + probeProperties = false; + } + } + } + + if (!located) { + located = true; + initializationArguments[i] = builder.build(fullName, + service, parameterTypes[i], properties); + } + } + + try { + return (T) ctor.newInstance(initializationArguments); + } catch (InstantiationException e) { + throw new ConfigurationException(e); + } catch (IllegalAccessException e) { + throw new ConfigurationException(e); + } catch (InvocationTargetException e) { + throw new ConfigurationException(e); + } + } + }); + return this; + } + + protected String dotCombine(String profile, String named) { + boolean noProfile = profile == null || profile.isEmpty(); + boolean noName = named == null || named.isEmpty(); + if (noName) { + return profile; + } + if (noProfile) { + return named; + } + + return profile + "." + named; + } + + protected String findNamedAnnotation(Annotation[] annotations) { + for (Annotation annotation : annotations) { + if (Named.class.isAssignableFrom(annotation.getClass())) { + return ((Named) annotation).value(); + } + } + return null; + } + + @Override + public Registry add(Factory factory) { + for (Type genericInterface : factory.getClass().getGenericInterfaces()) { + ParameterizedType parameterizedType = (ParameterizedType) genericInterface; + if (parameterizedType.getRawType().equals(Builder.Factory.class)) { + Type typeArgument = parameterizedType.getActualTypeArguments()[0]; + addFactory((Class) typeArgument, factory); + } + } + return this; + } + + @Override + @SuppressWarnings("unchecked") + public T build(String profile, Class service, + Class instanceClass, Map properties) { + Factory factory = (Factory) factories.get(instanceClass); + if (factory == null) { + throw new RuntimeException("Service or property not registered: " + + profile + " " + service.getName() + " " + instanceClass); + } + T instance = factory.create(profile, service, this, properties); + Map, List>> alterationMap = alterations + .get(service); + if (alterationMap != null) { + List> alterationList = alterationMap + .get(instanceClass); + if (alterationList != null) { + for (Alteration alteration : alterationList) { + instance = ((Alteration) alteration).alter(profile, + instance, this, properties); + } + } + } + return instance; + } + + @Override + public void alter(Class service, Class instance, + Alteration alteration) { + if (!this.alterations.containsKey(service)) { + this.alterations.put(service, + new HashMap, List>>()); + } + if (!this.alterations.get(service).containsKey(instance)) { + this.alterations.get(service).put(instance, + new ArrayList>()); + } + this.alterations.get(service).get(instance).add(alteration); + } + +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/FilterableService.java b/core/src/main/java/com/microsoft/windowsazure/core/FilterableService.java new file mode 100644 index 0000000000000..22f360f89f60a --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/FilterableService.java @@ -0,0 +1,28 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; + +public interface FilterableService { + T withRequestFilterFirst(ServiceRequestFilter serviceRequestFilter); + + T withRequestFilterLast(ServiceRequestFilter serviceRequestFilter); + + T withResponseFilterFirst(ServiceResponseFilter serviceResponseFilter); + + T withResponseFilterLast(ServiceResponseFilter serviceResponseFilter); +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ISO8601DateConverter.java b/core/src/main/java/com/microsoft/windowsazure/core/ISO8601DateConverter.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ISO8601DateConverter.java rename to core/src/main/java/com/microsoft/windowsazure/core/ISO8601DateConverter.java index 71d5bc3d4992f..1cbb0b4aaad12 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ISO8601DateConverter.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/ISO8601DateConverter.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core; +package com.microsoft.windowsazure.core; import java.text.DateFormat; import java.text.ParseException; @@ -26,43 +26,46 @@ * "not quite" ISO 8601 date time conversion routines */ public class ISO8601DateConverter { - // Note: because of the trailing "0000000", this is not quite ISO 8601 compatible + // Note: because of the trailing "0000000", this is not quite ISO 8601 + // compatible private static final String DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; private static final String SHORT_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; private static final String DATETIME_PATTERN_NO_S = "yyyy-MM-dd'T'HH:mm'Z'"; private static final String DATETIME_PATTERN_TO_DECIMAL = "yyyy-MM-dd'T'HH:mm:ss."; public String format(Date date) { - DateFormat iso8601Format = new SimpleDateFormat(DATETIME_PATTERN, Locale.US); + DateFormat iso8601Format = new SimpleDateFormat(DATETIME_PATTERN, + Locale.US); iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT")); return iso8601Format.format(date); } public String shortFormat(Date date) { - DateFormat iso8601Format = new SimpleDateFormat(SHORT_DATETIME_PATTERN, Locale.US); + DateFormat iso8601Format = new SimpleDateFormat(SHORT_DATETIME_PATTERN, + Locale.US); iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT")); return iso8601Format.format(date); } public Date parse(String date) throws ParseException { - if (date == null) + if (date == null) { return null; + } int length = date.length(); if (length == 17) { // [2012-01-04T23:21Z] length = 17 return parseDateFromString(date, DATETIME_PATTERN_NO_S); - } - else if (length == 20) { + } else if (length == 20) { // [2012-01-04T23:21:59Z] length = 20 return parseDateFromString(date, SHORT_DATETIME_PATTERN); - } - else if (length >= 22 && length <= 28) { + } else if (length >= 22 && length <= 28) { // [2012-01-04T23:21:59.1Z] length = 22 // [2012-01-04T23:21:59.1234567Z] length = 28 // Need to handle the milliseconds gently. - Date allExceptMilliseconds = parseDateFromString(date, DATETIME_PATTERN_TO_DECIMAL); + Date allExceptMilliseconds = parseDateFromString(date, + DATETIME_PATTERN_TO_DECIMAL); long timeWithSecondGranularity = allExceptMilliseconds.getTime(); // Decimal point is at 19 String secondDecimalString = date.substring(19, date.indexOf('Z')); @@ -72,14 +75,16 @@ else if (length >= 22 && length <= 28) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeInMS); return calendar.getTime(); - } - else { - throw new IllegalArgumentException(String.format("Invalid Date String: %s", date)); + } else { + throw new IllegalArgumentException(String.format( + "Invalid Date String: %s", date)); } } - private static Date parseDateFromString(final String value, final String pattern) throws ParseException { - DateFormat iso8601Format = new SimpleDateFormat(pattern, Locale.US); + private static Date parseDateFromString(final String value, + final String pattern) throws ParseException { + final DateFormat iso8601Format = new SimpleDateFormat(pattern, + Locale.US); iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT")); return iso8601Format.parse(value); } diff --git a/core/src/main/java/com/microsoft/windowsazure/core/OperationResponse.java b/core/src/main/java/com/microsoft/windowsazure/core/OperationResponse.java new file mode 100644 index 0000000000000..d1777f1c93014 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/OperationResponse.java @@ -0,0 +1,60 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core; + +public class OperationResponse { + private int httpStatusCode; + + /** + * Gets the HTTP status code for the request. + * + * @return The HTTP status code. + */ + public int getStatusCode() { + return this.httpStatusCode; + } + + /** + * Sets the HTTP status code for the request. + * + * @param httpStatusCode + * The HTTP status code. + */ + public void setStatusCode(int httpStatusCode) { + this.httpStatusCode = httpStatusCode; + } + + private String requestId; + + /** + * Gets the request identifier. + * + * @return The request identifier. + */ + public String getRequestId() { + return this.requestId; + } + + /** + * Sets the request identifier. + * + * @param requestId + * The request identifier. + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/OperationStatus.java b/core/src/main/java/com/microsoft/windowsazure/core/OperationStatus.java new file mode 100644 index 0000000000000..4413987861275 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/OperationStatus.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.windowsazure.core; + +/** + * The status of the asynchronous request. + */ +public enum OperationStatus { + /** + * The asynchronous request is in progress. + */ + InProgress, + + /** + * The asynchronous request succeeded. + */ + Succeeded, + + /** + * The asynchronous request failed. + */ + Failed, +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/OperationStatusResponse.java b/core/src/main/java/com/microsoft/windowsazure/core/OperationStatusResponse.java new file mode 100644 index 0000000000000..db2ff1c194043 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/OperationStatusResponse.java @@ -0,0 +1,171 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core; + +/** + * The response body contains the status of the specified asynchronous + * operation, indicating whether it has succeeded, is inprogress, or has failed. + * Note that this status is distinct from the HTTP status code returned for the + * Get Operation Status operation itself. If the asynchronous operation + * succeeded, the response body includes the HTTP status code for the successful + * request. If the asynchronous operation failed, the response body includes the + * HTTP status code for the failed request, and also includes error information + * regarding the failure. + */ +public class OperationStatusResponse extends OperationResponse { + private OperationStatusResponse.ErrorDetails error; + + /** + * If the asynchronous operation failed, the response body includes the HTTP + * status code for the failed request, and also includes error information + * regarding the failure. + * + * @return The Error value. + */ + public OperationStatusResponse.ErrorDetails getError() { + return this.error; + } + + /** + * If the asynchronous operation failed, the response body includes the HTTP + * status code for the failed request, and also includes error information + * regarding the failure. + * + * @param errorValue + * The Error value. + */ + public void setError(final OperationStatusResponse.ErrorDetails errorValue) { + this.error = errorValue; + } + + private Integer httpStatusCode; + + /** + * The HTTP status code for the asynchronous request. + * + * @return The HttpStatusCode value. + */ + public Integer getHttpStatusCode() { + return this.httpStatusCode; + } + + /** + * The HTTP status code for the asynchronous request. + * + * @param httpStatusCodeValue + * The HttpStatusCode value. + */ + public void setHttpStatusCode(final Integer httpStatusCodeValue) { + this.httpStatusCode = httpStatusCodeValue; + } + + private String id; + + /** + * The request ID of the asynchronous request. This value is returned in the + * x-ms-request-id response header of the asynchronous request. + * + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * The request ID of the asynchronous request. This value is returned in the + * x-ms-request-id response header of the asynchronous request. + * + * @param idValue + * The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private OperationStatus status; + + /** + * The status of the asynchronous request. + * + * @return The Status value. + */ + public OperationStatus getStatus() { + return this.status; + } + + /** + * The status of the asynchronous request. + * + * @param statusValue + * The Status value. + */ + public void setStatus(final OperationStatus statusValue) { + this.status = statusValue; + } + + /** + * If the asynchronous operation failed, the response body includes the HTTP + * status code for the failed request, and also includes error information + * regarding the failure. + */ + public static class ErrorDetails { + private String code; + + /** + * The management service error code returned if the asynchronous + * request failed. + * + * @return The Code value. + */ + public String getCode() { + return this.code; + } + + /** + * The management service error code returned if the asynchronous + * request failed. + * + * @param codeValue + * The Code value. + */ + public void setCode(final String codeValue) { + this.code = codeValue; + } + + private String message; + + /** + * The management service error message returned if the asynchronous + * request failed. + * + * @return The Message value. + */ + public String getMessage() { + return this.message; + } + + /** + * The management service error message returned if the asynchronous + * request failed. + * + * @param messageValue + * The Message value. + */ + public void setMessage(final String messageValue) { + this.message = messageValue; + } + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RFC1123DateAdapter.java b/core/src/main/java/com/microsoft/windowsazure/core/RFC1123DateAdapter.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RFC1123DateAdapter.java rename to core/src/main/java/com/microsoft/windowsazure/core/RFC1123DateAdapter.java index 559abd770daab..42796fa9d1690 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RFC1123DateAdapter.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/RFC1123DateAdapter.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core; +package com.microsoft.windowsazure.core; import java.util.Date; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RFC1123DateConverter.java b/core/src/main/java/com/microsoft/windowsazure/core/RFC1123DateConverter.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RFC1123DateConverter.java rename to core/src/main/java/com/microsoft/windowsazure/core/RFC1123DateConverter.java index 418a5782ba4b9..d2e2a84c66b5f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RFC1123DateConverter.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/RFC1123DateConverter.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core; +package com.microsoft.windowsazure.core; import java.text.DateFormat; import java.text.ParseException; @@ -34,15 +34,16 @@ public String format(Date date) { public Date parse(String date) { try { return getFormat().parse(date); - } - catch (ParseException e) { - String msg = String.format("The value \"%s\" is not a valid RFC 1123 date.", date); + } catch (ParseException e) { + String msg = String.format( + "The value \"%s\" is not a valid RFC 1123 date.", date); throw new IllegalArgumentException(msg, e); } } private DateFormat getFormat() { - DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, Locale.US); + DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, + Locale.US); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); return rfc1123Format; } diff --git a/core/src/main/java/com/microsoft/windowsazure/core/ServiceClient.java b/core/src/main/java/com/microsoft/windowsazure/core/ServiceClient.java new file mode 100644 index 0000000000000..d385a2757c58a --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/ServiceClient.java @@ -0,0 +1,108 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.apache.HttpRequestInterceptorAdapter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.apache.HttpResponseInterceptorAdapter; +import java.io.Closeable; +import java.io.IOException; +import java.util.concurrent.ExecutorService; + +import org.apache.http.HttpHost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; + +public abstract class ServiceClient implements + FilterableService, Closeable { + private final ExecutorService executorService; + + public ExecutorService getExecutorService() { + return this.executorService; + } + + private CloseableHttpClient httpClient; + + public CloseableHttpClient getHttpClient() { + if (this.httpClient == null) { + String proxyHost = System.getProperty("http.proxyHost"); + String proxyPort = System.getProperty("http.proxyPort"); + if ((proxyHost != null) && (proxyPort != null)) { + HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); + if (proxy != null) { + httpClientBuilder.setProxy(proxy); + } + } + + this.httpClient = httpClientBuilder.build(); + } + + return this.httpClient; + } + + private final HttpClientBuilder httpClientBuilder; + + protected ServiceClient(HttpClientBuilder httpClientBuilder, + ExecutorService executorService) { + this.httpClientBuilder = httpClientBuilder; + this.executorService = executorService; + } + + protected abstract TClient newInstance(HttpClientBuilder httpClientBuilder, + ExecutorService executorService); + + @Override + public TClient withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + httpClientBuilder + .addInterceptorFirst(new HttpRequestInterceptorAdapter( + serviceRequestFilter)); + return this.newInstance(httpClientBuilder, executorService); + } + + @Override + public TClient withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + httpClientBuilder.addInterceptorLast(new HttpRequestInterceptorAdapter( + serviceRequestFilter)); + return this.newInstance(httpClientBuilder, executorService); + } + + @Override + public TClient withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + httpClientBuilder + .addInterceptorFirst(new HttpResponseInterceptorAdapter( + serviceResponseFilter)); + return this.newInstance(httpClientBuilder, executorService); + } + + @Override + public TClient withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + httpClientBuilder + .addInterceptorLast(new HttpResponseInterceptorAdapter( + serviceResponseFilter)); + return this.newInstance(httpClientBuilder, executorService); + } + + @Override + public void close() throws IOException { + if (httpClient != null) { + httpClient.close(); + } + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/ServiceOperations.java b/core/src/main/java/com/microsoft/windowsazure/core/ServiceOperations.java new file mode 100644 index 0000000000000..6bc4b9fe6f3b1 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/ServiceOperations.java @@ -0,0 +1,19 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core; + +public interface ServiceOperations { + TClient getClient(); +} \ No newline at end of file diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceTimeoutException.java b/core/src/main/java/com/microsoft/windowsazure/core/ServiceTimeoutException.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceTimeoutException.java rename to core/src/main/java/com/microsoft/windowsazure/core/ServiceTimeoutException.java index 4e67f7b214622..9139a96512191 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceTimeoutException.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/ServiceTimeoutException.java @@ -13,7 +13,9 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.core; +package com.microsoft.windowsazure.core; + +import com.microsoft.windowsazure.exception.ServiceException; /** * Exception indicating a service operation has timed out. @@ -39,8 +41,8 @@ public ServiceTimeoutException(String message) { } /** - * Construct a ServiceTimeoutException instance with specified - * message and cause + * Construct a ServiceTimeoutException instance with specified message and + * cause * * @param message * Exception message diff --git a/core/src/main/java/com/microsoft/windowsazure/core/TimeSpan8601Converter.java b/core/src/main/java/com/microsoft/windowsazure/core/TimeSpan8601Converter.java new file mode 100644 index 0000000000000..a9c5b6e760725 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/TimeSpan8601Converter.java @@ -0,0 +1,38 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; + +public abstract class TimeSpan8601Converter { + public static String format(Duration duration) { + return duration.toString(); + } + + public static Duration parse(String duration) { + try { + DatatypeFactory factory = DatatypeFactory.newInstance(); + return factory.newDuration(duration); + } catch (DatatypeConfigurationException e) { + String msg = String.format( + "The value \"%s\" is not a valid ISO8601 duration.", + duration); + throw new IllegalArgumentException(msg, e); + } + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/UserAgentFilter.java b/core/src/main/java/com/microsoft/windowsazure/core/UserAgentFilter.java new file mode 100644 index 0000000000000..d56577de31d10 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/UserAgentFilter.java @@ -0,0 +1,96 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * The Class UserAgentFilter. + */ +public class UserAgentFilter implements ServiceRequestFilter { + + /** The azure SDK product token. */ + private static String azureSDKProductToken; + + /** + * Instantiates a new user agent filter. + */ + public UserAgentFilter() { + if ((azureSDKProductToken == null) || azureSDKProductToken.isEmpty()) { + azureSDKProductToken = createAzureSDKProductToken(); + } + } + + @Override + public void filter(ServiceRequestContext request) { + String userAgent; + + if (request.getHeader("User-Agent") != null) { + String currentUserAgent = request.getHeader("User-Agent"); + userAgent = azureSDKProductToken + " " + currentUserAgent; + request.removeHeader("User-Agent"); + } else { + userAgent = azureSDKProductToken; + } + + request.setHeader("User-Agent", userAgent); + } + + /** + * Creates the azure SDK product token. + * + * @return the string + */ + private String createAzureSDKProductToken() { + String version = getVersionFromResources(); + String productToken; + if ((version != null) && (!version.isEmpty())) { + productToken = "Azure-SDK-For-Java/" + version; + } else { + productToken = "Azure-SDK-For-Java"; + } + + return productToken; + } + + /** + * Gets the version of the SDK from resources. + * + * @return the version from resources + */ + private String getVersionFromResources() { + String version = "unknown"; + Properties properties = new Properties(); + try { + InputStream inputStream = getClass() + .getClassLoader() + .getResourceAsStream( + "META-INF/maven/com.microsoft.windowsazure/microsoft-windowsazure-api-core/pom.properties"); + if (inputStream != null) { + properties.load(inputStream); + version = properties.getProperty("version"); + inputStream.close(); + } + } catch (IOException e) { + // Do nothing + } + + return version; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/package.html b/core/src/main/java/com/microsoft/windowsazure/core/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/package.html rename to core/src/main/java/com/microsoft/windowsazure/core/package.html diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/Base64StringAdapter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/Base64StringAdapter.java similarity index 94% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/Base64StringAdapter.java rename to core/src/main/java/com/microsoft/windowsazure/core/pipeline/Base64StringAdapter.java index f9aedb2faf946..c682da78695a1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/Base64StringAdapter.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/Base64StringAdapter.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils.pipeline; +package com.microsoft.windowsazure.core.pipeline; import javax.xml.bind.annotation.adapters.XmlAdapter; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ConnectionStringField.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/ConnectionStringField.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ConnectionStringField.java rename to core/src/main/java/com/microsoft/windowsazure/core/pipeline/ConnectionStringField.java index ef773b7054655..2b98ac9305dde 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ConnectionStringField.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/ConnectionStringField.java @@ -13,21 +13,19 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils.pipeline; +package com.microsoft.windowsazure.core.pipeline; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** - * Annotation used to mark method setters to be used - * when the field name in the connection string isn't - * a valid Java method name. + * Annotation used to mark method setters to be used when the field name in the + * connection string isn't a valid Java method name. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ConnectionStringField { - public String name(); + String name(); } diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/PipelineHelpers.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/PipelineHelpers.java new file mode 100644 index 0000000000000..633bbbc6609a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/PipelineHelpers.java @@ -0,0 +1,156 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; +import com.microsoft.windowsazure.core.utils.AccessConditionHeaderType; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; + +public final class PipelineHelpers { + private PipelineHelpers() { + } + + private static String createErrorMessage(ClientResponse clientResponse) { + clientResponse.bufferEntity(); + String errorMessage = clientResponse.toString(); + if (clientResponse.hasEntity()) { + errorMessage = errorMessage + " " + + clientResponse.getEntity(String.class); + } + return errorMessage; + } + + public static void throwIfNotSuccess(ClientResponse clientResponse) { + int statusCode = clientResponse.getStatus(); + + if ((statusCode < 200) || (statusCode >= 300)) { + String errorMessage = createErrorMessage(clientResponse); + throw new UniformInterfaceException(errorMessage, clientResponse); + } + } + + public static void throwIfError(ClientResponse clientResponse) { + if (clientResponse.getStatus() >= 400) { + String errorMessage = createErrorMessage(clientResponse); + throw new UniformInterfaceException(errorMessage, clientResponse); + } + } + + public static WebResource addOptionalQueryParam(WebResource webResource, + String key, Object value) { + if (value != null) { + webResource = webResource.queryParam(key, value.toString()); + } + return webResource; + } + + public static WebResource addOptionalQueryParam(WebResource webResource, + String key, int value, int defaultValue) { + if (value != defaultValue) { + webResource = webResource.queryParam(key, Integer.toString(value)); + } + return webResource; + } + + public static Builder addOptionalHeader(Builder builder, String name, + Object value) { + if (value != null) { + builder = builder.header(name, value); + } + return builder; + } + + public static Builder addOptionalMetadataHeader(Builder builder, + Map metadata) { + for (Entry entry : metadata.entrySet()) { + builder = builder.header("x-ms-meta-" + entry.getKey(), + entry.getValue()); + } + return builder; + } + + public static Builder addOptionalRangeHeader(Builder builder, + Long rangeStart, Long rangeEnd) { + if (rangeStart != null) { + String range = rangeStart.toString() + "-"; + if (rangeEnd != null) { + range += rangeEnd.toString(); + } + builder = addOptionalHeader(builder, "Range", "bytes=" + range); + } + return builder; + } + + public static Builder addOptionalAccessConditionHeader(Builder builder, + AccessConditionHeader accessCondition) { + if (accessCondition != null) { + if (accessCondition.getHeader() != AccessConditionHeaderType.NONE) { + builder = addOptionalHeader(builder, accessCondition + .getHeader().toString(), accessCondition.getValue()); + } + } + return builder; + } + + public static Builder addOptionalSourceAccessConditionHeader( + Builder builder, AccessConditionHeader accessCondition) { + if (accessCondition != null) { + if (accessCondition.getHeader() != AccessConditionHeaderType.NONE) { + String headerName; + switch (accessCondition.getHeader()) { + case IF_MATCH: + headerName = "x-ms-source-if-match"; + break; + case IF_UNMODIFIED_SINCE: + headerName = "x-ms-source-if-unmodified-since"; + break; + case IF_MODIFIED_SINCE: + headerName = "x-ms-source-if-modified-since"; + break; + case IF_NONE_MATCH: + headerName = "x-ms-source-if-none-match"; + break; + default: + headerName = ""; + } + builder = addOptionalHeader(builder, headerName, + accessCondition.getValue()); + } + } + return builder; + } + + public static HashMap getMetadataFromHeaders( + ClientResponse response) { + HashMap metadata = new HashMap(); + for (Entry> entry : response.getHeaders() + .entrySet()) { + if (entry.getKey().startsWith("x-ms-meta-")) { + String name = entry.getKey().substring("x-ms-meta-".length()); + String value = entry.getValue().get(0); + metadata.put(name, value); + } + } + return metadata; + } + +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/ApacheConfigSettings.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/ApacheConfigSettings.java new file mode 100644 index 0000000000000..9d2a9115d52fc --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/ApacheConfigSettings.java @@ -0,0 +1,84 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.apache; + +import java.util.Map; +import org.apache.http.HttpHost; +import org.apache.http.client.HttpRequestRetryHandler; +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.conn.socket.LayeredConnectionSocketFactory; +import org.apache.http.impl.client.HttpClientBuilder; + +public class ApacheConfigSettings { + private final String profile; + private final Map properties; + + public ApacheConfigSettings(String profile, Map properties) { + this.profile = profile; + this.properties = properties; + } + + /** + * Update the given {@link HttpClientBuilder} object with the appropriate + * settings from configuration. + * + * @param httpClientBuilder + * The object to update. + * @return The updates httpClientBuilder + */ + public HttpClientBuilder applyConfig(HttpClientBuilder httpClientBuilder) { + if (properties + .containsKey(profile + + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)) { + httpClientBuilder + .setSSLSocketFactory((LayeredConnectionSocketFactory) properties + .get(profile + + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)); + } + + if (properties.containsKey(profile + + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)) { + httpClientBuilder + .setConnectionManager((HttpClientConnectionManager) properties + .get(profile + + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)); + } + + if (properties.containsKey(profile + + ApacheConfigurationProperties.PROPERTY_PROXY_URI)) { + httpClientBuilder + .setProxy(new HttpHost((String) properties.get(profile + + ApacheConfigurationProperties.PROPERTY_PROXY_URI))); + } + + if (properties.containsKey(profile + + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)) { + httpClientBuilder + .setRetryHandler((HttpRequestRetryHandler) properties + .get(profile + + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)); + } + + if (properties.containsKey(profile + + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER)) { + return (HttpClientBuilder) properties + .get(profile + + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER); + } + + return httpClientBuilder; + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/ApacheConfigurationProperties.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/ApacheConfigurationProperties.java new file mode 100644 index 0000000000000..9147e475cd6a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/ApacheConfigurationProperties.java @@ -0,0 +1,28 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.apache; + +public abstract class ApacheConfigurationProperties { + public static final String PROPERTY_SSL_CONNECTION_SOCKET_FACTORY = "com.microsoft.windowsazure.Configuration.sslConnectionSocketFactory"; + + public static final String PROPERTY_CONNECTION_MANAGER = "com.microsoft.windowsazure.Configuration.connectionManager"; + + public static final String PROPERTY_PROXY_URI = "com.microsoft.windowsazure.Configuration.proxy"; + + public static final String PROPERTY_RETRY_HANDLER = "com.microsoft.windowsazure.Configuration.retryHandler"; + + public static final String PROPERTY_HTTP_CLIENT_BUILDER = "com.microsoft.windowsazure.Configuration.httpClientBuilder"; +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/CustomHttpDelete.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/CustomHttpDelete.java new file mode 100644 index 0000000000000..8d595175422df --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/CustomHttpDelete.java @@ -0,0 +1,29 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.apache; + +import org.apache.http.client.methods.HttpPost; + +public class CustomHttpDelete extends HttpPost { + public CustomHttpDelete(String url) { + super(url); + } + + @Override + public String getMethod() { + return "DELETE"; + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/Exports.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/Exports.java new file mode 100644 index 0000000000000..c9b762ccde296 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/Exports.java @@ -0,0 +1,71 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.apache; + +import java.util.Map; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Registry; +import com.microsoft.windowsazure.credentials.CloudCredentials; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; + +public class Exports implements Builder.Exports { + + @Override + public void register(Registry registry) { + registry.add(new Builder.Factory() { + @Override + public ExecutorService create(String profile, Class service, + Builder builder, Map properties) { + + return Executors.newCachedThreadPool(); + } + }); + + registry.add(new Builder.Factory() { + @Override + public ApacheConfigSettings create(String profile, + Class service, Builder builder, + Map properties) { + + if (properties + .containsKey(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS)) { + CloudCredentials cloudCredentials = (CloudCredentials) properties + .get(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS); + cloudCredentials.applyConfig(profile, properties); + } + + return new ApacheConfigSettings(profile, properties); + } + }); + + registry.add(new Builder.Factory() { + @Override + public HttpClientBuilder create(String profile, + Class service, Builder builder, + Map properties) { + + HttpClientBuilder httpClientBuilder = HttpClients.custom(); + ApacheConfigSettings settings = builder.build(profile, service, + ApacheConfigSettings.class, properties); + return settings.applyConfig(httpClientBuilder); + } + }); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpRequestInterceptorAdapter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpRequestInterceptorAdapter.java new file mode 100644 index 0000000000000..cd20f3e684988 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpRequestInterceptorAdapter.java @@ -0,0 +1,33 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.apache; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import org.apache.http.HttpRequest; +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.protocol.HttpContext; + +public class HttpRequestInterceptorAdapter implements HttpRequestInterceptor { + private ServiceRequestFilter filter; + + public HttpRequestInterceptorAdapter(ServiceRequestFilter filter) { + this.filter = filter; + } + + @Override + public void process(HttpRequest request, HttpContext context) { + filter.filter(new HttpServiceRequestContext(request, context)); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpResponseInterceptorAdapter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpResponseInterceptorAdapter.java new file mode 100644 index 0000000000000..7687f381b4413 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpResponseInterceptorAdapter.java @@ -0,0 +1,33 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.apache; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import org.apache.http.HttpResponse; +import org.apache.http.HttpResponseInterceptor; +import org.apache.http.protocol.HttpContext; + +public class HttpResponseInterceptorAdapter implements HttpResponseInterceptor { + private ServiceResponseFilter filter; + + public HttpResponseInterceptorAdapter(ServiceResponseFilter filter) { + this.filter = filter; + } + + @Override + public void process(HttpResponse response, HttpContext context) { + filter.filter(null, new HttpServiceResponseContext(response, context)); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpServiceRequestContext.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpServiceRequestContext.java new file mode 100644 index 0000000000000..47c358f1a58b0 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpServiceRequestContext.java @@ -0,0 +1,95 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.apache; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import java.net.URI; +import java.net.URISyntaxException; +import org.apache.http.Header; +import org.apache.http.HttpRequest; +import org.apache.http.protocol.HttpContext; + +public class HttpServiceRequestContext implements ServiceRequestContext { + private final HttpRequest clientRequest; + private final HttpContext httpContext; + + public HttpServiceRequestContext(HttpRequest clientRequest, + HttpContext httpContext) { + this.clientRequest = clientRequest; + this.httpContext = httpContext; + } + + @Override + public Object getProperty(final String name) { + return httpContext.getAttribute(name); + } + + @Override + public void setProperty(final String name, final Object value) { + httpContext.setAttribute(name, value); + } + + @Override + public URI getURI() { + try { + return new URI(clientRequest.getRequestLine().getUri()); + } catch (URISyntaxException e) { + return null; + } + } + + @Override + public void setURI(final URI uri) { + // Do nothing. not supported + } + + @Override + public String getMethod() { + return clientRequest.getRequestLine().getMethod(); + } + + @Override + public void setMethod(String method) { + // Do nothing. not supported + } + + @Override + public Object getEntity() { + // Do nothing. not supported + return null; + } + + @Override + public void setEntity(final Object entity) { + // Do nothing. not supported + } + + @Override + public String getHeader(final String name) { + final Header first = clientRequest.getFirstHeader(name); + return first != null ? first.getValue() : null; + } + + @Override + public void setHeader(final String name, final String value) { + clientRequest.setHeader(name, value); + } + + @Override + public void removeHeader(final String name) { + clientRequest.removeHeaders(name); + } +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpServiceResponseContext.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpServiceResponseContext.java new file mode 100644 index 0000000000000..35238d3b048a2 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/HttpServiceResponseContext.java @@ -0,0 +1,96 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.apache; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import java.io.IOException; +import java.io.InputStream; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.protocol.HttpContext; + +public class HttpServiceResponseContext implements ServiceResponseContext { + private HttpResponse clientResponse; + private HttpContext httpContext; + + public HttpServiceResponseContext(HttpResponse clientResponse, + HttpContext httpContext) { + this.clientResponse = clientResponse; + this.httpContext = httpContext; + } + + @Override + public Object getProperty(String name) { + return httpContext.getAttribute(name); + } + + @Override + public void setProperty(String name, Object value) { + httpContext.setAttribute(name, value); + } + + @Override + public int getStatus() { + return clientResponse.getStatusLine().getStatusCode(); + } + + @Override + public void setStatus(int status) { + clientResponse.setStatusCode(status); + } + + @Override + public boolean hasEntity() { + return clientResponse.getEntity() != null; + } + + @Override + public String getHeader(String name) { + Header first = clientResponse.getFirstHeader(name); + if (first != null) { + return first.getValue(); + } + + return null; + } + + @Override + public void setHeader(String name, String value) { + clientResponse.setHeader(name, value); + } + + @Override + public void removeHeader(String name) { + clientResponse.removeHeaders(name); + } + + @Override + public InputStream getEntityInputStream() { + try { + return clientResponse.getEntity().getContent(); + } catch (IOException e) { + return null; + } catch (IllegalStateException e) { + return null; + } + } + + @Override + public void setEntityInputStream(InputStream entity) { + clientResponse.setEntity(new InputStreamEntity(entity)); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/package.html b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/apache/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceRequestContext.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceRequestContext.java new file mode 100644 index 0000000000000..0d8d8ebd4565d --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceRequestContext.java @@ -0,0 +1,42 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.filter; + +import java.net.URI; + +public interface ServiceRequestContext { + String getMethod(); + + void setMethod(String method); + + URI getURI(); + + void setURI(URI uri); + + String getHeader(String name); + + void setHeader(String name, String value); + + void removeHeader(String name); + + Object getEntity(); + + void setEntity(Object entity); + + Object getProperty(String name); + + void setProperty(String name, Object value); +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceRequestFilter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceRequestFilter.java new file mode 100644 index 0000000000000..8963e8710492c --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceRequestFilter.java @@ -0,0 +1,20 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.filter; + +public interface ServiceRequestFilter { + void filter(ServiceRequestContext request); +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceResponseContext.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceResponseContext.java new file mode 100644 index 0000000000000..990d6d0defd73 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceResponseContext.java @@ -0,0 +1,40 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.filter; + +import java.io.InputStream; + +public interface ServiceResponseContext { + int getStatus(); + + void setStatus(int status); + + String getHeader(String name); + + void setHeader(String name, String value); + + void removeHeader(String name); + + boolean hasEntity(); + + InputStream getEntityInputStream(); + + void setEntityInputStream(InputStream entity); + + Object getProperty(String name); + + void setProperty(String name, Object value); +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceResponseFilter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceResponseFilter.java new file mode 100644 index 0000000000000..38c0135f8b03c --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/ServiceResponseFilter.java @@ -0,0 +1,20 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.filter; + +public interface ServiceResponseFilter { + void filter(ServiceRequestContext request, ServiceResponseContext response); +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/package.html b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/filter/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ClientConfigSettings.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientConfigSettings.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ClientConfigSettings.java rename to core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientConfigSettings.java index b7421b9ed6564..e3764cf212d51 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ClientConfigSettings.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientConfigSettings.java @@ -13,14 +13,14 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils.pipeline; +package com.microsoft.windowsazure.core.pipeline.jersey; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; /** - * Class used for injecting timeout settings into the various places that need it. + * Class used for injecting settings into the various places that need it. * */ public class ClientConfigSettings { @@ -41,8 +41,7 @@ public ClientConfigSettings() { } /** - * Construct a {@link ClientConfigSettings} object wit the given - * settings. + * Construct a {@link ClientConfigSettings} object wit the given settings. * * @param connectTimeout * Connection timeout in milliseconds @@ -51,7 +50,8 @@ public ClientConfigSettings() { * @param shouldLog * if true, add logging filter to clients. */ - public ClientConfigSettings(Object connectTimeout, Object readTimeout, boolean shouldLog) { + public ClientConfigSettings(Object connectTimeout, Object readTimeout, + boolean shouldLog) { this.connectTimeout = getTimeout(connectTimeout); this.readTimeout = getTimeout(readTimeout); this.shouldLog = shouldLog; @@ -65,13 +65,15 @@ public ClientConfigSettings(Object connectTimeout, Object readTimeout, boolean s * object to update. */ public void applyConfig(ClientConfig clientConfig) { - clientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, connectTimeout); - clientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, readTimeout); + clientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, + connectTimeout); + clientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, + readTimeout); } /** - * Update the given {@link client} object with the appropriate settings - * from configuration. + * Update the given {@link client} object with the appropriate settings from + * configuration. * * @param client */ diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterAdapter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterAdapter.java new file mode 100644 index 0000000000000..a6ef01ea4f2f6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterAdapter.java @@ -0,0 +1,53 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; + +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class ClientFilterAdapter extends ClientFilter { + private ServiceFilter filter; + + public ClientFilterAdapter(ServiceFilter filter) { + this.filter = filter; + } + + @Override + public ClientResponse handle(ClientRequest clientRequest) { + + final ClientRequest cr = clientRequest; + try { + ServiceResponseContext resp = filter.handle( + new JerseyServiceRequestContext(clientRequest), + new ServiceFilter.Next() { + @Override + public ServiceResponseContext handle( + ServiceRequestContext request) { + return new JerseyServiceResponseContext(getNext() + .handle(cr)); + } + }); + + return ((JerseyServiceResponseContext) resp).getClientResponse(); + } catch (Exception e) { + throw new ClientHandlerException(e); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterRequestAdapter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterRequestAdapter.java new file mode 100644 index 0000000000000..501adc9200b15 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterRequestAdapter.java @@ -0,0 +1,35 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; + +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class ClientFilterRequestAdapter extends ClientFilter { + private ServiceRequestFilter filter; + + public ClientFilterRequestAdapter(ServiceRequestFilter filter) { + this.filter = filter; + } + + @Override + public ClientResponse handle(ClientRequest clientRequest) { + filter.filter(new JerseyServiceRequestContext(clientRequest)); + return getNext().handle(clientRequest); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterResponseAdapter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterResponseAdapter.java new file mode 100644 index 0000000000000..41f010f8ae7ae --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ClientFilterResponseAdapter.java @@ -0,0 +1,37 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; + +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class ClientFilterResponseAdapter extends ClientFilter { + private ServiceResponseFilter filter; + + public ClientFilterResponseAdapter(ServiceResponseFilter filter) { + this.filter = filter; + } + + @Override + public ClientResponse handle(ClientRequest clientRequest) { + ClientResponse clientResponse = getNext().handle(clientRequest); + filter.filter(new JerseyServiceRequestContext(clientRequest), + new JerseyServiceResponseContext(clientResponse)); + return clientResponse; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/EntityStreamingListener.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/EntityStreamingListener.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/EntityStreamingListener.java rename to core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/EntityStreamingListener.java index f0a2b98cfe684..ddb15c74edae5 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/EntityStreamingListener.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/EntityStreamingListener.java @@ -12,14 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils.pipeline; +package com.microsoft.windowsazure.core.pipeline.jersey; import com.sun.jersey.api.client.ClientRequest; public interface EntityStreamingListener { /** - * This method is called just before the entity is streamed to the underlying connection. This is the last chance - * for filters to inspect and modify the headers of the client request if necessary. + * This method is called just before the entity is streamed to the + * underlying connection. This is the last chance for filters to inspect and + * modify the headers of the client request if necessary. * * @param clientRequest * The client request diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ExponentialRetryPolicy.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ExponentialRetryPolicy.java new file mode 100644 index 0000000000000..883f6c905167c --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ExponentialRetryPolicy.java @@ -0,0 +1,80 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import java.util.Arrays; +import java.util.Random; + +public class ExponentialRetryPolicy extends RetryPolicy { + private final int deltaBackoffIntervalInMs; + private final int maximumAttempts; + private final Random randRef = new Random(); + private final int resolvedMaxBackoff = DEFAULT_MAX_BACKOFF; + private final int resolvedMinBackoff = DEFAULT_MIN_BACKOFF; + private final int[] retryableStatusCodes; + + public ExponentialRetryPolicy(int[] retryableStatusCodes) { + this(DEFAULT_CLIENT_BACKOFF, DEFAULT_CLIENT_RETRY_COUNT, + retryableStatusCodes); + } + + public ExponentialRetryPolicy(int deltaBackoff, int maximumAttempts, + int[] retryableStatusCodes) { + this.deltaBackoffIntervalInMs = deltaBackoff; + this.maximumAttempts = maximumAttempts; + this.retryableStatusCodes = Arrays.copyOf(retryableStatusCodes, + retryableStatusCodes.length); + Arrays.sort(this.retryableStatusCodes); + } + + @Override + public boolean shouldRetry(int retryCount, ServiceResponseContext response, + Exception error) { + if (response == null) { + return false; + } + + if (retryCount >= this.maximumAttempts) { + return false; + } + + // Don't retry if not retryable status code + if (Arrays + .binarySearch(this.retryableStatusCodes, response.getStatus()) < 0) { + return false; + } + + return true; + } + + @Override + public int calculateBackoff(int currentRetryCount, + ServiceResponseContext response, Exception error) { + // Calculate backoff Interval between 80% and 120% of the desired + // backoff, multiply by 2^n -1 for + // exponential + int incrementDelta = (int) (Math.pow(2, currentRetryCount) - 1); + int boundedRandDelta = (int) (this.deltaBackoffIntervalInMs * 0.8) + + this.randRef + .nextInt((int) (this.deltaBackoffIntervalInMs * 1.2) + - (int) (this.deltaBackoffIntervalInMs * 0.8)); + incrementDelta *= boundedRandDelta; + + // Enforce max / min backoffs + return Math.min(this.resolvedMinBackoff + incrementDelta, + this.resolvedMaxBackoff); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/Exports.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/Exports.java new file mode 100644 index 0000000000000..78368186a30d2 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/Exports.java @@ -0,0 +1,94 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.Configuration; +import static com.microsoft.windowsazure.core.utils.ExportUtils.getPropertyIfExists; + +import java.util.Map; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Registry; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; + +public class Exports implements Builder.Exports { + + @Override + public void register(Registry registry) { + registry.add(new Builder.Factory() { + @Override + public ClientConfig create(String profile, Class service, + Builder builder, Map properties) { + ClientConfig clientConfig = new DefaultClientConfig(); + ClientConfigSettings settings = builder.build(profile, service, + ClientConfigSettings.class, properties); + settings.applyConfig(clientConfig); + return clientConfig; + } + }); + + registry.add(new Builder.Factory() { + + @Override + public ClientConfigSettings create(String profile, + Class service, Builder builder, + Map properties) { + Object connectTimeout = getPropertyIfExists(profile, + properties, Configuration.PROPERTY_CONNECT_TIMEOUT); + Object readTimeout = getPropertyIfExists(profile, properties, + Configuration.PROPERTY_READ_TIMEOUT); + + return new ClientConfigSettings( + connectTimeout, + readTimeout, + getPropertyIfExists(profile, properties, + Configuration.PROPERTY_LOG_HTTP_REQUESTS) != null); + } + + }); + + registry.add(new Builder.Factory() { + @Override + public Client create(String profile, Class service, + Builder builder, Map properties) { + ClientConfig clientConfig = builder.build(profile, service, + ClientConfig.class, properties); + ClientConfigSettings settings = builder.build(profile, service, + ClientConfigSettings.class, properties); + Client client = Client.create(clientConfig); + settings.applyConfig(client); + return client; + } + }); + + registry.add(new Builder.Factory() { + @Override + public HttpURLConnectionClient create(String profile, + Class service, Builder builder, + Map properties) { + ClientConfig clientConfig = builder.build(profile, service, + ClientConfig.class, properties); + ClientConfigSettings settings = builder.build(profile, service, + ClientConfigSettings.class, properties); + HttpURLConnectionClient client = HttpURLConnectionClient + .create(clientConfig); + settings.applyConfig(client); + return client; + } + }); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/HttpURLConnectionClient.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/HttpURLConnectionClient.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/HttpURLConnectionClient.java rename to core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/HttpURLConnectionClient.java index a5751d7480b5f..8900f630db74c 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/HttpURLConnectionClient.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/HttpURLConnectionClient.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils.pipeline; +package com.microsoft.windowsazure.core.pipeline.jersey; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.config.ClientConfig; @@ -20,13 +20,15 @@ public class HttpURLConnectionClient extends Client { private final HttpURLConnectionClientHandler rootHandler; - public HttpURLConnectionClient(HttpURLConnectionClientHandler handler, ClientConfig config) { + public HttpURLConnectionClient(HttpURLConnectionClientHandler handler, + ClientConfig config) { super(handler, config); this.rootHandler = handler; } public static HttpURLConnectionClient create(ClientConfig config) { - return new HttpURLConnectionClient(new HttpURLConnectionClientHandler(config), config); + return new HttpURLConnectionClient(new HttpURLConnectionClientHandler( + config), config); } public HttpURLConnectionClientHandler getRootHandler() { diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/HttpURLConnectionClientHandler.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/HttpURLConnectionClientHandler.java new file mode 100644 index 0000000000000..54fb5967c334a --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/HttpURLConnectionClientHandler.java @@ -0,0 +1,357 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import com.microsoft.windowsazure.core.utils.CommaStringBuilder; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.CommittingOutputStream; +import com.sun.jersey.api.client.TerminatingClientHandler; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.core.header.InBoundHeaders; + +public class HttpURLConnectionClientHandler extends TerminatingClientHandler { + + private final int connectionTimeoutMillis; + private final int readTimeoutMillis; + + public HttpURLConnectionClientHandler(ClientConfig clientConfig) { + connectionTimeoutMillis = readTimeoutFromConfig(clientConfig, + ClientConfig.PROPERTY_CONNECT_TIMEOUT); + readTimeoutMillis = readTimeoutFromConfig(clientConfig, + ClientConfig.PROPERTY_READ_TIMEOUT); + } + + private static int readTimeoutFromConfig(ClientConfig config, + String propertyName) { + Integer property = (Integer) config.getProperty(propertyName); + if (property != null) { + return property.intValue(); + } + throw new IllegalArgumentException(propertyName); + } + + /** + * Empty "no-op" listener if none registered + */ + private static final EntityStreamingListener EMPTY_STREAMING_LISTENER = new EntityStreamingListener() { + @Override + public void onBeforeStreamingEntity(ClientRequest clientRequest) { + } + }; + + /** + * OutputStream used for buffering entity body when "Content-Length" is not + * known in advance. + */ + private final class BufferingOutputStream extends OutputStream { + private final ByteArrayOutputStream outputStream; + private final HttpURLConnection urlConnection; + private final ClientRequest clientRequest; + private final EntityStreamingListener entityStreamingListener; + private boolean closed; + + private BufferingOutputStream(HttpURLConnection urlConnection, + ClientRequest clientRequest, + EntityStreamingListener entityStreamingListener) { + this.outputStream = new ByteArrayOutputStream(); + this.urlConnection = urlConnection; + this.clientRequest = clientRequest; + this.entityStreamingListener = entityStreamingListener; + } + + @Override + public void close() throws IOException { + outputStream.close(); + + if (!closed) { + closed = true; + + // Give the listener a last change to modify headers now that + // the content length is known + setContentLengthHeader(clientRequest, outputStream.size()); + entityStreamingListener.onBeforeStreamingEntity(clientRequest); + + // Write headers, then entity to the http connection. + setURLConnectionHeaders(clientRequest.getHeaders(), + urlConnection); + + // Since we buffered the entity and we know the content size, we + // might as well + // use the "fixed length" streaming mode of HttpURLConnection to + // stream + // the buffer directly. + urlConnection.setFixedLengthStreamingMode(outputStream.size()); + OutputStream httpOutputStream = urlConnection.getOutputStream(); + outputStream.writeTo(httpOutputStream); + httpOutputStream.flush(); + httpOutputStream.close(); + } + } + + @Override + public void flush() throws IOException { + outputStream.flush(); + } + + @Override + public void write(byte[] b, int off, int len) { + outputStream.write(b, off, len); + } + + @Override + public void write(byte[] b) throws IOException { + outputStream.write(b); + } + + @Override + public void write(int b) { + outputStream.write(b); + } + } + + /** + * OutputStream used for directly streaming entity to url connection stream. + * Headers are written just before sending the first bytes to the output + * stream. + */ + private final class StreamingOutputStream extends CommittingOutputStream { + private final HttpURLConnection urlConnection; + private final ClientRequest clientRequest; + + private StreamingOutputStream(HttpURLConnection urlConnection, + ClientRequest clientRequest) { + this.urlConnection = urlConnection; + this.clientRequest = clientRequest; + } + + @Override + protected OutputStream getOutputStream() throws IOException { + return urlConnection.getOutputStream(); + } + + @Override + public void commit() throws IOException { + setURLConnectionHeaders(clientRequest.getHeaders(), urlConnection); + } + } + + /** + * Simple response implementation around an HttpURLConnection response + */ + private final class URLConnectionResponse extends ClientResponse { + private final String method; + private final HttpURLConnection urlConnection; + + URLConnectionResponse(int status, InBoundHeaders headers, + InputStream entity, String method, + HttpURLConnection urlConnection) { + super(status, headers, entity, getMessageBodyWorkers()); + this.method = method; + this.urlConnection = urlConnection; + } + + @Override + public boolean hasEntity() { + if (method.equals("HEAD") || getEntityInputStream() == null) { + return false; + } + + // Length "-1" means "unknown" + int length = urlConnection.getContentLength(); + return length > 0 || length == -1; + } + + @Override + public String toString() { + return urlConnection.getRequestMethod() + " " + + urlConnection.getURL() + + " returned a response status of " + this.getStatus() + + " " + this.getClientResponseStatus(); + } + } + + @Override + public ClientResponse handle(final ClientRequest ro) { + try { + return doHandle(ro); + } catch (Exception e) { + throw new ClientHandlerException(e); + } + } + + private ClientResponse doHandle(final ClientRequest clientRequest) + throws IOException { + final HttpURLConnection urlConnection = (HttpURLConnection) clientRequest + .getURI().toURL().openConnection(); + urlConnection.setReadTimeout(readTimeoutMillis); + urlConnection.setConnectTimeout(connectionTimeoutMillis); + + final EntityStreamingListener entityStreamingListener = getEntityStreamingListener(clientRequest); + + urlConnection.setRequestMethod(clientRequest.getMethod()); + + // Write the request headers + setURLConnectionHeaders(clientRequest.getHeaders(), urlConnection); + + // Write the entity (if any) + Object entity = clientRequest.getEntity(); + + // If no entity and "PUT method, force an empty entity to force the + // underlying + // connection to set the "Content-Length" header to 0. + // This is needed because some web servers require a "Content-Length" + // field for + // all PUT method calls (unless chunked encoding is used). + if (entity == null && "PUT".equals(clientRequest.getMethod())) { + entity = new byte[0]; + clientRequest.setEntity(entity); + } + + // Send headers and entity on the wire + if (entity != null) { + urlConnection.setDoOutput(true); + + writeRequestEntity(clientRequest, + new RequestEntityWriterListener() { + private boolean inStreamingMode; + + @Override + public void onRequestEntitySize(long size) { + if (size != -1 && size < Integer.MAX_VALUE) { + inStreamingMode = true; + setContentLengthHeader(clientRequest, + (int) size); + entityStreamingListener + .onBeforeStreamingEntity(clientRequest); + + urlConnection + .setFixedLengthStreamingMode((int) size); + } else { + Integer chunkedEncodingSize = (Integer) clientRequest + .getProperties() + .get(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); + if (chunkedEncodingSize != null) { + inStreamingMode = true; + entityStreamingListener + .onBeforeStreamingEntity(clientRequest); + + urlConnection + .setChunkedStreamingMode(chunkedEncodingSize); + } + } + } + + @Override + public OutputStream onGetOutputStream() + throws IOException { + if (inStreamingMode) { + return new StreamingOutputStream(urlConnection, + clientRequest); + } else { + return new BufferingOutputStream(urlConnection, + clientRequest, entityStreamingListener); + } + } + }); + } else { + entityStreamingListener.onBeforeStreamingEntity(clientRequest); + setURLConnectionHeaders(clientRequest.getHeaders(), urlConnection); + } + + // Return the in-bound response + return new URLConnectionResponse(urlConnection.getResponseCode(), + getInBoundHeaders(urlConnection), + getInputStream(urlConnection), clientRequest.getMethod(), + urlConnection); + } + + private EntityStreamingListener getEntityStreamingListener( + final ClientRequest clientRequest) { + EntityStreamingListener result = (EntityStreamingListener) clientRequest + .getProperties().get(EntityStreamingListener.class.getName()); + + if (result != null) { + return result; + } + + return EMPTY_STREAMING_LISTENER; + } + + private void setContentLengthHeader(ClientRequest clientRequest, int size) { + // Skip if already set + if (clientRequest.getHeaders().getFirst("Content-Length") != null) { + return; + } + + // Skip if size is unknown + if (size < 0) { + return; + } + + clientRequest.getHeaders().putSingle("Content-Length", size); + } + + private void setURLConnectionHeaders( + MultivaluedMap headers, + HttpURLConnection urlConnection) { + for (Map.Entry> e : headers.entrySet()) { + List vs = e.getValue(); + if (vs.size() == 1) { + urlConnection.setRequestProperty(e.getKey(), + ClientRequest.getHeaderValue(vs.get(0))); + } else { + CommaStringBuilder sb = new CommaStringBuilder(); + for (Object v : e.getValue()) { + sb.add(ClientRequest.getHeaderValue(v)); + } + urlConnection.setRequestProperty(e.getKey(), sb.toString()); + } + } + } + + private InBoundHeaders getInBoundHeaders(HttpURLConnection urlConnection) { + InBoundHeaders headers = new InBoundHeaders(); + for (Map.Entry> e : urlConnection + .getHeaderFields().entrySet()) { + if (e.getKey() != null) { + headers.put(e.getKey(), e.getValue()); + } + } + return headers; + } + + private InputStream getInputStream(HttpURLConnection urlConnection) + throws IOException { + if (urlConnection.getResponseCode() < 300) { + return urlConnection.getInputStream(); + } else { + InputStream ein = urlConnection.getErrorStream(); + return (ein != null) ? ein : new ByteArrayInputStream(new byte[0]); + } + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/IdempotentClientFilter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/IdempotentClientFilter.java new file mode 100644 index 0000000000000..3e43fb58b085a --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/IdempotentClientFilter.java @@ -0,0 +1,67 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +/** + * Base class for filters that enforces idempotency - the filter will only be + * applied once for a particular request, even if the request passes through + * this filter more than once. + * + */ +public abstract class IdempotentClientFilter extends ClientFilter { + /* + * (non-Javadoc) + * + * @see + * com.sun.jersey.api.client.filter.ClientFilter#handle(com.sun.jersey.api + * .client.ClientRequest) + */ + @Override + public ClientResponse handle(ClientRequest cr) { + String key = getKey(); + + if (cr.getProperties().containsKey(key)) { + return this.getNext().handle(cr); + } + cr.getProperties().put(key, this); + return doHandle(cr); + } + + /** + * Implemented by derived classes to provide the actual implementation for + * filtering. + * + * @param cr + * The ClientRequest being processed + * @return The returned ClientResponse + * @throws ClientHandlerException + */ + protected abstract ClientResponse doHandle(ClientRequest cr); + + /** + * Get the key value used to detect multiple runs. By default, defaults to + * the class name for the filter. + * + * @return Key name as a string + */ + protected String getKey() { + return this.getClass().getName(); + } +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyFilterableService.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyFilterableService.java new file mode 100644 index 0000000000000..7e68db0db8060 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyFilterableService.java @@ -0,0 +1,21 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.FilterableService; + +public interface JerseyFilterableService extends FilterableService { + T withFilter(ServiceFilter filter); +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyServiceRequestContext.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyServiceRequestContext.java new file mode 100644 index 0000000000000..9da004d9dd588 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyServiceRequestContext.java @@ -0,0 +1,89 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.sun.jersey.api.client.ClientRequest; +import java.net.URI; +import java.util.List; + +public class JerseyServiceRequestContext implements ServiceRequestContext { + private ClientRequest clientRequest; + + public JerseyServiceRequestContext(ClientRequest clientRequest) { + this.clientRequest = clientRequest; + } + + @Override + public Object getProperty(String name) { + return clientRequest.getProperties().get(name); + } + + @Override + public void setProperty(String name, Object value) { + clientRequest.getProperties().put(name, value); + } + + @Override + public URI getURI() { + return clientRequest.getURI(); + } + + @Override + public void setURI(URI uri) { + clientRequest.setURI(uri); + } + + @Override + public String getMethod() { + return clientRequest.getMethod(); + } + + @Override + public void setMethod(String method) { + clientRequest.setMethod(method); + } + + @Override + public Object getEntity() { + return clientRequest.getEntity(); + } + + @Override + public void setEntity(Object entity) { + clientRequest.setEntity(entity); + } + + @Override + public String getHeader(String name) { + List headers = clientRequest.getHeaders().get(name); + if (headers != null && headers.size() > 0) { + return (String) headers.get(0); + } + + return null; + } + + @Override + public void setHeader(String name, String value) { + clientRequest.getHeaders().add(name, value); + } + + @Override + public void removeHeader(String name) { + clientRequest.getHeaders().remove(name); + } +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyServiceResponseContext.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyServiceResponseContext.java new file mode 100644 index 0000000000000..d36bbf94092e5 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/JerseyServiceResponseContext.java @@ -0,0 +1,88 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import com.sun.jersey.api.client.ClientResponse; +import java.io.InputStream; +import java.util.List; + +public class JerseyServiceResponseContext implements ServiceResponseContext { + private final ClientResponse clientResponse; + + protected ClientResponse getClientResponse() { + return this.clientResponse; + } + + public JerseyServiceResponseContext(final ClientResponse clientResponse) { + this.clientResponse = clientResponse; + } + + @Override + public Object getProperty(String name) { + return clientResponse.getProperties().get(name); + } + + @Override + public void setProperty(String name, Object value) { + clientResponse.getProperties().put(name, value); + } + + @Override + public int getStatus() { + return clientResponse.getStatus(); + } + + @Override + public void setStatus(int status) { + clientResponse.setStatus(status); + } + + @Override + public String getHeader(String name) { + List headers = clientResponse.getHeaders().get(name); + if (headers != null && headers.size() > 0) { + return headers.get(0); + } + + return null; + } + + @Override + public void setHeader(String name, String value) { + clientResponse.getHeaders().add(name, value); + } + + @Override + public void removeHeader(String name) { + clientResponse.getHeaders().remove(name); + } + + @Override + public boolean hasEntity() { + return clientResponse.hasEntity(); + } + + @Override + public InputStream getEntityInputStream() { + return clientResponse.getEntityInputStream(); + } + + @Override + public void setEntityInputStream(InputStream entity) { + clientResponse.setEntityInputStream(entity); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/RetryPolicy.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/RetryPolicy.java new file mode 100644 index 0000000000000..39db07373979d --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/RetryPolicy.java @@ -0,0 +1,30 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; + +public abstract class RetryPolicy { + public static final int DEFAULT_CLIENT_BACKOFF = 1000 * 30; + public static final int DEFAULT_CLIENT_RETRY_COUNT = 3; + public static final int DEFAULT_MAX_BACKOFF = 1000 * 90; + public static final int DEFAULT_MIN_BACKOFF = 100 * 3; + + public abstract boolean shouldRetry(int retryCount, + ServiceResponseContext response, Exception error); + + public abstract int calculateBackoff(int retryCount, + ServiceResponseContext response, Exception error); +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/RetryPolicyFilter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/RetryPolicyFilter.java new file mode 100644 index 0000000000000..ab70177ba2c38 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/RetryPolicyFilter.java @@ -0,0 +1,115 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import java.io.InputStream; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class RetryPolicyFilter implements ServiceFilter { + private static final Log LOG = LogFactory.getLog(RetryPolicyFilter.class); + private final RetryPolicy retryPolicy; + + public RetryPolicyFilter(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + } + + @Override + public ServiceResponseContext handle(ServiceRequestContext request, + Next next) throws Exception { + // Only the last added retry policy should be active + if (request.getProperty("RetryPolicy") != null) { + return next.handle(request); + } + + request.setProperty("RetryPolicy", this); + + // Retry the operation as long as retry policy tells us to do so + for (int retryCount = 0;; ++retryCount) { + // Mark the stream before passing the request through + if (getEntityStream(request) != null) { + getEntityStream(request).mark(Integer.MAX_VALUE); + } + + // Pass the request to the next handler + ServiceResponseContext response = null; + Exception error = null; + try { + response = next.handle(request); + } catch (Exception e) { + error = e; + } + + // Determine if we should retry according to retry policy + boolean shouldRetry = retryPolicy.shouldRetry(retryCount, response, + error); + if (!shouldRetry) { + if (error != null) { + throw error; + } + + return response; + } + + // Reset the stream before retrying + if (getEntityStream(request) != null) { + getEntityStream(request).reset(); + } + + // Backoff for some time according to retry policy + int backoffTime = retryPolicy.calculateBackoff(retryCount, + response, error); + LOG.info(String + .format("Request failed. Backing off for %1s milliseconds before retrying (retryCount=%2d)", + backoffTime, retryCount)); + backoff(backoffTime); + } + } + + private InputStream getEntityStream(ServiceRequestContext request) { + if (request.getEntity() == null) { + return null; + } + + if (!(request.getEntity() instanceof InputStream)) { + return null; + } + + InputStream entityStream = (InputStream) request.getEntity(); + + // If the entity is an InputStream that doesn't support "mark/reset", we + // can't + // implement a retry logic, so we simply throw. + if (!entityStream.markSupported()) { + throw new IllegalArgumentException( + "The input stream for the request entity must support 'mark' and " + + "'reset' to be compatible with a retry policy filter."); + } + + return entityStream; + } + + private void backoff(int milliseconds) { + try { + Thread.sleep(milliseconds); + } catch (InterruptedException e) { + // Restore the interrupted status + Thread.currentThread().interrupt(); + } + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ServiceFilter.java b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ServiceFilter.java new file mode 100644 index 0000000000000..f94ecfc601aa9 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/ServiceFilter.java @@ -0,0 +1,28 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline.jersey; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; + +public interface ServiceFilter { + ServiceResponseContext handle(ServiceRequestContext request, Next next) + throws Exception; + + public interface Next { + ServiceResponseContext handle(ServiceRequestContext request) + throws Exception; + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/package.html b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/jersey/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/core/pipeline/package.html b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/pipeline/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/AccessConditionHeader.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/AccessConditionHeader.java new file mode 100644 index 0000000000000..121ea06c64e14 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/AccessConditionHeader.java @@ -0,0 +1,211 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.utils; + +import java.util.Date; + +import com.microsoft.windowsazure.core.RFC1123DateConverter; + +/** + * Represents a set of access conditions for operations that use storage + * services. + */ +public final class AccessConditionHeader { + + /** + * Specifies an access condition with no conditions set. + */ + public static final AccessConditionHeader NONE = new AccessConditionHeader( + AccessConditionHeaderType.NONE, null); + + /** + * Creates an access condition that only allows an operation if the + * resource's ETag value matches the specified ETag value. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-Match conditional header. If this access condition is set, the + * operation is performed only if the ETag of the resource matches the + * specified ETag. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param etag + * A String that represents the ETag value to check. + * + * @return An AccessCondition object that represents the + * If-Match condition. + */ + public static AccessConditionHeader ifMatch(String etag) { + return new AccessConditionHeader(AccessConditionHeaderType.IF_MATCH, + etag); + } + + /** + * Creates an access condition that only allows an operation if the resource + * has been modified since the specified time. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-Modified-Since conditional header. If this access condition is + * set, the operation is performed only if the resource has been modified + * since the specified time. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param lastMotified + * A java.util.Date object that represents the + * last-modified time to check for the resource. + * + * @return An AccessCondition object that represents the + * If-Modified-Since condition. + */ + public static AccessConditionHeader ifModifiedSince(Date lastMotified) { + return new AccessConditionHeader( + AccessConditionHeaderType.IF_MODIFIED_SINCE, + new RFC1123DateConverter().format(lastMotified)); + } + + /** + * Creates an access condition that only allows an operation if the + * resource's ETag value does not match the specified ETag value. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-None-Match conditional header. If this access condition is set, + * the operation is performed only if the ETag of the resource does not + * match the specified ETag. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param etag + * A String that represents the ETag value to check. + * + * @return An AccessCondition object that represents the + * If-None-Match condition. + */ + public static AccessConditionHeader ifNoneMatch(String etag) { + return new AccessConditionHeader( + AccessConditionHeaderType.IF_NONE_MATCH, etag); + } + + /** + * Creates an access condition that only allows an operation if the resource + * has not been modified since the specified time. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-Unmodified-Since conditional header. If this access condition + * is set, the operation is performed only if the resource has not been + * modified since the specified time. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param lastMotified + * A java.util.Date object that represents the + * last-modified time to check for the resource. + * + * @return An AccessCondition object that represents the + * If-Unmodified-Since condition. + */ + public static AccessConditionHeader ifNotModifiedSince(Date lastMotified) { + return new AccessConditionHeader( + AccessConditionHeaderType.IF_UNMODIFIED_SINCE, + new RFC1123DateConverter().format(lastMotified)); + } + + /** + * Represents the access condition header type. + */ + private AccessConditionHeaderType header = AccessConditionHeaderType.NONE; + + /** + * Represents the access condition header value. + */ + private String value; + + /** + * Creates an instance of the AccessCondition class. + */ + protected AccessConditionHeader() { + // Empty Default Ctor + } + + /** + * Creates an instance of the AccessCondition class using the + * specified header type and value. + * + * @param headerType + * An {@link AccessConditionHeaderType} value that represents the + * header type. + * @param value + * A String that represents the value of the header. + */ + protected AccessConditionHeader(AccessConditionHeaderType headerType, + String value) { + this.setHeader(headerType); + this.setValue(value); + } + + /** + * Gets the access condition header type set in this + * AccessCondition instance. + * + * @return The {@link AccessConditionHeaderType} set in this + * AccessCondition instance. + */ + public AccessConditionHeaderType getHeader() { + return header; + } + + /** + * Sets the access condition header type in this + * AccessCondition instance. + * + * @param header + * The {@link AccessConditionHeaderType} to set in this + * AccessCondition instance. + */ + public void setHeader(AccessConditionHeaderType header) { + this.header = header; + } + + /** + * Gets the access condition value set in this AccessCondition + * instance. + * + * @return A {@link String} containing the access condition value set in + * this AccessCondition instance. + */ + public String getValue() { + return value; + } + + /** + * Sets the access condition value in this AccessCondition + * instance. + * + * @param value + * A {@link String} containing the access condition value to set + * in this AccessCondition instance. + */ + public void setValue(String value) { + this.value = value; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessConditionHeaderType.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/AccessConditionHeaderType.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessConditionHeaderType.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/AccessConditionHeaderType.java index ecfea0b1da5af..d5f58b20afc5a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessConditionHeaderType.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/AccessConditionHeaderType.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.blob.models; +package com.microsoft.windowsazure.core.utils; /** * Specifies the kinds of conditional headers that may be set for a request. @@ -44,23 +44,25 @@ public enum AccessConditionHeaderType { IF_NONE_MATCH; /** - * Returns a string representation of the current value, or an empty string if no value is assigned. + * Returns a string representation of the current value, or an empty string + * if no value is assigned. * - * @return A String that represents the currently assigned value. + * @return A String that represents the currently assigned + * value. */ @Override public String toString() { switch (this) { - case IF_MATCH: - return "If-Match"; - case IF_UNMODIFIED_SINCE: - return "If-Unmodified-Since"; - case IF_MODIFIED_SINCE: - return "If-Modified-Since"; - case IF_NONE_MATCH: - return "If-None-Match"; - default: - return ""; + case IF_MATCH: + return "If-Match"; + case IF_UNMODIFIED_SINCE: + return "If-Unmodified-Since"; + case IF_MODIFIED_SINCE: + return "If-Modified-Since"; + case IF_NONE_MATCH: + return "If-None-Match"; + default: + return ""; } } } diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/BOMInputStream.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/BOMInputStream.java new file mode 100644 index 0000000000000..46bb4c2831340 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/BOMInputStream.java @@ -0,0 +1,234 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PushbackInputStream; + +public class BOMInputStream extends InputStream { + /** + * Constructs a new BOMInputStream. + * + * @param inputStream an InputStream. + * + */ + public BOMInputStream(final InputStream inputStream) throws NullPointerException, + IOException { + if (inputStream == null) { + throw new NullPointerException(); + } + + pushbackInputStream = new PushbackInputStream(inputStream, 4); + + final byte [] bom = new byte[4]; + final int read = pushbackInputStream.read(bom); + + switch(read) { + case 4: + if ((bom[0] == (byte) 0xFF) + && (bom[1] == (byte) 0xFE) + && (bom[2] == (byte) 0x00) + && (bom[3] == (byte) 0x00)) { + this.bom = BOM.UTF_32_LE; + break; + } + else + if ((bom[0] == (byte) 0x00) + && (bom[1] == (byte) 0x00) + && (bom[2] == (byte) 0xFE) + && (bom[3] == (byte) 0xFF)) { + this.bom = BOM.UTF_32_BE; + break; + } + + case 3: + if ((bom[0] == (byte) 0xEF) + && (bom[1] == (byte) 0xBB) + && (bom[2] == (byte) 0xBF)) { + this.bom = BOM.UTF_8; + break; + } + + case 2: + if ((bom[0] == (byte) 0xFF) + && (bom[1] == (byte) 0xFE)) { + this.bom = BOM.UTF_16_LE; + break; + } + else if ((bom[0] == (byte) 0xFE) + && (bom[1] == (byte) 0xFF)) { + this.bom = BOM.UTF_16_BE; + break; + } + + default: + this.bom = BOM.NONE; + break; + } + + if (read > 0) { + // If bytes read were not from a BOM, unread them. + pushbackInputStream.unread(bom, 0, read); + } + + if (this.bom != BOM.NONE) { + pushbackInputStream.skip(this.bom.bytes.length); + } + } + + /** + * {@inheritDoc} + */ + public int read() throws IOException { + return pushbackInputStream.read(); + } + + /** + * {@inheritDoc} + */ + public int read(final byte [] b) throws IOException, + NullPointerException { + return pushbackInputStream.read(b, 0, b.length); + } + + /** + * {@inheritDoc} + */ + public int read(final byte [] b, + final int off, + final int len) throws IOException, + NullPointerException { + return pushbackInputStream.read(b, off, len); + } + + /** + * {@inheritDoc} + */ + public long skip(final long n) throws IOException { + return pushbackInputStream.skip(n); + } + + /** + * {@inheritDoc} + */ + public int available() throws IOException { + return pushbackInputStream.available(); + } + + /** + * {@inheritDoc} + */ + public void close() throws IOException { + pushbackInputStream.close(); + } + + /** + * {@inheritDoc} + */ + public synchronized void mark(final int readlimit) { + pushbackInputStream.mark(readlimit); + } + + /** + * {@inheritDoc} + */ + public synchronized void reset() throws IOException { + pushbackInputStream.reset(); + } + + /** + * {@inheritDoc} + */ + public boolean markSupported() { + return pushbackInputStream.markSupported(); + } + + private final PushbackInputStream pushbackInputStream; + private final BOM bom; + + public static final class BOM { + /** + * NONE. + */ + public static final BOM NONE = new BOM(new byte[] {}, "NONE"); + + /** + * UTF-8 BOM (EF BB BF). + */ + public static final BOM UTF_8 = new BOM(new byte[] {(byte) 0xEF, + (byte) 0xBB, + (byte) 0xBF }, + "UTF-8"); + + /** + * UTF-16, little-endian (FF FE). + */ + public static final BOM UTF_16_LE = new BOM(new byte[] {(byte) 0xFF, + (byte) 0xFE }, + "UTF-16 little-endian"); + + /** + * UTF-16, big-endian (FE FF). + */ + public static final BOM UTF_16_BE = new BOM(new byte[] {(byte) 0xFE, + (byte) 0xFF }, + "UTF-16 big-endian"); + + /** + * UTF-32, little-endian (FF FE 00 00). + */ + public static final BOM UTF_32_LE = new BOM(new byte[] {(byte) 0xFF, + (byte) 0xFE, + (byte) 0x00, + (byte) 0x00 }, + "UTF-32 little-endian"); + + /** + * UTF-32, big-endian (00 00 FE FF). + */ + public static final BOM UTF_32_BE = new BOM(new byte[] {(byte) 0x00, + (byte) 0x00, + (byte) 0xFE, + (byte) 0xFF }, + "UTF-32 big-endian"); + + /** + * Returns a String representation of this BOM + * value. + */ + public String toString() { + return description; + } + + /** + * Returns the bytes corresponding to this BOM value. + */ + public byte[] getBytes() { + final byte[] result = new byte[bytes.length]; + System.arraycopy(bytes, 0, result, 0, bytes.length); + return result; + } + + private BOM(final byte [] bom, final String description) { + this.bytes = bom; + this.description = description; + } + + private final byte [] bytes; + private final String description; + } +} \ No newline at end of file diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/Base64.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/Base64.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/Base64.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/Base64.java index 8e8c79aaaa2fb..81295e98307b2 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/Base64.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/Base64.java @@ -12,10 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core.storage.utils; +package com.microsoft.windowsazure.core.utils; /** - * RESERVED FOR INTERNAL USE. Provides Base64 encoding, decoding, and validation functionality. + * RESERVED FOR INTERNAL USE. Provides Base64 encoding, decoding, and validation + * functionality. */ public final class Base64 { /** @@ -26,26 +27,34 @@ public final class Base64 { /** * Decoded values, -1 is invalid character, -2 is = pad character. */ - private static final byte DECODE_64[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0-15 - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* - * 16- 31 - */ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* - * 32- 47 - */ - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, /* - * 48- 63 - */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 64-79 */ - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* - * 80- 95 - */ - -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* - * 96- 111 - */ - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* - * 112- 127 - */ + private static final byte [] DECODE_64 = { + -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, // 0-15 + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* + * 16- + * 31 + */ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* + * 32- + * 47 + */ + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, /* + * 48- + * 63 + */ + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 64-79 */ + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* + * 80- + * 95 + */ + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* + * 96- + * 111 + */ + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* + * 112- + * 127 + */ }; /** @@ -63,8 +72,7 @@ public static byte[] decode(final String data) { if (data.endsWith("==")) { byteArrayLength -= 2; - } - else if (data.endsWith("=")) { + } else if (data.endsWith("=")) { byteArrayLength -= 1; } @@ -81,7 +89,8 @@ else if (data.endsWith("=")) { if (char1 < 0 || char2 < 0 || char3 == -1 || char4 == -1) { // invalid character(-1), or bad padding (-2) - throw new IllegalArgumentException("The String is not a valid Base64-encoded string."); + throw new IllegalArgumentException( + "The String is not a valid Base64-encoded string."); } int tVal = char1 << 18; @@ -93,15 +102,13 @@ else if (data.endsWith("=")) { // two "==" pad chars, check bits 12-24 tVal &= 0x00FFF000; retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); - } - else if (char4 == -2) { + } else if (char4 == -2) { // one pad char "=" , check bits 6-24. tVal &= 0x00FFFFC0; retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF); - } - else { + } else { // No pads take all 3 bytes, bits 0-24 retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF); @@ -126,8 +133,7 @@ public static Byte[] decodeAsByteObjectArray(final String data) { if (data.endsWith("==")) { byteArrayLength -= 2; - } - else if (data.endsWith("=")) { + } else if (data.endsWith("=")) { byteArrayLength -= 1; } @@ -144,7 +150,8 @@ else if (data.endsWith("=")) { if (char1 < 0 || char2 < 0 || char3 == -1 || char4 == -1) { // invalid character(-1), or bad padding (-2) - throw new IllegalArgumentException("The String is not a valid Base64-encoded string."); + throw new IllegalArgumentException( + "The String is not a valid Base64-encoded string."); } int tVal = char1 << 18; @@ -156,15 +163,13 @@ else if (data.endsWith("=")) { // two "==" pad chars, check bits 12-24 tVal &= 0x00FFF000; retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); - } - else if (char4 == -2) { + } else if (char4 == -2) { // one pad char "=" , check bits 6-24. tVal &= 0x00FFFFC0; retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF); - } - else { + } else { // No pads take all 3 bytes, bits 0-24 retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF); @@ -190,13 +195,12 @@ public static String encode(final byte[] data) { for (; j < data.length; j += 3) { if (j < data.length - dataRemainder) { - n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8) + (data[j + 2] & 0xFF); - } - else { + n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8) + + (data[j + 2] & 0xFF); + } else { if (dataRemainder == 1) { n = (data[j] & 0xFF) << 16; - } - else if (dataRemainder == 2) { + } else if (dataRemainder == 2) { n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8); } } @@ -217,8 +221,7 @@ else if (dataRemainder == 2) { // append '=' to pad if (data.length % 3 == 1) { builder.replace(bLength - 2, bLength, "=="); - } - else if (data.length % 3 == 2) { + } else if (data.length % 3 == 2) { builder.replace(bLength - 1, bLength, "="); } @@ -241,13 +244,12 @@ public static String encode(final Byte[] data) { for (; j < data.length; j += 3) { if (j < data.length - dataRemainder) { - n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8) + (data[j + 2] & 0xFF); - } - else { + n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8) + + (data[j + 2] & 0xFF); + } else { if (dataRemainder == 1) { n = (data[j] & 0xFF) << 16; - } - else if (dataRemainder == 2) { + } else if (dataRemainder == 2) { n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8); } } @@ -268,8 +270,7 @@ else if (dataRemainder == 2) { // append '=' to pad if (data.length % 3 == 1) { builder.replace(bLength - 2, bLength, "=="); - } - else if (data.length % 3 == 2) { + } else if (data.length % 3 == 2) { builder.replace(bLength - 1, bLength, "="); } @@ -281,7 +282,8 @@ else if (data.length % 3 == 2) { * * @param data * the string, as a String object, to validate - * @return true if data is a valid Base64 string, otherwise false + * @return true if data is a valid Base64 string, + * otherwise false */ public static boolean validateIsBase64String(final String data) { @@ -296,8 +298,8 @@ public static boolean validateIsBase64String(final String data) { if (DECODE_64[charByte] == -2) { if (m < data.length() - 2) { return false; - } - else if (m == data.length() - 2 && DECODE_64[(byte) data.charAt(m + 1)] != -2) { + } else if (m == data.length() - 2 + && DECODE_64[(byte) data.charAt(m + 1)] != -2) { return false; } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/CommaStringBuilder.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/CommaStringBuilder.java similarity index 94% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/CommaStringBuilder.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/CommaStringBuilder.java index 55558ed7fd30a..c8561bf5b1aff 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/CommaStringBuilder.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/CommaStringBuilder.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils; +package com.microsoft.windowsazure.core.utils; import java.util.List; @@ -54,8 +54,10 @@ public static String join(String... values) { @Override public String toString() { - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } + return sb.toString(); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ConnectionStringSyntaxException.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/ConnectionStringSyntaxException.java similarity index 94% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ConnectionStringSyntaxException.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/ConnectionStringSyntaxException.java index 4b611302e2caf..6fb8137df6f10 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ConnectionStringSyntaxException.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/ConnectionStringSyntaxException.java @@ -13,7 +13,7 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils; +package com.microsoft.windowsazure.core.utils; public class ConnectionStringSyntaxException extends Exception { diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/Constants.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/Constants.java new file mode 100644 index 0000000000000..f1fd99ec0335a --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/Constants.java @@ -0,0 +1,694 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.utils; + +/** + * Defines constants for use with blob operations, HTTP headers, and query + * strings. + */ +public final class Constants { + /** + * Defines constants for use Analytics requests. + */ + public static class AnalyticsConstants { + /** + * The XML element for the Analytics RetentionPolicy Days. + */ + public static final String DAYS_ELEMENT = "Days"; + + /** + * The XML element for the Default Service Version. + */ + public static final String DEFAULT_SERVICE_VERSION = "DefaultServiceVersion"; + + /** + * The XML element for the Analytics Logging Delete type. + */ + public static final String DELETE_ELEMENT = "Delete"; + + /** + * The XML element for the Analytics RetentionPolicy Enabled. + */ + public static final String ENABLED_ELEMENT = "Enabled"; + + /** + * The XML element for the Analytics Metrics IncludeAPIs. + */ + public static final String INCLUDE_APIS_ELEMENT = "IncludeAPIs"; + + /** + * The XML element for the Analytics Logging + */ + public static final String LOGGING_ELEMENT = "Logging"; + + /** + * The XML element for the Analytics Metrics + */ + public static final String METRICS_ELEMENT = "Metrics"; + + /** + * The XML element for the Analytics Logging Read type. + */ + public static final String READ_ELEMENT = "Read"; + + /** + * The XML element for the Analytics RetentionPolicy. + */ + public static final String RETENTION_POLICY_ELEMENT = "RetentionPolicy"; + + /** + * The XML element for the StorageServiceProperties + */ + public static final String STORAGE_SERVICE_PROPERTIES_ELEMENT = "StorageServiceProperties"; + + /** + * The XML element for the Analytics Version + */ + public static final String VERSION_ELEMENT = "Version"; + + /** + * The XML element for the Analytics Logging Write type. + */ + public static final String WRITE_ELEMENT = "Write"; + } + + /** + * Defines constants for use with HTTP headers. + */ + public static class HeaderConstants { + /** + * The Accept header. + */ + public static final String ACCEPT = "Accept"; + + /** + * The Accept header. + */ + public static final String ACCEPT_CHARSET = "Accept-Charset"; + + /** + * The Authorization header. + */ + public static final String AUTHORIZATION = "Authorization"; + + /** + * The CacheControl header. + */ + public static final String CACHE_CONTROL = "Cache-Control"; + + /** + * The header that specifies blob caching control. + */ + public static final String CACHE_CONTROL_HEADER = PREFIX_FOR_STORAGE_HEADER + + "blob-cache-control"; + + /** + * The Comp value. + */ + public static final String COMP = "comp"; + + /** + * The ContentEncoding header. + */ + public static final String CONTENT_ENCODING = "Content-Encoding"; + + /** + * The ContentLangauge header. + */ + public static final String CONTENT_LANGUAGE = "Content-Language"; + + /** + * The ContentLength header. + */ + public static final String CONTENT_LENGTH = "Content-Length"; + + /** + * The ContentMD5 header. + */ + public static final String CONTENT_MD5 = "Content-MD5"; + + /** + * The ContentRange header. + */ + public static final String CONTENT_RANGE = "Cache-Range"; + + /** + * The ContentType header. + */ + public static final String CONTENT_TYPE = "Content-Type"; + + /** + * The header for copy source. + */ + public static final String COPY_SOURCE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "copy-source"; + + /** + * The header that specifies the date. + */ + public static final String DATE = PREFIX_FOR_STORAGE_HEADER + "date"; + + /** + * The header to delete snapshots. + */ + public static final String DELETE_SNAPSHOT_HEADER = PREFIX_FOR_STORAGE_HEADER + + "delete-snapshots"; + + /** + * The ETag header. + */ + public static final String ETAG = "ETag"; + + /** + * Buffer width used to copy data to output streams. + */ + public static final int HTTP_UNUSED_306 = 306; + + /** + * The IfMatch header. + */ + public static final String IF_MATCH = "If-Match"; + + /** + * The IfModifiedSince header. + */ + public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; + + /** + * The IfNoneMatch header. + */ + public static final String IF_NONE_MATCH = "If-None-Match"; + + /** + * The IfUnmodifiedSince header. + */ + public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; + + /** + * The header that specifies lease ID. + */ + public static final String LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "lease-id"; + + /** + * The header that specifies lease status. + */ + public static final String LEASE_STATUS = PREFIX_FOR_STORAGE_HEADER + + "lease-status"; + + /** + * The header that specifies lease state. + */ + public static final String LEASE_STATE = PREFIX_FOR_STORAGE_HEADER + + "lease-state"; + + /** + * The header that specifies lease duration. + */ + public static final String LEASE_DURATION = PREFIX_FOR_STORAGE_HEADER + + "lease-duration"; + + /** + * The header that specifies copy status. + */ + public static final String COPY_STATUS = PREFIX_FOR_STORAGE_HEADER + + "copy-status"; + + /** + * The header that specifies copy progress. + */ + public static final String COPY_PROGRESS = PREFIX_FOR_STORAGE_HEADER + + "copy-progress"; + + /** + * The header that specifies copy status description. + */ + public static final String COPY_STATUS_DESCRIPTION = PREFIX_FOR_STORAGE_HEADER + + "copy-status-description"; + + /** + * The header that specifies copy id. + */ + public static final String COPY_ID = PREFIX_FOR_STORAGE_HEADER + + "copy-id"; + + /** + * The header that specifies copy source. + */ + public static final String COPY_SOURCE = PREFIX_FOR_STORAGE_HEADER + + "copy-source"; + + /** + * The header that specifies copy completion time. + */ + public static final String COPY_COMPLETION_TIME = PREFIX_FOR_STORAGE_HEADER + + "copy-completion-time"; + + /** + * The header prefix for metadata. + */ + public static final String PREFIX_FOR_STORAGE_METADATA = "x-ms-meta-"; + + /** + * The header prefix for properties. + */ + public static final String PREFIX_FOR_STORAGE_PROPERTIES = "x-ms-prop-"; + + /** + * The Range header. + */ + public static final String RANGE = "Range"; + + /** + * The header that specifies if the request will populate the ContentMD5 + * header for range gets. + */ + public static final String RANGE_GET_CONTENT_MD5 = PREFIX_FOR_STORAGE_HEADER + + "range-get-content-md5"; + + /** + * The format string for specifying ranges. + */ + public static final String RANGE_HEADER_FORMAT = "bytes=%d-%d"; + + /** + * The header that indicates the request ID. + */ + public static final String REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "request-id"; + + /** + * The header that indicates the client request ID. + */ + public static final String CLIENT_REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "client-request-id"; + + /** + * The header for the If-Match condition. + */ + public static final String SOURCE_IF_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-match"; + + /** + * The header for the If-Modified-Since condition. + */ + public static final String SOURCE_IF_MODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-modified-since"; + + /** + * The header for the If-None-Match condition. + */ + public static final String SOURCE_IF_NONE_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-none-match"; + + /** + * The header for the If-Unmodified-Since condition. + */ + public static final String SOURCE_IF_UNMODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-unmodified-since"; + + /** + * The header for the source lease id. + */ + public static final String SOURCE_LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-lease-id"; + + /** + * The header for data ranges. + */ + public static final String STORAGE_RANGE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "range"; + + /** + * The header for storage version. + */ + public static final String STORAGE_VERSION_HEADER = PREFIX_FOR_STORAGE_HEADER + + "version"; + + /** + * The current storage version header value. + */ + public static final String TARGET_STORAGE_VERSION = "2012-02-12"; + + /** + * The UserAgent header. + */ + public static final String USER_AGENT = "User-Agent"; + + /** + * Specifies the value to use for UserAgent header. + */ + public static final String USER_AGENT_PREFIX = "WA-Storage"; + + /** + * Specifies the value to use for UserAgent header. + */ + public static final String USER_AGENT_VERSION = "Client v0.1.3.2"; + } + + /** + * Defines constants for use with query strings. + */ + public static class QueryConstants { + /** + * The query component for the SAS signature. + */ + public static final String SIGNATURE = "sig"; + + /** + * The query component for the signed SAS expiry time. + */ + public static final String SIGNED_EXPIRY = "se"; + + /** + * The query component for the signed SAS identifier. + */ + public static final String SIGNED_IDENTIFIER = "si"; + + /** + * The query component for the signed SAS permissions. + */ + public static final String SIGNED_PERMISSIONS = "sp"; + + /** + * The query component for the signed SAS resource. + */ + public static final String SIGNED_RESOURCE = "sr"; + + /** + * The query component for the signed SAS start time. + */ + public static final String SIGNED_START = "st"; + + /** + * The query component for the SAS start partition key. + */ + public static final String START_PARTITION_KEY = "spk"; + + /** + * The query component for the SAS start row key. + */ + public static final String START_ROW_KEY = "srk"; + + /** + * The query component for the SAS end partition key. + */ + public static final String END_PARTITION_KEY = "epk"; + + /** + * The query component for the SAS end row key. + */ + public static final String END_ROW_KEY = "erk"; + + /** + * The query component for the SAS table name. + */ + public static final String SAS_TABLE_NAME = "tn"; + + /** + * The query component for the signing SAS key. + */ + public static final String SIGNED_KEY = "sk"; + + /** + * The query component for the signed SAS version. + */ + public static final String SIGNED_VERSION = "sv"; + + /** + * The query component for snapshot time. + */ + public static final String SNAPSHOT = "snapshot"; + } + + /** + * The master Windows Azure Storage header prefix. + */ + public static final String PREFIX_FOR_STORAGE_HEADER = "x-ms-"; + + /** + * Constant representing a kilobyte (Non-SI version). + */ + public static final int KB = 1024; + + /** + * Constant representing a megabyte (Non-SI version). + */ + public static final int MB = 1024 * KB; + + /** + * Constant representing a gigabyte (Non-SI version). + */ + public static final int GB = 1024 * MB; + + /** + * Buffer width used to copy data to output streams. + */ + public static final int BUFFER_COPY_LENGTH = 8 * KB; + + /** + * Default client side timeout, in milliseconds, for all service clients. + */ + public static final int DEFAULT_TIMEOUT_IN_MS = 90 * 1000; + + /** + * XML element for delimiters. + */ + public static final String DELIMITER_ELEMENT = "Delimiter"; + + /** + * An empty String to use for comparison. + */ + public static final String EMPTY_STRING = ""; + + /** + * XML element for page range end elements. + */ + public static final String END_ELEMENT = "End"; + + /** + * XML element for error codes. + */ + public static final String ERROR_CODE = "Code"; + + /** + * XML element for exception details. + */ + public static final String ERROR_EXCEPTION = "ExceptionDetails"; + + /** + * XML element for exception messages. + */ + public static final String ERROR_EXCEPTION_MESSAGE = "ExceptionMessage"; + + /** + * XML element for stack traces. + */ + public static final String ERROR_EXCEPTION_STACK_TRACE = "StackTrace"; + + /** + * XML element for error messages. + */ + public static final String ERROR_MESSAGE = "Message"; + + /** + * XML root element for errors. + */ + public static final String ERROR_ROOT_ELEMENT = "Error"; + + /** + * XML element for the ETag. + */ + public static final String ETAG_ELEMENT = "Etag"; + + /** + * Constant for False. + */ + public static final String FALSE = "false"; + + /** + * Specifies HTTP. + */ + public static final String HTTP = "http"; + + /** + * Specifies HTTPS. + */ + public static final String HTTPS = "https"; + + /** + * XML attribute for IDs. + */ + public static final String ID = "Id"; + + /** + * XML element for an invalid metadata name. + */ + public static final String INVALID_METADATA_NAME = "x-ms-invalid-name"; + + /** + * XML element for the last modified date. + */ + public static final String LAST_MODIFIED_ELEMENT = "Last-Modified"; + + /** + * XML element for the lease status. + */ + public static final String LEASE_STATUS_ELEMENT = "LeaseStatus"; + + /** + * XML element for the lease state. + */ + public static final String LEASE_STATE_ELEMENT = "LeaseState"; + + /** + * XML element for the lease duration. + */ + public static final String LEASE_DURATION_ELEMENT = "LeaseDuration"; + + /** + * XML element for the copy id. + */ + public static final String COPY_ID_ELEMENT = "CopyId"; + + /** + * XML element for the copy status. + */ + public static final String COPY_STATUS_ELEMENT = "CopyStatus"; + + /** + * XML element for the copy source . + */ + public static final String COPY_SOURCE_ELEMENT = "CopySource"; + + /** + * XML element for the copy progress. + */ + public static final String COPY_PROGRESS_ELEMENT = "CopyProgress"; + + /** + * XML element for the copy completion time. + */ + public static final String COPY_COMPLETION_TIME_ELEMENT = "CopyCompletionTime"; + + /** + * XML element for the copy status description. + */ + public static final String COPY_STATUS_DESCRIPTION_ELEMENT = "CopyStatusDescription"; + + /** + * Constant signaling the resource is locked. + */ + public static final String LOCKED_VALUE = "Locked"; + + /** + * XML element for a marker. + */ + public static final String MARKER_ELEMENT = "Marker"; + + /** + * XML element for maximum results. + */ + public static final String MAX_RESULTS_ELEMENT = "MaxResults"; + + /** + * Number of default concurrent requests for parallel operation. + */ + public static final int MAXIMUM_SEGMENTED_RESULTS = 5000; + + /** + * The maximum size, in bytes, of a given stream mark operation. + */ + // Note if BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES is updated + // then this needs to be as well. + public static final int MAX_MARK_LENGTH = 64 * MB; + + /** + * XML element for the metadata. + */ + public static final String METADATA_ELEMENT = "Metadata"; + + /** + * XML element for names. + */ + public static final String NAME_ELEMENT = "Name"; + + /** + * XML element for the next marker. + */ + public static final String NEXT_MARKER_ELEMENT = "NextMarker"; + + /** + * XML element for a prefix. + */ + public static final String PREFIX_ELEMENT = "Prefix"; + + /** + * Constant for True. + */ + public static final String TRUE = "true"; + + /** + * Constant signaling the resource is unlocked. + */ + public static final String UNLOCKED_VALUE = "Unlocked"; + + /** + * XML element for the URL. + */ + public static final String URL_ELEMENT = "Url"; + + /** + * XML element for a signed identifier. + */ + public static final String SIGNED_IDENTIFIER_ELEMENT = "SignedIdentifier"; + + /** + * XML element for signed identifiers. + */ + public static final String SIGNED_IDENTIFIERS_ELEMENT = "SignedIdentifiers"; + + /** + * XML element for an access policy. + */ + public static final String ACCESS_POLICY = "AccessPolicy"; + + /** + * Maximum number of shared access policy identifiers supported by server. + */ + public static final int MAX_SHARED_ACCESS_POLICY_IDENTIFIERS = 5; + + /** + * XML element for the start time of an access policy. + */ + public static final String START = "Start"; + + /** + * XML element for the end time of an access policy. + */ + public static final String EXPIRY = "Expiry"; + + /** + * XML element for the permission of an access policy. + */ + public static final String PERMISSION = "Permission"; + + /** + * Private Default Ctor + */ + private Constants() { + // No op + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/DateFactory.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/DateFactory.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/DateFactory.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/DateFactory.java index 219a08a45ac94..8c8c49cf7ffa7 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/DateFactory.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/DateFactory.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils; +package com.microsoft.windowsazure.core.utils; import java.util.Date; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/DefaultDateFactory.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/DefaultDateFactory.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/DefaultDateFactory.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/DefaultDateFactory.java index b7fa4f4447dfb..1ea441ad8a064 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/DefaultDateFactory.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/DefaultDateFactory.java @@ -12,11 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils; +package com.microsoft.windowsazure.core.utils; import java.util.Date; public class DefaultDateFactory implements DateFactory { + @Override public Date getDate() { return new Date(); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ExportUtils.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/ExportUtils.java similarity index 75% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ExportUtils.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/ExportUtils.java index d07a57c029418..6a37098f4ee64 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ExportUtils.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/ExportUtils.java @@ -13,13 +13,13 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils; +package com.microsoft.windowsazure.core.utils; import java.util.Map; /** * Helper functions useful when creating Exports classses. - * + * */ public abstract class ExportUtils { @@ -36,15 +36,19 @@ private static String normalizeProfile(String profile) { } /** - * Check if the given property exists under the given profile. If - * so, return the value, otherwise return null. - * - * @param profile profile to search - * @param properties the set of property values - * @param propertyName name of desired property + * Check if the given property exists under the given profile. If so, return + * the value, otherwise return null. + * + * @param profile + * profile to search + * @param properties + * the set of property values + * @param propertyName + * name of desired property * @return the property value, or null if it is not set. */ - public static Object getPropertyIfExists(String profile, Map properties, String propertyName) { + public static Object getPropertyIfExists(String profile, + Map properties, String propertyName) { String fullPropertyName = normalizeProfile(profile) + propertyName; if (properties.containsKey(fullPropertyName)) { @@ -52,5 +56,4 @@ public static Object getPropertyIfExists(String profile, Map pro } return null; } - } diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/Exports.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/Exports.java new file mode 100644 index 0000000000000..7506c291a29af --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/Exports.java @@ -0,0 +1,47 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.utils; + +import java.util.Map; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; + +public class Exports implements Builder.Exports { + @Override + public void register(Builder.Registry registry) { + registry.add(DateFactory.class, DefaultDateFactory.class); + registry.add(KeyStoreCredential.class); + + registry.add(new Builder.Factory() { + @Override + public KeyStoreType create(String profile, + Class service, Builder builder, + Map properties) { + KeyStoreType keyStoreType = null; + + Object keyStoreTypeObject = properties.get(ManagementConfiguration.KEYSTORE_TYPE); + if (keyStoreTypeObject.getClass() == KeyStoreType.class) { + keyStoreType = (KeyStoreType) keyStoreTypeObject; + } + else if (keyStoreTypeObject.getClass() == String.class) { + keyStoreType = KeyStoreType.fromString((String) properties.get(ManagementConfiguration.KEYSTORE_TYPE)); + } + + return keyStoreType; + } + }); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/InputStreamDataSource.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/InputStreamDataSource.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/InputStreamDataSource.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/InputStreamDataSource.java index 02c5fd31bb477..4a6c0a7f3b752 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/InputStreamDataSource.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/InputStreamDataSource.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.table.implementation; +package com.microsoft.windowsazure.core.utils; import java.io.IOException; import java.io.InputStream; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/KeyStoreCredential.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/KeyStoreCredential.java similarity index 77% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/KeyStoreCredential.java rename to core/src/main/java/com/microsoft/windowsazure/core/utils/KeyStoreCredential.java index c58b8d77eb5e1..0e9e30eab065b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/KeyStoreCredential.java +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/KeyStoreCredential.java @@ -13,10 +13,14 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.management.implementation; +package com.microsoft.windowsazure.core.utils; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; import java.io.IOException; +import javax.inject.Inject; +import javax.inject.Named; + /** * The Class KeyStoreCredential. */ @@ -43,17 +47,24 @@ public class KeyStoreCredential { * @throws IOException * when a I/O exception has occurred. */ - public KeyStoreCredential(String keyStorePath, String keyStorePassword, KeyStoreType keyStoreType) - throws IOException { + @Inject + public KeyStoreCredential(@Named(ManagementConfiguration.KEYSTORE_PATH) String keyStorePath, @Named(ManagementConfiguration.KEYSTORE_PASSWORD) String keyStorePassword, + @Named(ManagementConfiguration.KEYSTORE_TYPE) KeyStoreType keyStoreType) throws IOException { this.keystorePassword = keyStorePassword; this.keyStorePath = keyStorePath; this.keyStoreType = keyStoreType; } + public KeyStoreCredential(String keyStorePath, String keyStorePassword) + throws IOException { + this(keyStorePath, keyStorePassword, KeyStoreType.jks); + } + /** * Gets the type of the key store. * - * @return A KeyStoreType representing the type of the key store. + * @return A KeyStoreType representing the type of the key + * store. */ public KeyStoreType getKeyStoreType() { return keyStoreType; @@ -62,7 +73,8 @@ public KeyStoreType getKeyStoreType() { /** * Gets the keystore password. * - * @return A String instance representing the password of the keystore. + * @return A String instance representing the password of the + * keystore. */ public String getKeystorePassword() { return keystorePassword; @@ -76,5 +88,4 @@ public String getKeystorePassword() { public String getKeyStorePath() { return this.keyStorePath; } - -} +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/KeyStoreType.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/KeyStoreType.java new file mode 100644 index 0000000000000..10b80927b5912 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/KeyStoreType.java @@ -0,0 +1,47 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.utils; + +import java.security.InvalidParameterException; + +/** + * The Enum representing the type of the KeyStore. + */ +public enum KeyStoreType { + + /** The jceks. */ + jceks, + /** The jks. */ + jks, + /** The pkcs12. */ + pkcs12; + + public static KeyStoreType fromString(String keyStoreTypeString) { + if (keyStoreTypeString != null) { + if (keyStoreTypeString.equals("jceks")) { + return KeyStoreType.jceks; + } else if (keyStoreTypeString.equals("jks")) { + return KeyStoreType.jks; + } else if (keyStoreTypeString.equals("pkcs12")) { + return KeyStoreType.pkcs12; + } else { + throw new InvalidParameterException(String.format("keyStoreTypeString value %s cannot be recognized.", keyStoreTypeString)); + } + } else { + return KeyStoreType.jks; + } + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/ParsedConnectionString.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/ParsedConnectionString.java new file mode 100644 index 0000000000000..2a3cc1cd0f7f7 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/ParsedConnectionString.java @@ -0,0 +1,348 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.utils; + +import com.microsoft.windowsazure.core.pipeline.ConnectionStringField; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Base class representing an Azure connection string. This provides parsing + * logic to split the string up into the various fields. + */ +public abstract class ParsedConnectionString { + private String connectionString; + private int currentIndex; + private String currentKey; + private String currentValue; + + public ParsedConnectionString(String connectionString) + throws ConnectionStringSyntaxException { + // Forcing a separator at the end makes implementation below + // easier - don't have to check for end of string everywhere + this.connectionString = connectionString + ';'; + this.currentIndex = 0; + + matchConnectionString(); + } + + private char currentChar() { + return connectionString.charAt(currentIndex); + } + + private void consumeChar() { + currentIndex++; + } + + private boolean charsLeft() { + return currentIndex < connectionString.length(); + } + + // + // PEG Grammar for a connection string: + // + // ConnectionString <- Attribute (Separator+ Attribute)* Separator* END + // Attribute <- Spacing (KeyValuePair / &Separator) + // KeyValuePair <- Key Equals Spacing Value + // Key <- QuotedKey / RawKey + // QuotedKey <- DoubleQuote (!DoubleQuote .)* DoubleQuote / SingleQuote + // (!SingleQuote .)* SingleQuote + // RawKey <- (!Equals .)+ + // Equals <- Spacing '=' + // Value <- QuotedValue / RawValue + // QuotedValue <- DoubleQuote (!DoubleQuote .)* DoubleQuote / SingleQuote + // (!SingleQuote .*) SingleQuote + // RawValue <- (!Separator .)* + // Separator <- Spacing ';' + // Spacing <- WS* + // WS <- ' ' / '\t' + // END <- !. + // + + private boolean matchConnectionString() + throws ConnectionStringSyntaxException { + if (!matchAttribute()) { + throw new ConnectionStringSyntaxException(String.format( + "Could not parse connection string '%1$s'", + connectionString)); + } + + boolean moreAttributes = true; + int bookmark; + + while (moreAttributes) { + bookmark = currentIndex; + boolean separators = false; + while (matchSeparator()) { + separators = true; + } + moreAttributes = separators && matchAttribute(); + if (!moreAttributes) { + currentIndex = bookmark; + } + } + + while (matchSeparator()) { } + + if (!matchEND()) { + throw new ConnectionStringSyntaxException(String.format( + "Expected end of connection string '%1$s', did not get it", + connectionString)); + } + + return true; + } + + private boolean matchAttribute() throws ConnectionStringSyntaxException { + matchSpacing(); + if (matchKeyValuePair()) { + return true; + } + int bookmark = currentIndex; + boolean matchedSeparator = matchSeparator(); + currentIndex = bookmark; + return matchedSeparator; + } + + private boolean matchKeyValuePair() throws ConnectionStringSyntaxException { + if (!charsLeft()) { + return false; + } + if (!matchKey()) { + throw new ConnectionStringSyntaxException( + String.format( + "Expected key in connection string '%1$s' at position %2$d but did not find one", + connectionString, currentIndex)); + } + if (!matchEquals()) { + throw new ConnectionStringSyntaxException( + String.format( + "Expected '=' character in connection string '%1$s' after key near position %2$d", + connectionString, currentIndex)); + } + if (!matchValue()) { + throw new ConnectionStringSyntaxException( + String.format( + "Expected value in connection string '%1$s' for key '%3$s' at position %2$d but did not find one", + connectionString, currentIndex, currentKey)); + } + + saveValue(currentKey, currentValue); + return true; + } + + private boolean matchKey() throws ConnectionStringSyntaxException { + return matchQuotedKey() || matchRawKey(); + } + + private boolean matchQuotedKey() throws ConnectionStringSyntaxException { + if (!charsLeft()) { + return false; + } + String value = ""; + char quote = currentChar(); + int bookmark = currentIndex; + + if (quote == '"' || quote == '\'') { + consumeChar(); + while (charsLeft() && currentChar() != quote) { + value += currentChar(); + consumeChar(); + } + if (!charsLeft()) { + throw new ConnectionStringSyntaxException( + String.format( + "Unterminated quoted value in string '%1$s', starting at character %2$d", + connectionString, bookmark)); + } + consumeChar(); + currentKey = value; + return true; + } else { + return false; + } + } + + private boolean matchRawKey() throws ConnectionStringSyntaxException { + if (!charsLeft()) { + return false; + } + + String value = ""; + int bookmark = currentIndex; + + while (charsLeft() && !matchEquals()) { + value += currentChar(); + consumeChar(); + bookmark = currentIndex; + } + + if (!charsLeft()) { + throw new ConnectionStringSyntaxException( + String.format( + "Expected '=' in connection string '%1$s', key started at index %2$d", + connectionString, bookmark)); + } + + currentIndex = bookmark; + currentKey = value; + return true; + } + + private boolean matchEquals() { + int bookmark = currentIndex; + matchSpacing(); + if (charsLeft() && currentChar() == '=') { + consumeChar(); + return true; + } + currentIndex = bookmark; + return false; + } + + private boolean matchValue() throws ConnectionStringSyntaxException { + return matchQuotedValue() || matchRawValue(); + } + + private boolean matchQuotedValue() throws ConnectionStringSyntaxException { + String value = ""; + char quote = currentChar(); + int bookmark = currentIndex; + + if (quote == '"' || quote == '\'') { + consumeChar(); + while (charsLeft() && currentChar() != quote) { + value += currentChar(); + consumeChar(); + } + if (!charsLeft()) { + throw new ConnectionStringSyntaxException( + String.format( + "Unterminated quoted value in string '%1$s', starting at character %2$d", + connectionString, bookmark)); + } + consumeChar(); + currentValue = value; + return true; + } else { + return false; + } + } + + private boolean matchRawValue() { + String value = ""; + int bookmark = currentIndex; + + while (charsLeft() && !matchSeparator()) { + value += currentChar(); + consumeChar(); + bookmark = currentIndex; + } + currentIndex = bookmark; + currentValue = value; + return true; + } + + private boolean matchSeparator() { + int bookmark = currentIndex; + matchSpacing(); + if (charsLeft() && currentChar() == ';') { + consumeChar(); + return true; + } + currentIndex = bookmark; + return false; + } + + private boolean matchSpacing() { + while (matchWS()) { } + + return true; + } + + private boolean matchWS() { + if (charsLeft() && (currentChar() == ' ' || currentChar() == '\t')) { + consumeChar(); + return true; + } + return false; + } + + private boolean matchEND() { + return !(currentIndex < connectionString.length()); + } + + /** + * Store the value for the given key. + * + * Default implementation looks for a property setter with the matching name + * or the @ConnectionStringField annotation on the setter method to set the + * field. You can override this method for other behavior. + * + * @param key + * Key to store value under. If keys repeat, older values are + * overwritten. + * @param value + * value to associate with the key. + * + * @throws ConnectionStringSyntaxException + */ + protected void saveValue(String key, String value) + throws ConnectionStringSyntaxException { + Method setter; + try { + setter = findSetter(key); + setter.invoke(this, value); + } catch (NoSuchMethodException e) { + throw new ConnectionStringSyntaxException(String.format( + "The key '%1$s' is not valid for this connection string", + key), e); + } catch (InvocationTargetException e) { + throw new ConnectionStringSyntaxException(String.format( + "Could not invoke setter for key '%1$s'", key), e); + } catch (IllegalAccessException e) { + throw new ConnectionStringSyntaxException(String.format( + "Setter for key '%1$s' is not accessible in class %2$s", + key, getClass().getName()), e); + } + } + + private Method findSetter(String key) throws NoSuchMethodException { + Class thisClass = getClass(); + for (Method m : thisClass.getDeclaredMethods()) { + if (methodMatches(m, key)) { + return m; + } + } + throw new NoSuchMethodException(); + } + + private boolean methodMatches(Method method, String key) { + return matchesViaAnnotation(method, key) || matchesByName(method, key); + } + + private boolean matchesViaAnnotation(Method method, String key) { + ConnectionStringField annotation = method + .getAnnotation(ConnectionStringField.class); + return annotation != null + && annotation.name().toLowerCase().equals(key.toLowerCase()); + } + + private boolean matchesByName(Method method, String key) { + return method.getName().toLowerCase().equals("set" + key.toLowerCase()); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/SSLContextFactory.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/SSLContextFactory.java new file mode 100644 index 0000000000000..a4dcbe9fe13bf --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/SSLContextFactory.java @@ -0,0 +1,194 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.Security; +import java.security.cert.X509Certificate; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +/** + * A factory for creating SSLContext instance. + */ +public final class SSLContextFactory { + private SSLContextFactory() { + } + + /** + * Creates a SSLContext with specified keystore credential. + * + * @param keyStoreCredential + * the credential of the keystore. + * @return a SSLContext instance. + * @throws GeneralSecurityException + * the general security exception + * @throws IOException + * when an I/O exception has occurred. + */ + public static SSLContext create(KeyStoreCredential keyStoreCredential) + throws GeneralSecurityException, IOException { + if (keyStoreCredential == null) { + throw new IllegalArgumentException( + "KeyStoreCredential cannot be null."); + } + return create(keyStoreCredential.getKeyStorePath(), + keyStoreCredential.getKeystorePassword(), + keyStoreCredential.getKeyStoreType()); + } + + /** + * Creates a SSLContext object with specified keystore stream and password. + * + * @param keyStorePath + * the path of the keystore. + * @param keyStorePassword + * the password of the keystore. + * @param keyStoreType + * the type of the keystore. + * @return An SSLContext instance. + * @throws GeneralSecurityException + * the general security exception + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws ClassNotFoundException + */ + public static SSLContext create(String keyStorePath, + String keyStorePassword, KeyStoreType keyStoreType) + throws GeneralSecurityException, IOException { + + if ((keyStorePath == null) || (keyStorePath.isEmpty())) { + throw new IllegalArgumentException( + "The keystore path cannot be null or empty."); + } + + if (keyStoreType == null) { + throw new IllegalArgumentException( + "The type of the keystore cannot be null"); + } + + InputStream keyStoreInputStream = new FileInputStream(new File( + keyStorePath)); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + + // Using bouncy castle only in case of java6 and if keystore is having + // empty password + if (Float.valueOf(System.getProperty("java.specification.version")) < 1.7 + && (keyStorePassword != null && keyStorePassword.trim() + .length() == 0)) { + try { + String defaultAlgorithm = KeyManagerFactory + .getDefaultAlgorithm(); + KeyManagerFactory keyManagerFactory = KeyManagerFactory + .getInstance(defaultAlgorithm); + + // use bouncy castle provider + Class providerClass = Class + .forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); + Security.addProvider((Provider) providerClass.newInstance()); + + Field field = providerClass.getField("PROVIDER_NAME"); + KeyStore store = KeyStore.getInstance("PKCS12", field.get(null) + .toString()); + store.load(keyStoreInputStream, keyStorePassword.toCharArray()); + + keyManagerFactory.init(store, keyStorePassword.toCharArray()); + sslContext.init(keyManagerFactory.getKeyManagers(), null, null); + + } catch (Exception e) { + // Using catch all exception class to avoid repeated code in + // different catch blocks + throw new RuntimeException( + "Exception occured while initiatlizing SSL context" + + "Make sure java versions less than 1.7 has bouncycastle jar in classpath", + e); + } + } else { + KeyManager[] keyManagers = getKeyManagers(keyStoreInputStream, + keyStorePassword, keyStoreType); + + sslContext.init(keyManagers, + new TrustManager[] { + new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + // System.out.println("getAcceptedIssuers ============="); + return null; + } + + @Override + public void checkClientTrusted(X509Certificate[] certs, + String authType) { + // System.out.println("checkClientTrusted ============="); + } + + @Override + public void checkServerTrusted(X509Certificate[] certs, + String authType) { + // System.out.println("checkServerTrusted ============="); + } + } + }, new SecureRandom()); + + } + + keyStoreInputStream.close(); + return sslContext; + } + + /** + * Gets the key managers. + * + * @param keyStoreStream + * the key store stream + * @param keyStorePassword + * the key stream password + * @param type + * the type + * @return the key managers + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws GeneralSecurityException + * the general security exception + */ + private static KeyManager[] getKeyManagers(InputStream keyStoreInputStream, + String keyStorePassword, KeyStoreType keyStoreType) + throws IOException, GeneralSecurityException { + + KeyStore keyStore = KeyStore.getInstance(keyStoreType.name()); + keyStore.load(keyStoreInputStream, keyStorePassword.toCharArray()); + String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory keyManagerFactory = KeyManagerFactory + .getInstance(defaultAlgorithm); + keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); + + return keyManagerFactory.getKeyManagers(); + } + +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/StreamUtils.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/StreamUtils.java new file mode 100644 index 0000000000000..f1ddf55fbf928 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/StreamUtils.java @@ -0,0 +1,41 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.utils; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +public final class StreamUtils { + private StreamUtils() { + } + + public static String toString(final InputStream inputStream) + throws IOException { + final BufferedInputStream bufferedStream = new BufferedInputStream( + inputStream); + final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + + int result = bufferedStream.read(); + while (result >= 0) { + final byte data = (byte) result; + byteStream.write(data); + result = bufferedStream.read(); + } + return byteStream.toString(); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/Utility.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/Utility.java new file mode 100644 index 0000000000000..25258f9977dd6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/Utility.java @@ -0,0 +1,778 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.lang.reflect.Constructor; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Locale; +import java.util.TimeZone; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +/** + * RESERVED FOR INTERNAL USE. A class which provides utility methods. + */ +public final class Utility { + /** + * Stores a reference to the GMT time zone. + */ + public static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT"); + + /** + * Stores a reference to the UTC time zone. + */ + public static final TimeZone UTC_ZONE = TimeZone.getTimeZone("UTC"); + + /** + * Stores a reference to the US locale. + */ + public static final Locale LOCALE_US = Locale.US; + + /** + * Stores a reference to the RFC1123 date/time pattern. + */ + private static final String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z"; + + /** + * Stores a reference to the ISO8061 date/time pattern. + */ + public static final String ISO8061_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; + + /** + * Stores a reference to the ISO8061 date/time pattern. + */ + public static final String ISO8061_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + + /** + * Stores a reference to the ISO8061_LONG date/time pattern. + */ + public static final String ISO8061_LONG_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"; + + /** + * Asserts that a value is not null. + * + * @param param + * A String that represents the name of the + * parameter, which becomes the exception message text if the + * value parameter is null. + * @param value + * An Object object that represents the value of the + * specified parameter. This is the value being asserted as not + * null. + */ + public static void assertNotNull(final String param, final Object value) { + if (value == null) { + throw new IllegalArgumentException(param); + } + } + + /** + * Asserts that the specified string is not null or empty. + * + * @param param + * A String that represents the name of the + * parameter, which becomes the exception message text if the + * value parameter is null or an empty + * string. + * @param value + * A String that represents the value of the + * specified parameter. This is the value being asserted as not + * null and not an empty string. + */ + public static void assertNotNullOrEmpty(final String param, + final String value) { + assertNotNull(param, value); + + if (Utility.isNullOrEmpty(value)) { + throw new IllegalArgumentException( + "The argument must not be an empty string or null:" + .concat(param)); + } + } + + /** + * Asserts that the specified integer is in the valid range. + * + * @param param + * A String that represents the name of the + * parameter, which becomes the exception message text if the + * value parameter is out of bounds. + * @param value + * The value of the specified parameter. + * @param min + * The minimum value for the specified parameter. + * @param max + * The maximum value for the specified parameter. + */ + public static void assertInBounds(final String param, final int value, + final int min, final int max) { + if (value < min || value > max) { + throw new IllegalArgumentException( + String.format( + "The value of the parameter %s should be between %s and %s.", + param, min, max)); + } + } + + /** + * Creates an XML stream reader from the specified input stream. + * + * @param streamRef + * An InputStream object that represents the input + * stream to use as the source. + * + * @return A java.xml.stream.XMLStreamReader object that + * represents the XML stream reader created from the specified input + * stream. + * + * @throws XMLStreamException + * If the XML stream reader could not be created. + */ + public static XMLStreamReader createXMLStreamReaderFromStream( + final InputStream streamRef) throws XMLStreamException { + // TODO optimization keep this static + XMLInputFactory xmlif = null; + + xmlif = XMLInputFactory.newInstance(); + xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, + Boolean.TRUE); + xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, + Boolean.FALSE); + // set the IS_COALESCING property to true , if application desires to + // get whole text data as one event. + xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); + + return xmlif.createXMLStreamReader(streamRef); + } + + /** + * Creates an XML stream reader from the specified input stream. + * + * @param reader + * An InputStreamReader object that represents the + * input reader to use as the source. + * + * @return A java.xml.stream.XMLStreamReader object that + * represents the XML stream reader created from the specified input + * stream. + * + * @throws XMLStreamException + * If the XML stream reader could not be created. + */ + public static XMLStreamReader createXMLStreamReaderFromReader( + final Reader reader) throws XMLStreamException { + // TODO optimization keep this static + XMLInputFactory xmlif = null; + + xmlif = XMLInputFactory.newInstance(); + xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, + Boolean.TRUE); + xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, + Boolean.FALSE); + // set the IS_COALESCING property to true , if application desires to + // get whole text data as one event. + xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); + + return xmlif.createXMLStreamReader(reader); + } + + /** + * Returns a value that indicates whether a specified URI is a path-style + * URI. + * + * @param baseURI + * A java.net.URI value that represents the URI + * being checked. + * @param knownAccountName + * A String that represents the known account name + * to examine with baseURI, or null to + * examine baseURI on its own for being a path-style + * URI. + * + * @return true if the specified URI is path-style; otherwise, + * false. + */ + public static boolean determinePathStyleFromUri(final URI baseURI, + final String knownAccountName) { + String path = baseURI.getPath(); + + if (knownAccountName == null) { + if (Utility.isNullOrEmpty(path) || path.equals("/")) { + return false; + } + + return true; + } + + if (!Utility.isNullOrEmpty(path) && path.startsWith("/")) { + path = path.substring(1); + } + + if (Utility.isNullOrEmpty(path) + || baseURI.getHost().startsWith(knownAccountName)) { + return false; + } else if (!Utility.isNullOrEmpty(path) + && path.startsWith(knownAccountName)) { + return true; + } + + return false; + } + + /** + * Returns a byte array that represents the data of a long + * value. + * + * @param value + * The value from which the byte array will be returned. + * + * @return A byte array that represents the data of the specified + * long value. + */ + public static byte[] getBytesFromLong(final long value) { + final byte[] tempArray = new byte[8]; + + for (int m = 0; m < 8; m++) { + tempArray[7 - m] = (byte) ((value >> (8 * m)) & 0xFF); + } + + return tempArray; + } + + /** + * Returns the current GMT date/time using the RFC1123 pattern. + * + * @return A String that represents the current GMT date/time + * using the RFC1123 pattern. + */ + public static String getGMTTime() { + final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, + LOCALE_US); + rfc1123Format.setTimeZone(GMT_ZONE); + return rfc1123Format.format(new Date()); + } + + public static String getTimeByZoneAndFormat(Date date, TimeZone zone, + String format) { + final DateFormat formatter = new SimpleDateFormat(format, LOCALE_US); + formatter.setTimeZone(zone); + return formatter.format(date); + } + + /** + * Returns the GTM date/time for the specified value using the RFC1123 + * pattern. + * + * @param inDate + * A Date object that represents the date to convert + * to GMT date/time in the RFC1123 pattern. + * + * @return A String that represents the GMT date/time for the + * specified value using the RFC1123 pattern. + */ + public static String getGMTTime(final Date inDate) { + final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, + LOCALE_US); + rfc1123Format.setTimeZone(GMT_ZONE); + return rfc1123Format.format(inDate); + } + + /** + * Returns the standard header value from the specified connection request, + * or an empty string if no header value has been specified for the request. + * + * @param conn + * An HttpURLConnection object that represents the + * request. + * @param headerName + * A String that represents the name of the header + * being requested. + * + * @return A String that represents the header value, or + * null if there is no corresponding header value for + * headerName. + */ + public static String getStandardHeaderValue(final HttpURLConnection conn, + final String headerName) { + final String headerValue = conn.getRequestProperty(headerName); + + // Coalesce null value + return headerValue == null ? Constants.EMPTY_STRING : headerValue; + } + + /** + * Returns the current UTC date/time using the RFC1123 pattern. + * + * @return A String that represents the current UTC date/time + * using the RFC1123 pattern. + */ + protected static String getUTCTime() { + final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, + LOCALE_US); + rfc1123Format.setTimeZone(UTC_ZONE); + return rfc1123Format.format(new Date()); + } + + /** + * Returns the UTC date/time for the specified value using the RFC1123 + * pattern. + * + * @param inDate + * A Date object that represents the date to convert + * to UTC date/time in the RFC1123 pattern. + * + * @return A String that represents the UTC date/time for the + * specified value using the RFC1123 pattern. + */ + protected static String getUTCTime(final Date inDate) { + final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, + LOCALE_US); + rfc1123Format.setTimeZone(UTC_ZONE); + return rfc1123Format.format(inDate); + } + + /** + * Returns the UTC date/time for the specified value using the ISO8061 + * pattern. + * + * @param value + * A Date object that represents the date to convert + * to UTC date/time in the ISO8061 pattern. If this value is + * null, this method returns an empty string. + * + * @return A String that represents the UTC date/time for the + * specified value using the ISO8061 pattern, or an empty string if + * value is null. + */ + public static String getUTCTimeOrEmpty(final Date value) { + if (value == null) { + return Constants.EMPTY_STRING; + } + + final DateFormat iso8061Format = new SimpleDateFormat(ISO8061_PATTERN, + LOCALE_US); + iso8061Format.setTimeZone(UTC_ZONE); + + return iso8061Format.format(value); + } + + /** + * Creates an instance of the IOException class using the + * specified exception. + * + * @param ex + * An Exception object that represents the exception + * used to create the IO exception. + * + * @return A java.io.IOException object that represents the + * created IO exception. + */ + public static IOException initIOException(final Exception ex) { + final IOException retEx = new IOException(); + retEx.initCause(ex); + return retEx; + } + + /** + * Returns a value that indicates whether the specified string is + * null or empty. + * + * @param value + * A String being examined for null or + * empty. + * + * @return true if the specified value is null or + * empty; otherwise, false + */ + public static boolean isNullOrEmpty(final String value) { + return value == null || value.length() == 0; + } + + /** + * Parses a connection string and returns its values as a hash map of + * key/value pairs. + * + * @param parseString + * A String that represents the connection string to + * parse. + * + * @return A java.util.HashMap object that represents the hash + * map of the key / value pairs parsed from the connection string. + */ + public static HashMap parseAccountString( + final String parseString) { + + // 1. split name value pairs by splitting on the ';' character + final String[] valuePairs = parseString.split(";"); + final HashMap retVals = new HashMap(); + + // 2. for each field value pair parse into appropriate map entries + for (int m = 0; m < valuePairs.length; m++) { + final int equalDex = valuePairs[m].indexOf("="); + if (equalDex < 1) { + throw new IllegalArgumentException("Invalid Connection String"); + } + + final String key = valuePairs[m].substring(0, equalDex); + final String value = valuePairs[m].substring(equalDex + 1); + + // 2.1 add to map + retVals.put(key, value); + } + + return retVals; + } + + /** + * Returns a GMT date in the specified format + * + * @param value + * the string to parse + * @return the GMT date, as a Date + * @throws ParseException + * If the specified string is invalid + */ + public static Date parseDateFromString(final String value, + final String pattern, final TimeZone timeZone) + throws ParseException { + final DateFormat rfc1123Format = new SimpleDateFormat(pattern, + Utility.LOCALE_US); + rfc1123Format.setTimeZone(timeZone); + return rfc1123Format.parse(value); + } + + /** + * Returns a date in the ISO8061 long pattern for the specified string. + * + * @param value + * A String that represents the string to parse. + * + * @return A Date object that represents the date in the + * ISO8061 long pattern. + * + * @throws ParseException + * If the specified string is invalid. + */ + public static Date parseISO8061LongDateFromString(final String value) + throws ParseException { + return parseDateFromString(value, ISO8061_LONG_PATTERN, + Utility.UTC_ZONE); + } + + /** + * Returns a GMT date in the RFC1123 pattern for the specified string. + * + * @param value + * A String that represents the string to parse. + * + * @return A Date object that represents the GMT date in the + * RFC1123 pattern. + * + * @throws ParseException + * If the specified string is invalid. + */ + public static Date parseRFC1123DateFromStringInGMT(final String value) + throws ParseException { + return parseDateFromString(value, RFC1123_PATTERN, Utility.GMT_ZONE); + } + + /** + * Reads character data for the specified XML element from an XML stream + * reader. This method will read start events, characters, and end events + * from a stream. + * + * @param xmlr + * An XMLStreamReader object that represents the + * source XML stream reader. + * + * @param elementName + * A String that represents XML element name. + * + * @return A String that represents the character data for the + * specified element. + * + * @throws XMLStreamException + * If an XML stream failure occurs. + */ + public static String readElementFromXMLReader(final XMLStreamReader xmlr, + final String elementName) throws XMLStreamException { + return readElementFromXMLReader(xmlr, elementName, true); + } + + /** + * Reads character data for the specified XML element from an XML stream + * reader. This method will read start events, characters, and end events + * from a stream. + * + * @param xmlr + * An XMLStreamReader object that represents the + * source XML stream reader. + * + * @param elementName + * A String that represents XML element name. + * @param returnNullOnEmpty + * If true, returns null when a empty string is read, otherwise + * EmptyString ("") is returned. + * + * @return A String that represents the character data for the + * specified element. + * + * @throws XMLStreamException + * If an XML stream failure occurs. + */ + public static String readElementFromXMLReader(final XMLStreamReader xmlr, + final String elementName, boolean returnNullOnEmpty) + throws XMLStreamException { + xmlr.require(XMLStreamConstants.START_ELEMENT, null, elementName); + int eventType = xmlr.next(); + final StringBuilder retVal = new StringBuilder(); + + if (eventType == XMLStreamConstants.CHARACTERS) { + // This do while is in case the XMLStreamReader does not have + // the IS_COALESCING property set + // to true which may result in text being read in multiple events + // If we ensure all xmlreaders have this property we can optimize + // the StringBuilder and while loop + // away + do { + retVal.append(xmlr.getText()); + eventType = xmlr.next(); + + } while (eventType == XMLStreamConstants.CHARACTERS); + } + + xmlr.require(XMLStreamConstants.END_ELEMENT, null, elementName); + if (retVal.length() == 0) { + return returnNullOnEmpty ? null : Constants.EMPTY_STRING; + } else { + return retVal.toString(); + } + } + + /** + * Determines the relative difference between the two specified URIs. + * + * @param baseURI + * A java.net.URI object that represents the base + * URI for which toUri will be made relative. + * @param toUri + * A java.net.URI object that represents the URI to + * make relative to baseURI. + * + * @return A String that either represents the relative URI of + * toUri to baseURI, or the URI of + * toUri itself, depending on whether the hostname and + * scheme are identical for toUri and + * baseURI. If the hostname and scheme of + * baseURI and toUri are identical, this + * method returns a relative URI such that if appended to + * baseURI, it will yield toUri. If the + * hostname or scheme of baseURI and toUri + * are not identical, this method returns the full URI specified by + * toUri. + * + * @throws URISyntaxException + * If baseURI or toUri is invalid. + */ + public static String safeRelativize(final URI baseURI, final URI toUri) + throws URISyntaxException { + // For compatibility followed + // http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx + + // if host and scheme are not identical return from uri + if (!baseURI.getHost().equals(toUri.getHost()) + || !baseURI.getScheme().equals(toUri.getScheme())) { + return toUri.toString(); + } + + final String basePath = baseURI.getPath(); + String toPath = toUri.getPath(); + + int truncatePtr = 1; + + // Seek to first Difference + // int maxLength = Math.min(basePath.length(), toPath.length()); + int m = 0; + int ellipsesCount = 0; + for (; m < basePath.length(); m++) { + if (m >= toPath.length()) { + if (basePath.charAt(m) == '/') { + ellipsesCount++; + } + } else { + if (basePath.charAt(m) != toPath.charAt(m)) { + break; + } else if (basePath.charAt(m) == '/') { + truncatePtr = m + 1; + } + } + } + + if (m == toPath.length()) { + // No path difference, return query + fragment + return new URI(null, null, null, toUri.getQuery(), + toUri.getFragment()).toString(); + } else { + toPath = toPath.substring(truncatePtr); + final StringBuilder sb = new StringBuilder(); + while (ellipsesCount > 0) { + sb.append("../"); + ellipsesCount--; + } + + if (!Utility.isNullOrEmpty(toPath)) { + sb.append(toPath); + } + + if (!Utility.isNullOrEmpty(toUri.getQuery())) { + sb.append("?"); + sb.append(toUri.getQuery()); + } + if (!Utility.isNullOrEmpty(toUri.getFragment())) { + sb.append("#"); + sb.append(toUri.getRawFragment()); + } + + return sb.toString(); + } + } + + /** + * Trims the specified character from the end of a string. + * + * @param value + * A String that represents the string to trim. + * @param trimChar + * The character to trim from the end of the string. + * + * @return The string with the specified character trimmed from the end. + */ + protected static String trimEnd(final String value, final char trimChar) { + int stopDex = value.length() - 1; + while (stopDex > 0 && value.charAt(stopDex) == trimChar) { + stopDex--; + } + + return stopDex == value.length() - 1 ? value : value.substring(stopDex); + } + + /** + * Trims whitespace from the beginning of a string. + * + * @param value + * A String that represents the string to trim. + * + * @return The string with whitespace trimmed from the beginning. + */ + public static String trimStart(final String value) { + int spaceDex = 0; + while (spaceDex < value.length() && value.charAt(spaceDex) == ' ') { + spaceDex++; + } + + return value.substring(spaceDex); + } + + /** + * Private Default Ctor. + */ + private Utility() { + // No op + } + + public static void checkNullaryCtor(Class clazzType) { + Constructor ctor = null; + try { + ctor = clazzType.getDeclaredConstructor((Class[]) null); + } catch (Exception e) { + throw new IllegalArgumentException( + "Class type must have contain a nullary constructor."); + } + + if (ctor == null) { + throw new IllegalArgumentException( + "Class type must have contain a nullary constructor."); + } + } + + public static Date parseDate(String dateString) { + try { + if (dateString.length() == 28) { + // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"-> + // [2012-01-04T23:21:59.1234567Z] length = 28 + return Utility.parseDateFromString(dateString, + Utility.ISO8061_LONG_PATTERN, Utility.UTC_ZONE); + } else if (dateString.length() == 20) { + // "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length = + // 20 + return Utility.parseDateFromString(dateString, + Utility.ISO8061_PATTERN, Utility.UTC_ZONE); + } else if (dateString.length() == 17) { + // "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17 + return Utility.parseDateFromString(dateString, + Utility.ISO8061_PATTERN_NO_SECONDS, Utility.UTC_ZONE); + } else if (dateString.length() == 27) { + // "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"-> + // [2012-01-04T23:21:59.123456Z] length = 27 + return Utility.parseDateFromString(dateString, + "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", Utility.UTC_ZONE); + } else if (dateString.length() == 26) { + // "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"-> + // [2012-01-04T23:21:59.12345Z] length = 26 + return Utility.parseDateFromString(dateString, + "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'", Utility.UTC_ZONE); + } else if (dateString.length() == 25) { + // "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z] + // length = 25 + return Utility.parseDateFromString(dateString, + "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'", Utility.UTC_ZONE); + } else if (dateString.length() == 24) { + // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z] + // length = 24 + return Utility.parseDateFromString(dateString, + "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Utility.UTC_ZONE); + } else if (dateString.length() == 23) { + // "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z] + // length = 23 + return Utility.parseDateFromString(dateString, + "yyyy-MM-dd'T'HH:mm:ss.SS'Z'", Utility.UTC_ZONE); + } else if (dateString.length() == 22) { + // "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z] + // length = 22 + return Utility.parseDateFromString(dateString, + "yyyy-MM-dd'T'HH:mm:ss.S'Z'", Utility.UTC_ZONE); + } else { + throw new IllegalArgumentException(String.format( + "Invalid Date String: %s", dateString)); + } + } catch (final ParseException e) { + throw new IllegalArgumentException(String.format( + "Invalid Date String: %s", dateString), e); + } + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/XmlUtility.java b/core/src/main/java/com/microsoft/windowsazure/core/utils/XmlUtility.java new file mode 100644 index 0000000000000..94e7615985cf1 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/XmlUtility.java @@ -0,0 +1,92 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core.utils; + +import java.util.ArrayList; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public abstract class XmlUtility { + public static Element getElementByTagNameNS(Node element, String namespace, + String name) { + NodeList elements = element.getChildNodes(); + CharSequence colon = ":"; + if (elements != null) { + for (int i = 0; i < elements.getLength(); i++) { + if (elements.item(i).getNodeType() == Node.ELEMENT_NODE + && (elements.item(i).getAttributes().getNamedItemNS("http://www.w3.org/2001/XMLSchema-instance", "nil") == null + || !"true".equals(elements.item(i).getAttributes().getNamedItemNS("http://www.w3.org/2001/XMLSchema-instance", "nil")))) { + Element currentElement = (Element) elements.item(i); + String nodeName = currentElement.getNodeName(); + String nodeNameOnly = nodeName; + if (nodeName.contains(colon)) { + String[] nodeNameSplit = nodeName.split(":"); + nodeNameOnly = nodeNameSplit[1]; + } + + if ((currentElement.getNamespaceURI() == null + || currentElement.getNamespaceURI().equals(namespace)) + && nodeNameOnly.equals(name)) { + return currentElement; + } + } + } + } + + return null; + } + + public static ArrayList getElementsByTagNameNS(Node element, + String namespace, String name) { + ArrayList childElements = new ArrayList(); + + NodeList elements = element.getChildNodes(); + if (elements != null) { + for (int i = 0; i < elements.getLength(); i++) { + if (elements.item(i).getNodeType() == Node.ELEMENT_NODE) { + Element currentElement = (Element) elements.item(i); + if ((currentElement.getNamespaceURI() == null + || currentElement.getNamespaceURI().equals(namespace)) + && currentElement.getNodeName().equals(name)) { + + childElements.add(currentElement); + } + } + } + } + + return childElements; + } + + public static Element getElementByTagName(Node element, String name) { + NodeList elements = element.getChildNodes(); + if (elements != null) { + for (int i = 0; i < elements.getLength(); i++) { + if (elements.item(i).getNodeType() == Node.ELEMENT_NODE) { + Element currentElement = (Element) elements.item(i); + if (currentElement.getNodeName().equals(name)) { + + return currentElement; + } + } + } + } + + return null; + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/core/utils/package.html b/core/src/main/java/com/microsoft/windowsazure/core/utils/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/core/utils/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/credentials/CertificateCloudCredentials.java b/core/src/main/java/com/microsoft/windowsazure/credentials/CertificateCloudCredentials.java new file mode 100644 index 0000000000000..3280550dc90e8 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/credentials/CertificateCloudCredentials.java @@ -0,0 +1,142 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.credentials; + +import com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigurationProperties; +import com.microsoft.windowsazure.core.utils.KeyStoreCredential; +import com.microsoft.windowsazure.core.utils.SSLContextFactory; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import java.io.IOException; +import java.net.URI; +import java.security.GeneralSecurityException; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.net.ssl.SSLContext; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; + +/** + * The Class CertificateCloudCredentials. + */ +public class CertificateCloudCredentials extends SubscriptionCloudCredentials { + + /** The subscription id. */ + private String subscriptionId; + + /** The key store credential. */ + private KeyStoreCredential keyStoreCredential; + + /** The uri. */ + private URI uri; + + /** + * Instantiates a new certificate cloud credentials. + */ + public CertificateCloudCredentials() { + } + + /** + * Instantiates a new certificate cloud credentials. + * + * @param uri the uri + * @param subscriptionId the subscription id + * @param keyStoreCredential the key store credential + */ + @Inject + public CertificateCloudCredentials(@Named(ManagementConfiguration.URI) URI uri, @Named(ManagementConfiguration.SUBSCRIPTION_ID) String subscriptionId, + KeyStoreCredential keyStoreCredential) { + this.uri = uri; + this.subscriptionId = subscriptionId; + this.keyStoreCredential = keyStoreCredential; + } + + /* (non-Javadoc) + * @see com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials#getSubscriptionId() + */ + public String getSubscriptionId() { + return subscriptionId; + } + + /** + * Sets the subscription id. + * + * @param subscriptionId the new subscription id + */ + public void setSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + } + + /** + * Gets the key store credential. + * + * @return the key store credential + */ + public KeyStoreCredential getKeyStoreCredential() { + return keyStoreCredential; + } + + /** + * Sets the key store credential. + * + * @param keyStoreCredential the new key store credential + */ + public void setKeyStoreCredential(KeyStoreCredential keyStoreCredential) { + this.keyStoreCredential = keyStoreCredential; + } + + /** + * Gets the URI. + * + * @return the URI + */ + public URI getUri() { + return uri; + } + + /** + * Sets the URI. + * + * @param uri the new URI + */ + public void setUri(URI uri) { + this.uri = uri; + } + + /* (non-Javadoc) + * @see com.microsoft.windowsazure.credentials.CloudCredentials#applyConfig(java.lang.String, java.util.Map) + */ + @Override + public void applyConfig(String profile, Map properties) { + SSLContext sslContext; + try { + sslContext = SSLContextFactory.create(this.getKeyStoreCredential()); + properties + .put(profile + + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY, + new SSLConnectionSocketFactory(sslContext)); + } catch (GeneralSecurityException ex) { + Logger.getLogger(CertificateCloudCredentials.class.getName()).log( + Level.SEVERE, null, ex); + } catch (IOException ex) { + Logger.getLogger(CertificateCloudCredentials.class.getName()).log( + Level.SEVERE, null, ex); + } + } + +} diff --git a/core/src/main/java/com/microsoft/windowsazure/credentials/CloudCredentials.java b/core/src/main/java/com/microsoft/windowsazure/credentials/CloudCredentials.java new file mode 100644 index 0000000000000..9b376fe0d9080 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/credentials/CloudCredentials.java @@ -0,0 +1,23 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.credentials; + +import java.util.Map; + +public abstract class CloudCredentials { + public abstract void applyConfig(String profile, + Map properties); +} diff --git a/core/src/main/java/com/microsoft/windowsazure/credentials/Exports.java b/core/src/main/java/com/microsoft/windowsazure/credentials/Exports.java new file mode 100644 index 0000000000000..d3b04dfc8257d --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/credentials/Exports.java @@ -0,0 +1,27 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.credentials; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Registry; + +public class Exports implements Builder.Exports { + + @Override + public void register(Registry registry) { + + registry.add(SubscriptionCloudCredentials.class, CertificateCloudCredentials.class); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/credentials/SubscriptionCloudCredentials.java b/core/src/main/java/com/microsoft/windowsazure/credentials/SubscriptionCloudCredentials.java new file mode 100644 index 0000000000000..3c0d504bbb1d1 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/credentials/SubscriptionCloudCredentials.java @@ -0,0 +1,25 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.credentials; + +public abstract class SubscriptionCloudCredentials extends CloudCredentials { + /* + * When you create a Windows Azure subscription, it is uniquely identified + * by a subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. + */ + public abstract String getSubscriptionId(); +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/credentials/package.html b/core/src/main/java/com/microsoft/windowsazure/credentials/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/credentials/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/exception/ServiceException.java b/core/src/main/java/com/microsoft/windowsazure/exception/ServiceException.java new file mode 100644 index 0000000000000..d184e9966a7dd --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/exception/ServiceException.java @@ -0,0 +1,304 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.exception; + +import com.microsoft.windowsazure.core.utils.BOMInputStream; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.map.ObjectMapper; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +/** + * The Service Exception indicates an error while executing a service operation. + */ +public class ServiceException extends Exception { + + private static final long serialVersionUID = -4942076377009150131L; + + private int httpStatusCode; + private String httpReasonPhrase; + private String serviceName; + + private String errorCode; + private String errorMessage; + private Map errorValues; + private String rawResponseBody; + + public ServiceException() { + super(); + + init(); + } + + public ServiceException(final String message) { + super(message); + init(); + } + + public ServiceException(final String message, final Throwable cause) { + super(message, cause); + init(); + } + + public ServiceException(final Throwable cause) { + super(cause); + init(); + } + + private void init() { + errorValues = new HashMap(); + } + + @Override + public String getMessage() { + final StringBuffer buffer = new StringBuffer(50); + buffer.append(super.getMessage()); + + if (this.rawResponseBody != null) { + buffer.append("\nResponse Body: "); + buffer.append(this.rawResponseBody); + } + + return buffer.toString(); + } + + public int getHttpStatusCode() { + return httpStatusCode; + } + + public void setHttpStatusCode(final int httpStatusCode) { + this.httpStatusCode = httpStatusCode; + } + + public String getHttpReasonPhrase() { + return httpReasonPhrase; + } + + public void setHttpReasonPhrase(final String httpReasonPhrase) { + this.httpReasonPhrase = httpReasonPhrase; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(final String errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(final String errorMessage) { + this.errorMessage = errorMessage; + } + + public Map getErrorValues() { + return errorValues; + } + + public void setErrorValues(final Map errorValues) { + this.errorValues = errorValues; + } + + public String getErrorValue(final String name) { + return errorValues.get(name); + } + + public void setErrorValue(final String name, final String value) { + this.errorValues.put(name, value); + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(final String serviceName) { + this.serviceName = serviceName; + } + + public void setRawResponseBody(final String body) { + this.rawResponseBody = body; + } + + public String getRawResponseBody() { + return rawResponseBody; + } + + public static ServiceException create(final HttpRequest httpRequest, + final String requestContent, final HttpResponse httpResponse, + final HttpEntity entity, final String defaultTo) { + ServiceException serviceException; + + if (httpResponse.getEntity().getContentType().getValue() + .equals("application/json") + || httpResponse.getEntity().getContentType().getValue() + .equals("text/json")) { + serviceException = createFromJson(httpRequest, requestContent, + httpResponse, entity); + } else if (httpResponse.getEntity().getContentType().getValue() + .equals("application/xml") + || httpResponse.getEntity().getContentType().getValue() + .equals("text/xml")) { + serviceException = createFromXml(httpRequest, requestContent, + httpResponse, entity); + } else if ("Json".equals(defaultTo)) { + serviceException = createFromJson(httpRequest, requestContent, + httpResponse, entity); + } else { + serviceException = createFromXml(httpRequest, requestContent, + httpResponse, entity); + } + + return serviceException; + } + + public static ServiceException createFromXml(final HttpRequest httpRequest, + final String requestContent, final HttpResponse httpResponse, + final HttpEntity entity) { + String content; + try { + content = EntityUtils.toString(entity); + } catch (IOException e) { + return new ServiceException(e); + } + + ServiceException serviceException; + + try { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory + .newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(new ByteArrayInputStream(content.getBytes()))); + + XPathFactory xPathfactory = XPathFactory.newInstance(); + XPath xpath = xPathfactory.newXPath(); + + String code = xpath.compile("/Error/Code/text()").evaluate( + responseDoc); + String message = xpath.compile("/Error/Message/text()").evaluate( + responseDoc); + + serviceException = new ServiceException(buildExceptionMessage(code, + message, content, httpResponse)); + + serviceException.setErrorCode(code); + serviceException.setErrorMessage(message); + } catch (XPathExpressionException e) { + return new ServiceException(content); + } catch (ParserConfigurationException e) { + return new ServiceException(content); + } catch (SAXException e) { + return new ServiceException(content); + } catch (IOException e) { + return new ServiceException(content); + } + + serviceException.setHttpStatusCode(httpResponse.getStatusLine() + .getStatusCode()); + serviceException.setHttpReasonPhrase(httpResponse.getStatusLine() + .getReasonPhrase()); + + return serviceException; + } + + private static String buildExceptionMessage(String code, String message, + String responseContent, HttpResponse httpResponse) { + return (code != null && message != null) ? code + ": " + message + : (message != null) ? message + : (code != null) ? code + : (responseContent != null) ? responseContent + : (httpResponse != null + && httpResponse.getStatusLine() != null && httpResponse + .getStatusLine() + .getReasonPhrase() != null) ? httpResponse + .getStatusLine() + .getReasonPhrase() + : (httpResponse != null && httpResponse + .getStatusLine() != null) ? Integer + .toString(httpResponse + .getStatusLine() + .getStatusCode()) + : "Invalid operation"; + } + + public static ServiceException createFromJson(HttpRequest httpRequest, + String requestContent, HttpResponse httpResponse, HttpEntity entity) { + String content; + try { + content = EntityUtils.toString(entity); + } catch (IOException e) { + return new ServiceException(e); + } + + ServiceException serviceException; + + try { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode responseDoc = objectMapper.readTree(content); + + String code; + if (responseDoc.get("Code") != null) { + code = responseDoc.get("Code").getTextValue(); + } else if (responseDoc.get("code") != null) { + code = responseDoc.get("code").getTextValue(); + } else { + code = Integer.toString(httpResponse.getStatusLine().getStatusCode()); + } + + String message; + if (responseDoc.get("Message") != null) { + message = responseDoc.get("Message").getTextValue(); + } else if (responseDoc.get("message") != null) { + message = responseDoc.get("message").getTextValue(); + } else { + message = httpResponse.getStatusLine().getReasonPhrase(); + } + + serviceException = new ServiceException(buildExceptionMessage(code, + message, content, httpResponse)); + serviceException.setErrorCode(code); + serviceException.setErrorMessage(message); + } catch (IOException e) { + return new ServiceException(); + } + + serviceException.setHttpStatusCode(httpResponse.getStatusLine() + .getStatusCode()); + serviceException.setHttpReasonPhrase(httpResponse.getStatusLine() + .getReasonPhrase()); + + return serviceException; + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/exception/ServiceExceptionFactory.java b/core/src/main/java/com/microsoft/windowsazure/exception/ServiceExceptionFactory.java new file mode 100644 index 0000000000000..48fc2eba929a5 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/exception/ServiceExceptionFactory.java @@ -0,0 +1,101 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.exception; + +import java.net.SocketTimeoutException; + +import com.microsoft.windowsazure.core.ServiceTimeoutException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.ClientResponse.Status; +import com.sun.jersey.api.client.UniformInterfaceException; + +public abstract class ServiceExceptionFactory { + public static ServiceException process(String serviceName, + ServiceException exception) { + Throwable cause = exception.getCause(); + + for (Throwable scan = cause; scan != null; scan = scan.getCause()) { + Class scanClass = scan.getClass(); + if (ServiceException.class.isAssignableFrom(scanClass)) { + return populate(exception, serviceName, (ServiceException) scan); + } else if (UniformInterfaceException.class + .isAssignableFrom(scanClass)) { + return populate(exception, serviceName, + (UniformInterfaceException) scan); + } else if (SocketTimeoutException.class.isAssignableFrom(scanClass)) { + return populate(exception, serviceName, + (SocketTimeoutException) scan); + } + } + + exception.setServiceName(serviceName); + + return exception; + } + + static ServiceException populate(ServiceException exception, + String serviceName, UniformInterfaceException cause) { + exception.setServiceName(serviceName); + + if (cause != null) { + ClientResponse response = cause.getResponse(); + if (response != null) { + // Set status + Status status = response.getClientResponseStatus(); + if (status == null) { + status = Status.fromStatusCode(response.getStatus()); + } + if (status == null) { + exception.setHttpStatusCode(response.getStatus()); + } else { + exception.setHttpStatusCode(status.getStatusCode()); + exception.setHttpReasonPhrase(status.getReasonPhrase()); + } + + // Set raw response body + if (response.hasEntity()) { + try { + String body = response.getEntity(String.class); + exception.setRawResponseBody(body); + } catch (Exception e) { + // Skip exceptions as getting the response body as a + // string is a best effort thing + } + } + } + } + return exception; + } + + static ServiceException populate(final ServiceException exception, + final String serviceName, final ServiceException cause) { + exception.setServiceName(cause.getServiceName()); + exception.setHttpStatusCode(cause.getHttpStatusCode()); + exception.setHttpReasonPhrase(cause.getHttpReasonPhrase()); + exception.setErrorCode(cause.getErrorCode()); + exception.setErrorMessage(cause.getErrorMessage()); + exception.setRawResponseBody(cause.getRawResponseBody()); + exception.setErrorValues(cause.getErrorValues()); + return exception; + } + + static ServiceException populate(ServiceException exception, + String serviceName, SocketTimeoutException cause) { + ServiceTimeoutException newException = new ServiceTimeoutException( + cause.getMessage(), cause); + newException.setServiceName(serviceName); + return newException; + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/exception/package.html b/core/src/main/java/com/microsoft/windowsazure/exception/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/exception/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/management/configuration/Exports.java b/core/src/main/java/com/microsoft/windowsazure/management/configuration/Exports.java new file mode 100644 index 0000000000000..ae5d936e0d37a --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/management/configuration/Exports.java @@ -0,0 +1,51 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.configuration; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Registry; + +public class Exports implements Builder.Exports { + + @Override + public void register(Registry registry) { + + registry.add(new Builder.Factory() { + @Override + public URI create(String profile, + Class service, Builder builder, + Map properties) { + URI uri = null; + + if (properties.get(ManagementConfiguration.URI) != null) { + try { + if (properties.get(ManagementConfiguration.URI).getClass() == URI.class) { + uri = (URI) properties.get(ManagementConfiguration.URI); + } else if (properties.get(ManagementConfiguration.URI).getClass() == String.class) { + uri = new URI((String) properties.get(ManagementConfiguration.URI)); + } + } catch (URISyntaxException e) { + // Intentionally blank + } + } + return uri; + } + }); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/management/configuration/ManagementConfiguration.java b/core/src/main/java/com/microsoft/windowsazure/management/configuration/ManagementConfiguration.java new file mode 100644 index 0000000000000..ac76ca34fdc00 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/management/configuration/ManagementConfiguration.java @@ -0,0 +1,214 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.configuration; + +import com.microsoft.windowsazure.core.utils.KeyStoreCredential; +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.credentials.CertificateCloudCredentials; +import com.microsoft.windowsazure.Configuration; +import java.io.IOException; +import java.net.URI; + +/** + * Provides functionality to create a service management configuration. + * + */ +public final class ManagementConfiguration { + private ManagementConfiguration() { + } + + /** + * Defines the subscription cloud credentials object of the Windows Azure + * account. + */ + public static final String SUBSCRIPTION_CLOUD_CREDENTIALS = "com.microsoft.windowsazure.Configuration.credentials"; + + /** + * Defines the path of the keystore. + * + */ + public static final String KEYSTORE_PATH = "management.keystore.path"; + + /** + * Defines the password of the keystore. + * + */ + public static final String KEYSTORE_PASSWORD = "management.keystore.password"; + + /** + * Defines the type of the keystore. + */ + public static final String KEYSTORE_TYPE = "management.keystore.type"; + + /** + * Defines the URI of service management. + * + */ + public static final String URI = "management.uri"; + + /** + * Defines the subscription ID of the Windows Azure account. + */ + public static final String SUBSCRIPTION_ID = "management.subscription.id"; + + /** + * Creates a service management configuration using specified URI, and + * subscription ID. + * + * @param subscriptionId + * A String object that represents the subscription + * ID. + * @param keyStoreLocation + * A String object that represents the key store + * location. + * @param keyStorePassword + * A String object that represents the key store + * password. + * @return the configuration A Configuration object that can be + * used when creating an instance of the + * ManagementContract class. + * @throws java.io.IOException + * If the key store location or its contents is invalid. + */ + public static Configuration configure(URI uri, String subscriptionId, + String keyStoreLocation, String keyStorePassword) + throws IOException { + return configure(null, Configuration.getInstance(), uri, subscriptionId, + keyStoreLocation, keyStorePassword); + } + + /** + * Creates a service management configuration using specified URI, and + * subscription ID. + * + * @param subscriptionId + * A String object that represents the subscription + * ID. + * @param keyStoreLocation + * A String object that represents the key store + * location. + * @param keyStorePassword + * A String object that represents the key store + * password. + * @param type + * Type of key store. + * @return the configuration A Configuration object that can be + * used when creating an instance of the + * ManagementContract class. + * @throws java.io.IOException + * If the key store location or its contents is invalid. + */ + public static Configuration configure(URI uri, String subscriptionId, + String keyStoreLocation, String keyStorePassword, KeyStoreType type) + throws IOException { + return configure(null, Configuration.getInstance(), uri, subscriptionId, + keyStoreLocation, keyStorePassword, type); + } + + /** + * Creates a service management configuration with specified parameters. + * + * @param profile + * A String object that represents the profile. + * @param configuration + * A previously instantiated Configuration object. + * @param subscriptionId + * A String object that represents the subscription + * ID. + * @param keyStoreLocation + * the key store location + * @param keyStorePassword + * A String object that represents the password of + * the keystore. + * @return A Configuration object that can be used when + * creating an instance of the ManagementContract + * class. + * @throws java.io.IOException + * If the key store location or its contents is invalid. + */ + public static Configuration configure(String profile, + Configuration configuration, URI uri, String subscriptionId, + String keyStoreLocation, String keyStorePassword) + throws IOException { + + if (profile == null) { + profile = ""; + } else if (profile.length() != 0 && !profile.endsWith(".")) { + profile = profile + "."; + } + + configuration.setProperty(profile + SUBSCRIPTION_ID, subscriptionId); + configuration.setProperty(profile + KEYSTORE_PATH, keyStoreLocation); + configuration + .setProperty(profile + KEYSTORE_PASSWORD, keyStorePassword); + + configuration.setProperty(profile + SUBSCRIPTION_CLOUD_CREDENTIALS, + new CertificateCloudCredentials(uri, subscriptionId, + new KeyStoreCredential(keyStoreLocation, + keyStorePassword))); + + return configuration; + } + + /** + * Creates a service management configuration with specified parameters. + * + * @param profile + * A String object that represents the profile. + * @param configuration + * A previously instantiated Configuration object. + * @param subscriptionId + * A String object that represents the subscription + * ID. + * @param keyStoreLocation + * the key store location + * @param keyStorePassword + * A String object that represents the password of + * the keystore. + * @param keyStoreType + * The type of key store. + * @return A Configuration object that can be used when + * creating an instance of the ManagementContract + * class. + * @throws java.io.IOException + * If the key store location or its contents is invalid. + */ + public static Configuration configure(String profile, + Configuration configuration, URI uri, String subscriptionId, + String keyStoreLocation, String keyStorePassword, KeyStoreType keyStoreType) + throws IOException { + + if (profile == null) { + profile = ""; + } else if (profile.length() != 0 && !profile.endsWith(".")) { + profile = profile + "."; + } + + configuration.setProperty(profile + ManagementConfiguration.URI, uri); + configuration.setProperty(profile + ManagementConfiguration.SUBSCRIPTION_ID, subscriptionId); + configuration.setProperty(profile + ManagementConfiguration.KEYSTORE_PATH, keyStoreLocation); + configuration.setProperty(profile + ManagementConfiguration.KEYSTORE_PASSWORD, keyStorePassword); + configuration.setProperty(profile + ManagementConfiguration.KEYSTORE_TYPE, keyStoreType); + + KeyStoreCredential keyStoreCredential = new KeyStoreCredential( + keyStoreLocation, keyStorePassword, keyStoreType); + CertificateCloudCredentials cloudCredentials = new CertificateCloudCredentials(uri, + subscriptionId, keyStoreCredential); + configuration.setProperty(profile + SUBSCRIPTION_CLOUD_CREDENTIALS, + cloudCredentials); + + return configuration; + } +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/management/configuration/PublishSettingsLoader.java b/core/src/main/java/com/microsoft/windowsazure/management/configuration/PublishSettingsLoader.java new file mode 100644 index 0000000000000..e35a869e6e02c --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/management/configuration/PublishSettingsLoader.java @@ -0,0 +1,238 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.configuration; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.Security; +import java.security.cert.CertificateException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.KeyStoreType; + +/** + * Loading a publish settings file to create a service management configuration. + * Supports both schema version 1.0 (deprecated) and 2.0. To get different + * schema versions, use the 'SchemaVersion' query parameter when downloading the + * file: + *

    + *
  • https://manage.windowsazure.com/publishsettings/Index?client=vs& + * SchemaVersion=1.0
  • + *
  • https://manage.windowsazure.com/publishsettings/Index?client=vs& + * SchemaVersion=2.0
  • + *
+ * + */ +public abstract class PublishSettingsLoader { + + /** + * Create a service management configuration using specified publish settings + * file and subscription ID. + *

+ * Please note: + *

    + *
  • Will use the first PublishProfile present in the file.
  • + *
  • An unprotected keystore file keystore.out will be left + * in the working directory containing the management certificate.
  • + *
+ *

+ * + * @param publishSettingsFileName + * The name of the publish settings file with a valid certificate obtained from + * Microsoft Azure portal. + * @param subscriptionId + * subscription ID + * @return a management configuration instance + * @throws IOException + * if any error occurs when handling the specified file or the + * keystore + * @throws IllegalArgumentException + * if the file is not of the expected format + */ + public static Configuration createManagementConfiguration( + String publishSettingsFileName, String subscriptionId) + throws IOException { + if (publishSettingsFileName == null) { + throw new IllegalArgumentException("The publish settings file cannot be null."); + } + + if (subscriptionId == null) { + throw new IllegalArgumentException("The subscription ID cannot be null."); + } + + if (publishSettingsFileName.isEmpty()) { + throw new IllegalArgumentException("The publish settings file cannot be empty."); + } + + if (subscriptionId.isEmpty()) { + throw new IllegalArgumentException("The subscription ID cannot be empty."); + } + + File publishSettingsFile = new File(publishSettingsFileName); + // By default creating keystore output file in user home + String outputKeyStore = System.getProperty("user.home") + File.separator + + ".azure" + File.separator + subscriptionId + ".out"; + URI managementUrl = createCertficateFromPublishSettingsFile(publishSettingsFile, subscriptionId, outputKeyStore); + return ManagementConfiguration.configure(managementUrl, subscriptionId, outputKeyStore, "", + KeyStoreType.pkcs12); + } + + private static KeyStore createKeyStoreFromCertifcate(String certificate, String keyStoreFileName) throws IOException { + KeyStore keyStore = null; + try { + if (Float.valueOf(System.getProperty("java.specification.version")) < 1.7) { + // Use Bouncy Castle Provider for java versions less than 1.7 + keyStore = getBCProviderKeyStore(); + } else { + keyStore = KeyStore.getInstance("PKCS12"); + } + + keyStore.load(null, "".toCharArray()); + + InputStream sslInputStream = new ByteArrayInputStream( + Base64.decode(certificate)); + + keyStore.load(sslInputStream, "".toCharArray()); + + // create directories if does not exists + File outStoreFile = new File(keyStoreFileName); + if (!outStoreFile.getParentFile().exists()) { + outStoreFile.getParentFile().mkdirs(); + } + + OutputStream outputStream; + outputStream = new FileOutputStream(keyStoreFileName); + keyStore.store(outputStream, "".toCharArray()); + outputStream.close(); + + } catch (KeyStoreException e) { + throw new IllegalArgumentException( + "Cannot create keystore from the publish settings file", e); + } catch (CertificateException e) { + throw new IllegalArgumentException( + "Cannot create keystore from the publish settings file", e); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException( + "Cannot create keystore from the publish settings file", e); + } + + return keyStore; + } + + private static URI createCertficateFromPublishSettingsFile( + File publishSettingsFile, String subscriptionId, String outputKeyStore) throws IOException { + String certificate = null; + URI managementUri = null; + try { + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() + .newDocumentBuilder(); + Document document = documentBuilder.parse(publishSettingsFile); + document.getDocumentElement().normalize(); + NodeList publishProfileNodeList = document + .getElementsByTagName("PublishProfile"); + Element publishProfileElement = (Element) publishProfileNodeList.item(0); + if (publishProfileElement.hasAttribute("SchemaVersion") + && publishProfileElement.getAttribute("SchemaVersion").equals("2.0")) { + NodeList subscriptionNodeList = publishProfileElement.getElementsByTagName("Subscription"); + for (int i = 0; i < subscriptionNodeList.getLength(); i++) { + Element subscription = (Element) subscriptionNodeList.item(i); + String id = subscription.getAttribute("Id"); + if (id.equals(subscriptionId)) { + certificate = subscription.getAttribute("ManagementCertificate"); + String serviceManagementUrl = subscription.getAttribute("ServiceManagementUrl"); + try { + managementUri = new URI(serviceManagementUrl); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("The syntax of the Url in the publish settings file is incorrect.", e); + } + break; + } + } + } else { + certificate = publishProfileElement.getAttribute("ManagementCertificate"); + String url = publishProfileElement.getAttribute("Url"); + try { + managementUri = new URI(url); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("The syntax of the Url in the publish settings file is incorrect.", e); + } + } + } catch (ParserConfigurationException e) { + throw new IllegalArgumentException( + "could not parse publishsettings file", e); + } catch (SAXException e) { + throw new IllegalArgumentException( + "could not parse publishsettings file", e); + } catch (NullPointerException e) { + throw new IllegalArgumentException( + "could not parse publishsettings file", e); + } + + createKeyStoreFromCertifcate(certificate, outputKeyStore); + return managementUri; + } + + /** + * Sun JCE provider cannot open password less pfx files , refer to + * discussion @ https://community.oracle.com/thread/2334304 + * + * To read password less pfx files in java versions less than 1.7 need to + * use BouncyCastle's JCE provider + */ + private static KeyStore getBCProviderKeyStore() { + KeyStore keyStore = null; + try { + // Loading Bouncy castle classes dynamically so that BC dependency + // is only for java 1.6 clients + Class providerClass = Class + .forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); + Security.addProvider((Provider) providerClass.newInstance()); + + Field field = providerClass.getField("PROVIDER_NAME"); + keyStore = KeyStore.getInstance("PKCS12", field.get(null) + .toString()); + } catch (Exception e) { + // Using catch all exception class to avoid repeated code in + // different catch blocks + throw new RuntimeException( + "Could not create keystore from publishsettings file." + + "Make sure java versions less than 1.7 has bouncycastle jar in classpath", + e); + } + return keyStore; + } + +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/management/configuration/package.html b/core/src/main/java/com/microsoft/windowsazure/management/configuration/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/management/configuration/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/package.html b/core/src/main/java/com/microsoft/windowsazure/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/java/com/microsoft/windowsazure/tracing/ClientRequestTrackingHandler.java b/core/src/main/java/com/microsoft/windowsazure/tracing/ClientRequestTrackingHandler.java new file mode 100644 index 0000000000000..316cd3b803990 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/tracing/ClientRequestTrackingHandler.java @@ -0,0 +1,45 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.tracing; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; + +public class ClientRequestTrackingHandler implements ServiceRequestFilter, + ServiceResponseFilter { + private final String trackingId; + + public String getTrackingId() { + return trackingId; + } + + public ClientRequestTrackingHandler(String trackingId) { + this.trackingId = trackingId; + } + + @Override + public void filter(ServiceRequestContext request) { + request.setHeader("client-tracking-id", trackingId); + } + + @Override + public void filter(ServiceRequestContext request, + ServiceResponseContext response) { + response.setHeader("client-tracking-id", trackingId); + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/tracing/CloudTracing.java b/core/src/main/java/com/microsoft/windowsazure/tracing/CloudTracing.java new file mode 100644 index 0000000000000..9039a3782c3c2 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/tracing/CloudTracing.java @@ -0,0 +1,194 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.tracing; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; + +/** + * Provides tracing utilities that insight into all aspects of client operations + * via implementations of the ICloudTracingInterceptor interface. All tracing is + * global. + */ +public abstract class CloudTracing { + private CloudTracing() { + } + + /** + * The collection of tracing interceptors to notify. + */ + private static List interceptors; + + /** + * Gets the collection of tracing interceptors to notify. + * + * @return the collection of tracing interceptors. + */ + public static List getInterceptors() { + return interceptors; + } + + /** + * Gets a value indicating whether tracing is enabled. Tracing can be + * disabled for performance. + */ + private static boolean isEnabled; + + /** + * Gets the value indicating whether tracing is enabled. + * + * @return Boolean value indicating if tracing is enabled. + */ + public static boolean getIsEnabled() { + return isEnabled; + } + + /** + * Sets the value indicating whether tracing is enabled. + * + * @param enabled + * Boolean value indicating if tracing is enabled. + */ + public static void setIsEnabled(final boolean enabled) { + isEnabled = enabled; + } + + static { + isEnabled = true; + interceptors = Collections + .synchronizedList(new ArrayList()); + } + + /** + * Add a tracing interceptor to be notified of changes. + * + * @param cloudTracingInterceptor + * The tracing interceptor. + */ + public static void addTracingInterceptor( + final CloudTracingInterceptor cloudTracingInterceptor) { + if (cloudTracingInterceptor == null) { + throw new NullPointerException(); + } + + interceptors.add(cloudTracingInterceptor); + } + + /** + * Remove a tracing interceptor from change notifications. + * + * @param cloudTracingInterceptor + * The tracing interceptor. + * @return True if the tracing interceptor was found and removed; false + * otherwise. + */ + public static boolean removeTracingInterceptor( + CloudTracingInterceptor cloudTracingInterceptor) { + if (cloudTracingInterceptor == null) { + throw new NullPointerException(); + } + + return interceptors.remove(cloudTracingInterceptor); + } + + private static long nextInvocationId = 0; + + public static long getNextInvocationId() { + return ++nextInvocationId; + } + + public static void information(String message, Object... parameters) { + if (isEnabled) { + information(String.format(message, parameters)); + } + } + + public static void configuration(String source, String name, String value) { + if (isEnabled) { + synchronized (interceptors) { + for (CloudTracingInterceptor writer : interceptors) { + writer.configuration(source, name, value); + } + } + } + } + + public static void information(String message) { + if (isEnabled) { + synchronized (interceptors) { + for (CloudTracingInterceptor writer : interceptors) { + writer.information(message); + } + } + } + } + + public static void enter(String invocationId, Object instance, + String method, HashMap parameters) { + if (isEnabled) { + synchronized (interceptors) { + for (CloudTracingInterceptor writer : interceptors) { + writer.enter(invocationId, instance, method, parameters); + } + } + } + } + + public static void sendRequest(String invocationId, HttpRequest request) { + if (isEnabled) { + synchronized (interceptors) { + for (CloudTracingInterceptor writer : interceptors) { + writer.sendRequest(invocationId, request); + } + } + } + } + + public static void receiveResponse(String invocationId, + HttpResponse response) { + if (isEnabled) { + synchronized (interceptors) { + for (CloudTracingInterceptor writer : interceptors) { + writer.receiveResponse(invocationId, response); + } + } + } + } + + public static void error(String invocationId, Exception ex) { + if (isEnabled) { + synchronized (interceptors) { + for (CloudTracingInterceptor writer : interceptors) { + writer.error(invocationId, ex); + } + } + } + } + + public static void exit(String invocationId, Object result) { + if (isEnabled) { + synchronized (interceptors) { + for (CloudTracingInterceptor writer : interceptors) { + writer.exit(invocationId, result); + } + } + } + } +} diff --git a/core/src/main/java/com/microsoft/windowsazure/tracing/CloudTracingInterceptor.java b/core/src/main/java/com/microsoft/windowsazure/tracing/CloudTracingInterceptor.java new file mode 100644 index 0000000000000..fa0512edf1ac1 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/tracing/CloudTracingInterceptor.java @@ -0,0 +1,102 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.tracing; + +import java.util.HashMap; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; + +/** + * The CloudTracingInterceptor provides useful information about cloud + * operations. Interception is global and a tracing interceptor can be added via + * CloudContext.Configuration.Tracing.AddTracingInterceptor. + */ +public interface CloudTracingInterceptor { + /** + * Trace information. + * + * @param message + * The information to trace. + */ + void information(String message); + + /** + * Probe configuration for the value of a setting. + * + * @param source + * The configuration source. + * @param name + * The name of the setting. + * @param value + * The value of the setting in the source. + */ + void configuration(String source, String name, String value); + + /** + * Enter a method. + * + * @param invocationId + * Method invocation identifier. + * @param instance + * The instance with the method. + * @param method + * Name of the method. + * @param parameters + * Method parameters. + */ + void enter(String invocationId, Object instance, String method, + HashMap parameters); + + /** + * Send an HTTP request. + * + * @param invocationId + * Method invocation identifier. + * @param request + * The request about to be sent. + */ + void sendRequest(String invocationId, HttpRequest request); + + /** + * Receive an HTTP response. + * + * @param invocationId + * Method invocation identifier. + * @param response + * The response instance. + */ + void receiveResponse(String invocationId, HttpResponse response); + + /** + * Raise an error. + * + * @param invocationId + * Method invocation identifier. + * @param exception + * The error. + */ + void error(String invocationId, Exception exception); + + /** + * Exit a method. Note: Exit will not be called in the event of an error. + * + * @param invocationId + * Method invocation identifier. + * @param returnValue + * Method return value. + */ + void exit(String invocationId, Object returnValue); +} \ No newline at end of file diff --git a/core/src/main/java/com/microsoft/windowsazure/tracing/package.html b/core/src/main/java/com/microsoft/windowsazure/tracing/package.html new file mode 100644 index 0000000000000..513ca5833c7a6 --- /dev/null +++ b/core/src/main/java/com/microsoft/windowsazure/tracing/package.html @@ -0,0 +1,5 @@ + + +This package contains the core classes across difference services. + + diff --git a/core/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/core/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..851da60ffee71 --- /dev/null +++ b/core/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1,5 @@ +com.microsoft.windowsazure.core.pipeline.apache.Exports +com.microsoft.windowsazure.core.pipeline.jersey.Exports +com.microsoft.windowsazure.core.utils.Exports +com.microsoft.windowsazure.credentials.Exports +com.microsoft.windowsazure.management.configuration.Exports \ No newline at end of file diff --git a/core/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java new file mode 100644 index 0000000000000..4953b653907e6 --- /dev/null +++ b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java @@ -0,0 +1,30 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +import java.util.Map; + +import com.microsoft.windowsazure.core.Builder; + +public class AlterClassWithProperties implements + Builder.Alteration { + @Override + public ClassWithProperties alter(String profile, + ClassWithProperties instance, Builder builder, + Map properties) { + instance.setFoo(instance.getFoo() + " - changed"); + return instance; + } +} \ No newline at end of file diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorMultipleInject.java b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorMultipleInject.java similarity index 100% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorMultipleInject.java rename to core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorMultipleInject.java diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorNoInject.java b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorNoInject.java similarity index 100% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorNoInject.java rename to core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorNoInject.java diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithNamedParameter.java b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithNamedParameter.java similarity index 100% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithNamedParameter.java rename to core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithNamedParameter.java diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithProperties.java b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithProperties.java similarity index 100% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithProperties.java rename to core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithProperties.java diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithSingleCtorNoInject.java b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithSingleCtorNoInject.java similarity index 100% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithSingleCtorNoInject.java rename to core/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithSingleCtorNoInject.java diff --git a/core/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java new file mode 100644 index 0000000000000..65976cf1009c0 --- /dev/null +++ b/core/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java @@ -0,0 +1,203 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +import java.util.HashMap; +import java.util.Map; + + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import com.microsoft.windowsazure.core.DefaultBuilder; + +public class DefaultBuilderTest { + + Map properties; + DefaultBuilder builder; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Before + public void init() { + properties = new HashMap(); + builder = new DefaultBuilder(); + } + + @Test + public void namedAnnotationsComeFromBuildProperties() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + + // Act + Map properties = new HashMap(); + properties.put("Foo", "world"); + ClassWithNamedParameter cwnp = builder.build("", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("world", cwnp.getHello()); + } + + @Test + public void namedAnnotationReportsMissingProperty() throws Exception { + // Arrange + thrown.expect(RuntimeException.class); + + builder.add(ClassWithNamedParameter.class); + + // Act + ClassWithNamedParameter cwnp = builder.build("", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("world", cwnp.getHello()); + } + + @Test + public void singleCtorWithNoInjectShouldBeUsed() throws Exception { + // Arrange + builder.add(ClassWithSingleCtorNoInject.class); + + // Act + ClassWithSingleCtorNoInject result = builder.build("", + ClassWithSingleCtorNoInject.class, + ClassWithSingleCtorNoInject.class, properties); + + // Assert + Assert.assertNotNull(result); + } + + @Test + public void multipleCtorWithNoInjectShouldFail() throws Exception { + // Arrange + thrown.expect(RuntimeException.class); + + builder.add(ClassWithMultipleCtorNoInject.class); + + // Act + ClassWithMultipleCtorNoInject result = builder.build("", + ClassWithMultipleCtorNoInject.class, + ClassWithMultipleCtorNoInject.class, properties); + + // Assert + Assert.assertTrue("Exception must occur", false); + Assert.assertNull("Result should be null", result); + } + + @Test + public void multipleCtorWithMultipleInjectShouldFail() throws Exception { + // Arrange + thrown.expect(RuntimeException.class); + + builder.add(ClassWithMultipleCtorMultipleInject.class); + + // Act + ClassWithMultipleCtorMultipleInject result = builder.build("", + ClassWithMultipleCtorMultipleInject.class, + ClassWithMultipleCtorMultipleInject.class, properties); + + // Assert + Assert.assertTrue("Exception must occur", false); + Assert.assertNull("Result should be null", result); + } + + @Test + public void alterationExecutesWhenInstanceCreated() throws Exception { + // Arrange + builder.add(ClassWithProperties.class); + builder.alter(ClassWithProperties.class, ClassWithProperties.class, + new AlterClassWithProperties()); + + // Act + ClassWithProperties result = builder.build("", + ClassWithProperties.class, ClassWithProperties.class, + properties); + + // Assert + Assert.assertEquals("one - changed", result.getFoo()); + } + + @Test + public void namedParametersUseProfileBasedKeysFirst() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + properties.put("Foo", "fallback"); + properties.put("testing.Foo", "Profile foo value"); + + // Act + ClassWithNamedParameter result = builder.build("testing", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("Profile foo value", result.getHello()); + } + + @Test + public void namedParametersFallBackToNonProfileBasedKeys() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + properties.put("Foo", "fallback"); + properties.put("testing.Foo", "Profile foo value"); + + // Act + ClassWithNamedParameter result1 = builder.build("", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result2 = builder.build("production", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result3 = builder.build("testing.custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("fallback", result1.getHello()); + Assert.assertEquals("fallback", result2.getHello()); + Assert.assertEquals("fallback", result3.getHello()); + } + + @Test + public void namedParamatersFallBackFromLeftToRight() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + properties.put("Foo", "fallback"); + properties.put("custom.Foo", "custom.Foo value"); + properties.put("testing.custom.Foo", "testing.custom.Foo value"); + + // Act + ClassWithNamedParameter result1 = builder.build("custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result2 = builder.build("production.custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result3 = builder.build("testing.custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("custom.Foo value", result1.getHello()); + Assert.assertEquals("custom.Foo value", result2.getHello()); + Assert.assertEquals("testing.custom.Foo value", result3.getHello()); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/ISO8601DateConverterTests.java b/core/src/test/java/com/microsoft/windowsazure/core/ISO8601DateConverterTests.java similarity index 97% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/ISO8601DateConverterTests.java rename to core/src/test/java/com/microsoft/windowsazure/core/ISO8601DateConverterTests.java index f25703bad210a..cb08e8b8eaa38 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/ISO8601DateConverterTests.java +++ b/core/src/test/java/com/microsoft/windowsazure/core/ISO8601DateConverterTests.java @@ -12,8 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.core; +package com.microsoft.windowsazure.core; +import com.microsoft.windowsazure.core.ISO8601DateConverter; import static org.junit.Assert.*; import java.util.Calendar; diff --git a/core/src/test/java/com/microsoft/windowsazure/core/TimeSpan8601ConverterTests.java b/core/src/test/java/com/microsoft/windowsazure/core/TimeSpan8601ConverterTests.java new file mode 100644 index 0000000000000..4b66244b48ef1 --- /dev/null +++ b/core/src/test/java/com/microsoft/windowsazure/core/TimeSpan8601ConverterTests.java @@ -0,0 +1,45 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.core; + +import com.microsoft.windowsazure.core.TimeSpan8601Converter; +import static org.junit.Assert.*; + +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; +import org.junit.Test; + +public class TimeSpan8601ConverterTests { + @Test + public void formatShouldWork() throws Exception { + DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance(); + Duration duration = dataTypeFactory.newDurationDayTime(true, 0, 3, 10, + 2); + String durationString = TimeSpan8601Converter.format(duration); + + assertEquals("P0DT3H10M2S", durationString); + } + + @Test + public void parseShouldWork() throws Exception { + Duration duration = TimeSpan8601Converter.parse("P0DT3H10M2S"); + + assertEquals(0, duration.getDays()); + assertEquals(3, duration.getHours()); + assertEquals(10, duration.getMinutes()); + assertEquals(2, duration.getSeconds()); + } +} diff --git a/core/src/test/java/com/microsoft/windowsazure/core/pipeline/PipelineHelpersTest.java b/core/src/test/java/com/microsoft/windowsazure/core/pipeline/PipelineHelpersTest.java new file mode 100644 index 0000000000000..71746638df562 --- /dev/null +++ b/core/src/test/java/com/microsoft/windowsazure/core/pipeline/PipelineHelpersTest.java @@ -0,0 +1,47 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.pipeline; + +import com.microsoft.windowsazure.core.pipeline.PipelineHelpers; +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; + +public class PipelineHelpersTest { + @Test + public void addOptionalSourceAccessConditionHeaderSuccess() + throws Exception { + // Arrange + Client client = Client.create(); + WebResource webResource = client.resource("http://www.microsoft.com"); + Builder builder = webResource.header("ms-version", "1.0"); + AccessConditionHeader accessCondition = AccessConditionHeader + .ifMatch("thisIsAETag"); + + // Act + Builder resultBuilder = PipelineHelpers + .addOptionalSourceAccessConditionHeader(builder, + accessCondition); + + // Assert + assertNotNull(resultBuilder); + + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/utils/ParsedConnectionStringTest.java b/core/src/test/java/com/microsoft/windowsazure/core/utils/ParsedConnectionStringTest.java similarity index 76% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/utils/ParsedConnectionStringTest.java rename to core/src/test/java/com/microsoft/windowsazure/core/utils/ParsedConnectionStringTest.java index 096149abaeb72..a0d3fe27babbd 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/utils/ParsedConnectionStringTest.java +++ b/core/src/test/java/com/microsoft/windowsazure/core/utils/ParsedConnectionStringTest.java @@ -13,22 +13,25 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.core.utils; +package com.microsoft.windowsazure.core.utils; +import com.microsoft.windowsazure.core.utils.ConnectionStringSyntaxException; +import com.microsoft.windowsazure.core.utils.ParsedConnectionString; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import com.microsoft.windowsazure.services.core.utils.pipeline.ConnectionStringField; +import com.microsoft.windowsazure.core.pipeline.ConnectionStringField; public class ParsedConnectionStringTest { private static class OneField extends ParsedConnectionString { private String aField; - public OneField(String connectionString) throws ConnectionStringSyntaxException { + public OneField(String connectionString) + throws ConnectionStringSyntaxException { super(connectionString); } @@ -43,7 +46,8 @@ protected void setAField(String aField) { } @Test - public void shouldSuccessfullyParseValidStringWithOneField() throws Exception { + public void shouldSuccessfullyParseValidStringWithOneField() + throws Exception { OneField cs = new OneField("AField=avalue"); assertEquals("avalue", cs.getAField()); @@ -54,7 +58,8 @@ private static class ThreeFields extends ParsedConnectionString { private String fieldTwo; private int fieldThree; - public ThreeFields(String connectionString) throws ConnectionStringSyntaxException { + public ThreeFields(String connectionString) + throws ConnectionStringSyntaxException { super(connectionString); } @@ -80,7 +85,6 @@ public int getFieldThree() { return fieldThree; } - @SuppressWarnings("unused") @ConnectionStringField(name = "fieldthree") protected void setNumericField(String fieldThree) { this.fieldThree = Integer.parseInt(fieldThree); @@ -88,8 +92,10 @@ protected void setNumericField(String fieldThree) { } @Test - public void shouldSuccessfullyParseValidStringWithMultipleFields() throws Exception { - ThreeFields cs = new ThreeFields("FieldOne=hello;FieldTwo=world;FieldThree=27"); + public void shouldSuccessfullyParseValidStringWithMultipleFields() + throws Exception { + ThreeFields cs = new ThreeFields( + "FieldOne=hello;FieldTwo=world;FieldThree=27"); assertEquals("hello", cs.getFieldOne()); assertEquals("world", cs.getFieldTwo()); @@ -97,8 +103,10 @@ public void shouldSuccessfullyParseValidStringWithMultipleFields() throws Except } @Test - public void shouldSuccessFullyParseValisStringWithQuotedKeysAndValues() throws Exception { - ThreeFields cs = new ThreeFields("FieldOne=hello;'FieldTwo'=world;FieldThree='27'"); + public void shouldSuccessFullyParseValisStringWithQuotedKeysAndValues() + throws Exception { + ThreeFields cs = new ThreeFields( + "FieldOne=hello;'FieldTwo'=world;FieldThree='27'"); assertEquals("hello", cs.getFieldOne()); assertEquals("world", cs.getFieldTwo()); @@ -116,13 +124,15 @@ public void shouldThrowForFieldThatDoesntExist() throws Exception { @Test public void shouldNotThrowIfValueMissing() throws Exception { - ThreeFields cs = new ThreeFields(" FieldOne= hello; FieldTwo =;FieldThree=19 "); + ThreeFields cs = new ThreeFields( + " FieldOne= hello; FieldTwo =;FieldThree=19 "); assertEquals("", cs.getFieldTwo()); } @Test public void shouldIgnoreEmptyPairsAndExtraSemicolons() throws Exception { - ThreeFields cs = new ThreeFields("FieldOne=hello;; ; 'FieldTwo'=world;FieldThree='27';"); + ThreeFields cs = new ThreeFields( + "FieldOne=hello;; ; 'FieldTwo'=world;FieldThree='27';"); assertEquals("hello", cs.getFieldOne()); assertEquals("world", cs.getFieldTwo()); diff --git a/core/src/test/java/com/microsoft/windowsazure/management/configuration/PublishSettingsLoaderTest.java b/core/src/test/java/com/microsoft/windowsazure/management/configuration/PublishSettingsLoaderTest.java new file mode 100644 index 0000000000000..f720986d4b258 --- /dev/null +++ b/core/src/test/java/com/microsoft/windowsazure/management/configuration/PublishSettingsLoaderTest.java @@ -0,0 +1,101 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.configuration; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import org.junit.Test; +import com.microsoft.windowsazure.Configuration; + +/** + * The certificate used in the test publishsettings file is a dummy one + * generated for this unit test. Here's how to create one (press + * ENTER at any prompt): + * + *

+ * + * openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
+ * openssl pkcs12 -export -out mycert.pfx -in mycert.pem -name "My Certificate"
+ * base64 mycert.pfx > mycert.b64
+ *
+ *

+ * + * Remove all line-breaks in mycert.b64 and copy & paste into the + * ManagementCertificate attribute. + */ +public class PublishSettingsLoaderTest { + + @Test + public void shouldCreateManagementConfigurationFromVersion1() + throws Exception { + // Arrange + String file = getClass().getResource("v1.publishsettings").getFile(); + String expectedKeyStoreLocation = System.getProperty("user.home") + File.separator + + ".azure" + File.separator + "1234.out"; + + // Act + Configuration config = PublishSettingsLoader + .createManagementConfiguration(file, "1234"); + + // Assert + assertEquals("subscriptionId", "1234", + config.getProperty(ManagementConfiguration.SUBSCRIPTION_ID)); + assertEquals("keyStoreLocation", expectedKeyStoreLocation, + config.getProperty(ManagementConfiguration.KEYSTORE_PATH)); + assertEquals("keyStorePassword", "", + config.getProperty(ManagementConfiguration.KEYSTORE_PASSWORD)); + } + + @Test + public void shouldCreateManagementConfigurationFromVersion2() + throws Exception { + // Arrange + String file = getClass().getResource("v2.publishsettings").getFile(); + String expectedKeyStoreLocation = System.getProperty("user.home") + File.separator + + ".azure" + File.separator + "2345.out"; + + // Act + Configuration config = PublishSettingsLoader + .createManagementConfiguration(file, "2345"); + + // Assert + assertEquals("subscriptionId", "2345", + config.getProperty(ManagementConfiguration.SUBSCRIPTION_ID)); + assertEquals("keyStoreLocation", expectedKeyStoreLocation, + config.getProperty(ManagementConfiguration.KEYSTORE_PATH)); + assertEquals("keyStorePassword", "", + config.getProperty(ManagementConfiguration.KEYSTORE_PASSWORD)); + } + + @Test(expected = IOException.class) + public void shouldFailOnNonExistingFile() throws Exception { + // Act + PublishSettingsLoader.createManagementConfiguration("nonexisting", + "1234"); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldFailOnFaultyFile() throws Exception { + // Arrange + String file = getClass().getResource("faulty.publishsettings") + .getFile(); + + // Act + PublishSettingsLoader.createManagementConfiguration(file, "1234"); + } + +} diff --git a/core/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java b/core/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java new file mode 100644 index 0000000000000..f6c28157babbe --- /dev/null +++ b/core/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java @@ -0,0 +1,105 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.utils; + +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; +import java.net.SocketTimeoutException; + +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.core.ServiceTimeoutException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class ServiceExceptionFactoryTest { + @Test + public void serviceNameAndMessageAndCauseAppearInException() { + // Arrange + ClientResponse response = new ClientResponse(404, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException cause = new UniformInterfaceException( + response); + + // Act + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException("this is a test", cause)); + + // Assert + assertNotNull(exception); + assertEquals("testing", exception.getServiceName()); + assertEquals("this is a test", exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void httpStatusCodeAndReasonPhraseAppearInException() { + // Arrange + ClientResponse response = new ClientResponse(404, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException cause = new UniformInterfaceException( + response); + + // Act + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException("this is a test", cause)); + + // Assert + assertNotNull(exception); + assertEquals(404, exception.getHttpStatusCode()); + assertEquals("Not Found", exception.getHttpReasonPhrase()); + } + + @Test + public void informationWillPassUpIfServiceExceptionIsRootCauseOfClientHandlerExceptions() { + // Arrange + ClientResponse response = new ClientResponse(503, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException rootCause = new UniformInterfaceException( + response); + ServiceException originalDescription = ServiceExceptionFactory.process( + "underlying", new ServiceException(rootCause)); + ClientHandlerException wrappingException = new ClientHandlerException( + originalDescription); + + // Act + ServiceException exception = ServiceExceptionFactory.process("actual", + new ServiceException(wrappingException)); + + // Assert + assertEquals(503, exception.getHttpStatusCode()); + assertEquals("underlying", exception.getServiceName()); + } + + @Test + public void socketTimeoutWillPassUpIfInsideClientHandlerException() { + String expectedMessage = "connect timeout"; + SocketTimeoutException rootCause = new SocketTimeoutException( + expectedMessage); + ClientHandlerException wrappingException = new ClientHandlerException( + rootCause); + + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException(wrappingException)); + + assertSame(ServiceTimeoutException.class, exception.getClass()); + assertEquals(expectedMessage, exception.getMessage()); + assertEquals("testing", exception.getServiceName()); + } +} diff --git a/microsoft-azure-api/src/test/resources/META-INF/com.microsoft.windowsazure.properties b/core/src/test/resources/META-INF/com.microsoft.windowsazure.properties similarity index 100% rename from microsoft-azure-api/src/test/resources/META-INF/com.microsoft.windowsazure.properties rename to core/src/test/resources/META-INF/com.microsoft.windowsazure.properties diff --git a/core/src/test/resources/com/microsoft/windowsazure/management/configuration/faulty.publishsettings b/core/src/test/resources/com/microsoft/windowsazure/management/configuration/faulty.publishsettings new file mode 100644 index 0000000000000..47e2a406af26e --- /dev/null +++ b/core/src/test/resources/com/microsoft/windowsazure/management/configuration/faulty.publishsettings @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file diff --git a/core/src/test/resources/com/microsoft/windowsazure/management/configuration/v1.publishsettings b/core/src/test/resources/com/microsoft/windowsazure/management/configuration/v1.publishsettings new file mode 100644 index 0000000000000..09cc20bdb787b --- /dev/null +++ b/core/src/test/resources/com/microsoft/windowsazure/management/configuration/v1.publishsettings @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file diff --git a/core/src/test/resources/com/microsoft/windowsazure/management/configuration/v2.publishsettings b/core/src/test/resources/com/microsoft/windowsazure/management/configuration/v2.publishsettings new file mode 100644 index 0000000000000..511e24858412a --- /dev/null +++ b/core/src/test/resources/com/microsoft/windowsazure/management/configuration/v2.publishsettings @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/management-compute/pom.xml b/management-compute/pom.xml new file mode 100644 index 0000000000000..250bea4b33fc6 --- /dev/null +++ b/management-compute/pom.xml @@ -0,0 +1,169 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-management-compute + jar + + Microsoft Azure Compute Management Client API + Microsoft Azure Compute Management SDK Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + 2.1.1 + 3.0.7.RELEASE + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + org.apache.httpcomponents + httpclient + + + javax.inject + javax.inject + + + + + ${project.groupId} + microsoft-azure-api-management-storage + 0.5.0 + test + + + ${project.groupId} + microsoft-azure-api-management + 0.5.0 + test + + + com.microsoft.windowsazure.storage + microsoft-windowsazure-storage-sdk + 0.5.0 + test + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk16 + test + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+
+
diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementClient.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementClient.java new file mode 100644 index 0000000000000..6930d73934add --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementClient.java @@ -0,0 +1,192 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.FilterableService; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import java.io.Closeable; +import java.io.IOException; +import java.net.URI; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API provides programmatic access to much of the +* functionality available through the Management Portal. The Service +* Management API is a REST API. All API operations are performed over SSL, and +* are mutually authenticated using X.509 v3 certificates. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for more +* information) +*/ +public interface ComputeManagementClient extends Closeable, FilterableService { + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + URI getBaseUri(); + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + SubscriptionCloudCredentials getCredentials(); + + /** + * The Service Management API includes operations for managing the + * deployments in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for + * more information) + * @return The DeploymentsOperations value. + */ + DeploymentOperations getDeploymentsOperations(); + + /** + * The Service Management API includes operations for managing the hosted + * services beneath your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for + * more information) + * @return The HostedServicesOperations value. + */ + HostedServiceOperations getHostedServicesOperations(); + + /** + * Operations for determining the version of the Azure Guest Operating + * System on which your service is running. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ff684169.aspx for + * more information) + * @return The OperatingSystemsOperations value. + */ + OperatingSystemOperations getOperatingSystemsOperations(); + + /** + * Operations for managing service certificates for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for + * more information) + * @return The ServiceCertificatesOperations value. + */ + ServiceCertificateOperations getServiceCertificatesOperations(); + + /** + * The Service Management API includes operations for managing the disks in + * your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx for + * more information) + * @return The VirtualMachineDisksOperations value. + */ + VirtualMachineDiskOperations getVirtualMachineDisksOperations(); + + /** + * The Service Management API includes operations for managing the virtual + * machine extensions in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for + * more information) + * @return The VirtualMachineExtensionsOperations value. + */ + VirtualMachineExtensionOperations getVirtualMachineExtensionsOperations(); + + /** + * The Service Management API includes operations for managing the virtual + * machines in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for + * more information) + * @return The VirtualMachinesOperations value. + */ + VirtualMachineOperations getVirtualMachinesOperations(); + + /** + * The Service Management API includes operations for managing the OS images + * in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx for + * more information) + * @return The VirtualMachineOSImagesOperations value. + */ + VirtualMachineOSImageOperations getVirtualMachineOSImagesOperations(); + + /** + * The Service Management API includes operations for managing the virtual + * machine templates in your subscription. + * @return The VirtualMachineVMImagesOperations value. + */ + VirtualMachineVMImageOperations getVirtualMachineVMImagesOperations(); + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future getOperationStatusAsync(String requestId); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementClientImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementClientImpl.java new file mode 100644 index 0000000000000..addafde1e4034 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementClientImpl.java @@ -0,0 +1,536 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceClient; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.CertificateFormat; +import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbeTransportProtocol; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import javax.inject.Inject; +import javax.inject.Named; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API provides programmatic access to much of the +* functionality available through the Management Portal. The Service +* Management API is a REST API. All API operations are performed over SSL, and +* are mutually authenticated using X.509 v3 certificates. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for more +* information) +*/ +public class ComputeManagementClientImpl extends ServiceClient implements ComputeManagementClient { + private URI baseUri; + + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + public URI getBaseUri() { + return this.baseUri; + } + + private SubscriptionCloudCredentials credentials; + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + public SubscriptionCloudCredentials getCredentials() { + return this.credentials; + } + + private DeploymentOperations deployments; + + /** + * The Service Management API includes operations for managing the + * deployments in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for + * more information) + * @return The DeploymentsOperations value. + */ + public DeploymentOperations getDeploymentsOperations() { + return this.deployments; + } + + private HostedServiceOperations hostedServices; + + /** + * The Service Management API includes operations for managing the hosted + * services beneath your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for + * more information) + * @return The HostedServicesOperations value. + */ + public HostedServiceOperations getHostedServicesOperations() { + return this.hostedServices; + } + + private OperatingSystemOperations operatingSystems; + + /** + * Operations for determining the version of the Azure Guest Operating + * System on which your service is running. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ff684169.aspx for + * more information) + * @return The OperatingSystemsOperations value. + */ + public OperatingSystemOperations getOperatingSystemsOperations() { + return this.operatingSystems; + } + + private ServiceCertificateOperations serviceCertificates; + + /** + * Operations for managing service certificates for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for + * more information) + * @return The ServiceCertificatesOperations value. + */ + public ServiceCertificateOperations getServiceCertificatesOperations() { + return this.serviceCertificates; + } + + private VirtualMachineDiskOperations virtualMachineDisks; + + /** + * The Service Management API includes operations for managing the disks in + * your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx for + * more information) + * @return The VirtualMachineDisksOperations value. + */ + public VirtualMachineDiskOperations getVirtualMachineDisksOperations() { + return this.virtualMachineDisks; + } + + private VirtualMachineExtensionOperations virtualMachineExtensions; + + /** + * The Service Management API includes operations for managing the virtual + * machine extensions in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for + * more information) + * @return The VirtualMachineExtensionsOperations value. + */ + public VirtualMachineExtensionOperations getVirtualMachineExtensionsOperations() { + return this.virtualMachineExtensions; + } + + private VirtualMachineOperations virtualMachines; + + /** + * The Service Management API includes operations for managing the virtual + * machines in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for + * more information) + * @return The VirtualMachinesOperations value. + */ + public VirtualMachineOperations getVirtualMachinesOperations() { + return this.virtualMachines; + } + + private VirtualMachineOSImageOperations virtualMachineOSImages; + + /** + * The Service Management API includes operations for managing the OS images + * in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx for + * more information) + * @return The VirtualMachineOSImagesOperations value. + */ + public VirtualMachineOSImageOperations getVirtualMachineOSImagesOperations() { + return this.virtualMachineOSImages; + } + + private VirtualMachineVMImageOperations virtualMachineVMImages; + + /** + * The Service Management API includes operations for managing the virtual + * machine templates in your subscription. + * @return The VirtualMachineVMImagesOperations value. + */ + public VirtualMachineVMImageOperations getVirtualMachineVMImagesOperations() { + return this.virtualMachineVMImages; + } + + /** + * Initializes a new instance of the ComputeManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + private ComputeManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) { + super(httpBuilder, executorService); + this.deployments = new DeploymentOperationsImpl(this); + this.hostedServices = new HostedServiceOperationsImpl(this); + this.operatingSystems = new OperatingSystemOperationsImpl(this); + this.serviceCertificates = new ServiceCertificateOperationsImpl(this); + this.virtualMachineDisks = new VirtualMachineDiskOperationsImpl(this); + this.virtualMachineExtensions = new VirtualMachineExtensionOperationsImpl(this); + this.virtualMachines = new VirtualMachineOperationsImpl(this); + this.virtualMachineOSImages = new VirtualMachineOSImageOperationsImpl(this); + this.virtualMachineVMImages = new VirtualMachineVMImageOperationsImpl(this); + } + + /** + * Initializes a new instance of the ComputeManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @param baseUri Required. The URI used as the base for all Service + * Management requests. + */ + @Inject + public ComputeManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } else { + this.credentials = credentials; + } + if (baseUri == null) { + try { + this.baseUri = new URI("https://management.core.windows.net"); + } + catch (URISyntaxException ex) { + } + } else { + this.baseUri = baseUri; + } + } + + /** + * Initializes a new instance of the ComputeManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + */ + public ComputeManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } + this.credentials = credentials; + this.baseUri = new URI("https://management.core.windows.net"); + } + + /** + * Initializes a new instance of the ComputeManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + protected ComputeManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) { + return new ComputeManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri()); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future getOperationStatusAsync(final String requestId) { + return this.getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return getOperationStatus(requestId); + } + }); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (requestId == null) { + throw new NullPointerException("requestId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("requestId", requestId); + CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getBaseUri().toString(); + String url = "/" + this.getCredentials().getSubscriptionId().trim() + "/operations/" + requestId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new OperationStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setId(idInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + OperationStatus statusInstance; + statusInstance = OperationStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "HttpStatusCode"); + if (httpStatusCodeElement != null) { + Integer httpStatusCodeInstance; + httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent()); + result.setHttpStatusCode(httpStatusCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); + result.setError(errorInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + errorInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + errorInstance.setMessage(messageInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Parse enum values for type CertificateFormat. + * + * @param value The value to parse. + * @return The enum value. + */ + static CertificateFormat parseCertificateFormat(String value) { + if ("pfx".equalsIgnoreCase(value)) { + return CertificateFormat.Pfx; + } + if ("cer".equalsIgnoreCase(value)) { + return CertificateFormat.Cer; + } + throw new IllegalArgumentException("value"); + } + + /** + * Convert an enum of type CertificateFormat to a string. + * + * @param value The value to convert to a string. + * @return The enum value as a string. + */ + static String certificateFormatToString(CertificateFormat value) { + if (value == CertificateFormat.Pfx) { + return "pfx"; + } + if (value == CertificateFormat.Cer) { + return "cer"; + } + throw new IllegalArgumentException("value"); + } + + /** + * Parse enum values for type LoadBalancerProbeTransportProtocol. + * + * @param value The value to parse. + * @return The enum value. + */ + static LoadBalancerProbeTransportProtocol parseLoadBalancerProbeTransportProtocol(String value) { + if ("tcp".equalsIgnoreCase(value)) { + return LoadBalancerProbeTransportProtocol.Tcp; + } + if ("http".equalsIgnoreCase(value)) { + return LoadBalancerProbeTransportProtocol.Http; + } + throw new IllegalArgumentException("value"); + } + + /** + * Convert an enum of type LoadBalancerProbeTransportProtocol to a string. + * + * @param value The value to convert to a string. + * @return The enum value as a string. + */ + static String loadBalancerProbeTransportProtocolToString(LoadBalancerProbeTransportProtocol value) { + if (value == LoadBalancerProbeTransportProtocol.Tcp) { + return "tcp"; + } + if (value == LoadBalancerProbeTransportProtocol.Http) { + return "http"; + } + throw new IllegalArgumentException("value"); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementService.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementService.java new file mode 100644 index 0000000000000..eb78088c8cf15 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ComputeManagementService.java @@ -0,0 +1,74 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.Configuration; + +/** + * + * Access service management functionality. + * + */ +public final class ComputeManagementService { + private ComputeManagementService() { + // class is not instantiated + } + + /** + * Creates an instance of the ComputeManagementClient API. + * @return An instance of the ComputeManagementClient API. + */ + public static ComputeManagementClient create() { + return Configuration.getInstance().create( + ComputeManagementClient.class); + } + + /** + * Creates an instance of the ComputeManagementClient API using + * the specified configuration. + * + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the ComputeManagementClient API. + */ + public static ComputeManagementClient create(final Configuration config) { + return config.create(ComputeManagementClient.class); + } + + /** + * Creates an instance of the ComputeManagementClient API. + * + * @param profile A String object that representing the profile + * of the service management service. + * @return An instance of the ComputeManagementClient API. + */ + public static ComputeManagementClient create(final String profile) { + return Configuration.getInstance().create(profile, + ComputeManagementClient.class); + } + + /** + * Creates an instance of the ComputeManagementClient API using + * the specified configuration. + * + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the ComputeManagementClient API. + */ + public static ComputeManagementClient create(final String profile, + final Configuration config) { + return config.create(profile, ComputeManagementClient.class); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/DeploymentOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/DeploymentOperations.java new file mode 100644 index 0000000000000..96979bdc47234 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/DeploymentOperations.java @@ -0,0 +1,2645 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.DeploymentChangeConfigurationParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentCreateParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentDeleteRoleInstanceParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentGetPackageParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentGetResponse; +import com.microsoft.windowsazure.management.compute.models.DeploymentRollbackUpdateOrUpgradeParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentSlot; +import com.microsoft.windowsazure.management.compute.models.DeploymentSwapParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentUpdateStatusParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentUpgradeParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentWalkUpgradeDomainParameters; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the deployments +* in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for more +* information) +*/ +public interface DeploymentOperations { + /** + * The Begin Changing Deployment Configuration By Name operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginChangingConfigurationByName(String serviceName, String deploymentName, DeploymentChangeConfigurationParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Changing Deployment Configuration By Name operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginChangingConfigurationByNameAsync(String serviceName, String deploymentName, DeploymentChangeConfigurationParameters parameters); + + /** + * The Begin Changing Deployment Configuration By Slot operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginChangingConfigurationBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Changing Deployment Configuration By Slot operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginChangingConfigurationBySlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters); + + /** + * The Begin Creating Deployment operation uploads a new service package and + * creates a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Begin Creating + * Deployment operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginCreating(String serviceName, DeploymentSlot deploymentSlot, DeploymentCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Creating Deployment operation uploads a new service package and + * creates a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Begin Creating + * Deployment operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginCreatingAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentCreateParameters parameters); + + /** + * The Begin Deleting Deployment By Name operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeletingByName(String serviceName, String deploymentName, boolean deleteFromStorage) throws IOException, ServiceException; + + /** + * The Begin Deleting Deployment By Name operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingByNameAsync(String serviceName, String deploymentName, boolean deleteFromStorage); + + /** + * The Begin Deleting Deployment By Slot operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeletingBySlot(String serviceName, DeploymentSlot deploymentSlot) throws IOException, ServiceException; + + /** + * The Begin Deleting Deployment By Slot operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingBySlotAsync(String serviceName, DeploymentSlot deploymentSlot); + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeletingRoleInstanceByBeploymentSlot(String serviceName, String deploymentSlot, DeploymentDeleteRoleInstanceParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingRoleInstanceByBeploymentSlotAsync(String serviceName, String deploymentSlot, DeploymentDeleteRoleInstanceParameters parameters); + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param parameters Required. The parameters to delete the role. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeletingRoleInstanceByDeploymentName(String serviceName, String deploymentName, DeploymentDeleteRoleInstanceParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param parameters Required. The parameters to delete the role. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingRoleInstanceByDeploymentNameAsync(String serviceName, String deploymentName, DeploymentDeleteRoleInstanceParameters parameters); + + /** + * The Begin Rebooting Role Instance By Deployment Name operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginRebootingRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws IOException, ServiceException; + + /** + * The Begin Rebooting Role Instance By Deployment Name operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginRebootingRoleInstanceByDeploymentNameAsync(String serviceName, String deploymentName, String roleInstanceName); + + /** + * The Begin Rebooting Role Instance By Deployment Slot operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginRebootingRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws IOException, ServiceException; + + /** + * The Begin Rebooting Role Instance By Deployment Slot operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginRebootingRoleInstanceByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName); + + /** + * The Begin Reimaging Role Instance By Deployment Name operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginReimagingRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws IOException, ServiceException; + + /** + * The Begin Reimaging Role Instance By Deployment Name operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginReimagingRoleInstanceByDeploymentNameAsync(String serviceName, String deploymentName, String roleInstanceName); + + /** + * The Begin Reimaging Role Instance By Deployment Slot operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginReimagingRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws IOException, ServiceException; + + /** + * The Begin Reimaging Role Instance By Deployment Slot operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginReimagingRoleInstanceByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName); + + /** + * The Begin Swapping Deployment operation initiates a virtual IP address + * swap between the staging and production deployment environments for a + * service. If the service is currently running in the staging environment, + * it will be swapped to the production environment. If it is running in + * the production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Begin Swapping + * Deployment operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginSwapping(String serviceName, DeploymentSwapParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Swapping Deployment operation initiates a virtual IP address + * swap between the staging and production deployment environments for a + * service. If the service is currently running in the staging environment, + * it will be swapped to the production environment. If it is running in + * the production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Begin Swapping + * Deployment operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginSwappingAsync(String serviceName, DeploymentSwapParameters parameters); + + /** + * The Begin Updating Deployment Status By Deployment Name operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginUpdatingStatusByDeploymentName(String serviceName, String deploymentName, DeploymentUpdateStatusParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Updating Deployment Status By Deployment Name operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginUpdatingStatusByDeploymentNameAsync(String serviceName, String deploymentName, DeploymentUpdateStatusParameters parameters); + + /** + * The Begin Updating Deployment Status By Deployment Slot operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginUpdatingStatusByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpdateStatusParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Updating Deployment Status By Deployment Slot operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginUpdatingStatusByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpdateStatusParameters parameters); + + /** + * The Begin Upgrading Deployment By Name operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginUpgradingByName(String serviceName, String deploymentName, DeploymentUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Upgrading Deployment By Name operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginUpgradingByNameAsync(String serviceName, String deploymentName, DeploymentUpgradeParameters parameters); + + /** + * The Begin Upgrading Deployment By Slot operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx.This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginUpgradingBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Upgrading Deployment By Slot operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx.This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginUpgradingBySlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpgradeParameters parameters); + + /** + * The Begin Walking Upgrade Domain By Deployment Name operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginWalkingUpgradeDomainByDeploymentName(String serviceName, String deploymentName, DeploymentWalkUpgradeDomainParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Walking Upgrade Domain By Deployment Name operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginWalkingUpgradeDomainByDeploymentNameAsync(String serviceName, String deploymentName, DeploymentWalkUpgradeDomainParameters parameters); + + /** + * The Begin Walking Upgrade Domain By Deployment Slot operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginWalkingUpgradeDomainByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentWalkUpgradeDomainParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Walking Upgrade Domain By Deployment Slot operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginWalkingUpgradeDomainByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentWalkUpgradeDomainParameters parameters); + + /** + * The Change Deployment Configuration By Name operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Change + * ConfigurationDeployment By Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse changeConfigurationByName(String serviceName, String deploymentName, DeploymentChangeConfigurationParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Change Deployment Configuration By Name operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Change + * ConfigurationDeployment By Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future changeConfigurationByNameAsync(String serviceName, String deploymentName, DeploymentChangeConfigurationParameters parameters); + + /** + * The Change Deployment Configuration By Slot operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Change + * Configuration Deployment By Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse changeConfigurationBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Change Deployment Configuration By Slot operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Change + * Configuration Deployment By Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future changeConfigurationBySlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters); + + /** + * The Create Deployment operation uploads a new service package and creates + * a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Create Deployment + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse create(String serviceName, DeploymentSlot deploymentSlot, DeploymentCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException; + + /** + * The Create Deployment operation uploads a new service package and creates + * a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Create Deployment + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future createAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentCreateParameters parameters); + + /** + * The Delete Deployment By Name operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse deleteByName(String serviceName, String deploymentName, boolean deleteFromStorage) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Delete Deployment By Name operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteByNameAsync(String serviceName, String deploymentName, boolean deleteFromStorage); + + /** + * The Delete Deployment By Slot operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse deleteBySlot(String serviceName, DeploymentSlot deploymentSlot) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Delete Deployment By Slot operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteBySlotAsync(String serviceName, DeploymentSlot deploymentSlot); + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param roleInstanceName Required. The parameters to delete the role. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse deleteRoleInstanceByDeploymentName(String serviceName, String deploymentName, DeploymentDeleteRoleInstanceParameters roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param roleInstanceName Required. The parameters to delete the role. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteRoleInstanceByDeploymentNameAsync(String serviceName, String deploymentName, DeploymentDeleteRoleInstanceParameters roleInstanceName); + + /** + * The Delete Role Instances operation deletes the role instances from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse deleteRoleInstanceByDeploymentSlot(String serviceName, String deploymentSlot, DeploymentDeleteRoleInstanceParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Delete Role Instances operation deletes the role instances from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteRoleInstanceByDeploymentSlotAsync(String serviceName, String deploymentSlot, DeploymentDeleteRoleInstanceParameters parameters); + + /** + * The Get Deployment By Name operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A deployment that exists in the cloud service. + */ + DeploymentGetResponse getByName(String serviceName, String deploymentName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Deployment By Name operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @return A deployment that exists in the cloud service. + */ + Future getByNameAsync(String serviceName, String deploymentName); + + /** + * The Get Deployment By Slot operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A deployment that exists in the cloud service. + */ + DeploymentGetResponse getBySlot(String serviceName, DeploymentSlot deploymentSlot) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Deployment By Slot operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @return A deployment that exists in the cloud service. + */ + Future getBySlotAsync(String serviceName, DeploymentSlot deploymentSlot); + + /** + * The Get Package By Name operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Get Package By + * Name operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse getPackageByName(String serviceName, String deploymentName, DeploymentGetPackageParameters parameters) throws IOException, ServiceException; + + /** + * The Get Package By Name operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Get Package By + * Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future getPackageByNameAsync(String serviceName, String deploymentName, DeploymentGetPackageParameters parameters); + + /** + * The Get Package By Slot operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Get Package By + * Slot operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse getPackageBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentGetPackageParameters parameters) throws IOException, ServiceException; + + /** + * The Get Package By Slot operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Get Package By + * Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future getPackageBySlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentGetPackageParameters parameters); + + /** + * The Reboot Role Instance By Deployment Name operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse rebootRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Reboot Role Instance By Deployment Name operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future rebootRoleInstanceByDeploymentNameAsync(String serviceName, String deploymentName, String roleInstanceName); + + /** + * The Reboot Role Instance By Deployment Slot operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse rebootRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Reboot Role Instance By Deployment Slot operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future rebootRoleInstanceByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName); + + /** + * The Reimage Role Instance By Deployment Name operation requests a reimage + * of a role instance that is running in a deployment.This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse reimageRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Reimage Role Instance By Deployment Name operation requests a reimage + * of a role instance that is running in a deployment.This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future reimageRoleInstanceByDeploymentNameAsync(String serviceName, String deploymentName, String roleInstanceName); + + /** + * The Reimage Role Instance By Deployment Slot operation requests a reimage + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse reimageRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Reimage Role Instance By Deployment Slot operation requests a reimage + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future reimageRoleInstanceByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName); + + /** + * The Rollback Update Or Upgrade By Deployment Name operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse rollbackUpdateOrUpgradeByDeploymentName(String serviceName, String deploymentName, DeploymentRollbackUpdateOrUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Rollback Update Or Upgrade By Deployment Name operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future rollbackUpdateOrUpgradeByDeploymentNameAsync(String serviceName, String deploymentName, DeploymentRollbackUpdateOrUpgradeParameters parameters); + + /** + * The Rollback Update Or Upgrade By Deployment Slot operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse rollbackUpdateOrUpgradeByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentRollbackUpdateOrUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Rollback Update Or Upgrade By Deployment Slot operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future rollbackUpdateOrUpgradeByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentRollbackUpdateOrUpgradeParameters parameters); + + /** + * The Swap Deployment operation initiates a virtual IP address swap between + * the staging and production deployment environments for a service. If the + * service is currently running in the staging environment, it will be + * swapped to the production environment. If it is running in the + * production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Swap Deployment + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse swap(String serviceName, DeploymentSwapParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Swap Deployment operation initiates a virtual IP address swap between + * the staging and production deployment environments for a service. If the + * service is currently running in the staging environment, it will be + * swapped to the production environment. If it is running in the + * production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Swap Deployment + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future swapAsync(String serviceName, DeploymentSwapParameters parameters); + + /** + * The Update Deployment Status By Deployment Name operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse updateStatusByDeploymentName(String serviceName, String deploymentName, DeploymentUpdateStatusParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Update Deployment Status By Deployment Name operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future updateStatusByDeploymentNameAsync(String serviceName, String deploymentName, DeploymentUpdateStatusParameters parameters); + + /** + * The Update Deployment Status By Deployment Slot operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse updateStatusByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpdateStatusParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Update Deployment Status By Deployment Slot operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future updateStatusByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpdateStatusParameters parameters); + + /** + * The Upgrade Deployment By Name operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse upgradeByName(String serviceName, String deploymentName, DeploymentUpgradeParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Upgrade Deployment By Name operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future upgradeByNameAsync(String serviceName, String deploymentName, DeploymentUpgradeParameters parameters); + + /** + * The Upgrade Deployment By Slot operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse upgradeBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpgradeParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Upgrade Deployment By Slot operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future upgradeBySlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpgradeParameters parameters); + + /** + * The Walk Upgrade Domain By Deployment Name operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse walkUpgradeDomainByDeploymentName(String serviceName, String deploymentName, DeploymentWalkUpgradeDomainParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Walk Upgrade Domain By Deployment Name operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future walkUpgradeDomainByDeploymentNameAsync(String serviceName, String deploymentName, DeploymentWalkUpgradeDomainParameters parameters); + + /** + * The Walk Upgrade Domain By Deployment Slot operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse walkUpgradeDomainByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentWalkUpgradeDomainParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Walk Upgrade Domain By Deployment Slot operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future walkUpgradeDomainByDeploymentSlotAsync(String serviceName, DeploymentSlot deploymentSlot, DeploymentWalkUpgradeDomainParameters parameters); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/DeploymentOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/DeploymentOperationsImpl.java new file mode 100644 index 0000000000000..8b1918f99f15e --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/DeploymentOperationsImpl.java @@ -0,0 +1,9727 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.AccessControlListRule; +import com.microsoft.windowsazure.management.compute.models.ConfigurationSet; +import com.microsoft.windowsazure.management.compute.models.DataVirtualHardDisk; +import com.microsoft.windowsazure.management.compute.models.DeploymentChangeConfigurationParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentCreateParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentDeleteRoleInstanceParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentGetPackageParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentGetResponse; +import com.microsoft.windowsazure.management.compute.models.DeploymentRollbackUpdateOrUpgradeParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentSlot; +import com.microsoft.windowsazure.management.compute.models.DeploymentStatus; +import com.microsoft.windowsazure.management.compute.models.DeploymentSwapParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentUpdateStatusParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentUpgradeParameters; +import com.microsoft.windowsazure.management.compute.models.DeploymentUpgradeType; +import com.microsoft.windowsazure.management.compute.models.DeploymentWalkUpgradeDomainParameters; +import com.microsoft.windowsazure.management.compute.models.DnsServer; +import com.microsoft.windowsazure.management.compute.models.DnsSettings; +import com.microsoft.windowsazure.management.compute.models.DomainJoinCredentials; +import com.microsoft.windowsazure.management.compute.models.DomainJoinProvisioning; +import com.microsoft.windowsazure.management.compute.models.DomainJoinSettings; +import com.microsoft.windowsazure.management.compute.models.EndpointAcl; +import com.microsoft.windowsazure.management.compute.models.ExtensionConfiguration; +import com.microsoft.windowsazure.management.compute.models.GuestAgentFormattedMessage; +import com.microsoft.windowsazure.management.compute.models.GuestAgentMessage; +import com.microsoft.windowsazure.management.compute.models.GuestAgentStatus; +import com.microsoft.windowsazure.management.compute.models.InputEndpoint; +import com.microsoft.windowsazure.management.compute.models.InstanceEndpoint; +import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbe; +import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbeTransportProtocol; +import com.microsoft.windowsazure.management.compute.models.OSVirtualHardDisk; +import com.microsoft.windowsazure.management.compute.models.PersistentVMDowntime; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionConfigurationStatus; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionParameterValue; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionReference; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionStatus; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionSubStatus; +import com.microsoft.windowsazure.management.compute.models.Role; +import com.microsoft.windowsazure.management.compute.models.RoleInstance; +import com.microsoft.windowsazure.management.compute.models.RoleInstancePowerState; +import com.microsoft.windowsazure.management.compute.models.SshSettingKeyPair; +import com.microsoft.windowsazure.management.compute.models.SshSettingPublicKey; +import com.microsoft.windowsazure.management.compute.models.SshSettings; +import com.microsoft.windowsazure.management.compute.models.StoredCertificateSettings; +import com.microsoft.windowsazure.management.compute.models.UpgradeDomainState; +import com.microsoft.windowsazure.management.compute.models.UpgradeStatus; +import com.microsoft.windowsazure.management.compute.models.VirtualHardDiskHostCaching; +import com.microsoft.windowsazure.management.compute.models.VirtualIPAddress; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineWindowsRemoteManagementListenerType; +import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementListener; +import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementSettings; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the deployments +* in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for more +* information) +*/ +public class DeploymentOperationsImpl implements ServiceOperations, DeploymentOperations { + /** + * Initializes a new instance of the DeploymentOperationsImpl class. + * + * @param client Reference to the service client. + */ + DeploymentOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The Begin Changing Deployment Configuration By Name operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginChangingConfigurationByNameAsync(final String serviceName, final String deploymentName, final DeploymentChangeConfigurationParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginChangingConfigurationByName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Changing Deployment Configuration By Name operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginChangingConfigurationByName(String serviceName, String deploymentName, DeploymentChangeConfigurationParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfiguration() == null) { + throw new NullPointerException("parameters.Configuration"); + } + if (parameters.getExtensionConfiguration() != null) { + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration().getAllRoles()) { + if (allRolesParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id"); + } + } + } + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters.getExtensionConfiguration().getNamedRoles()) { + if (namedRolesParameterItem.getExtensions() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions"); + } + if (namedRolesParameterItem.getExtensions() != null) { + for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem.getExtensions()) { + if (extensionsParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions.Id"); + } + } + } + if (namedRolesParameterItem.getRoleName() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName"); + } + } + } + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginChangingConfigurationByNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/" + "?" + "comp=config"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element changeConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ChangeConfiguration"); + requestDoc.appendChild(changeConfigurationElement); + + Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Configuration"); + configurationElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes()))); + changeConfigurationElement.appendChild(configurationElement); + + if (parameters.isTreatWarningsAsError() != null) { + Element treatWarningsAsErrorElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TreatWarningsAsError"); + treatWarningsAsErrorElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isTreatWarningsAsError()).toLowerCase())); + changeConfigurationElement.appendChild(treatWarningsAsErrorElement); + } + + if (parameters.getMode() != null) { + Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode"); + modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString())); + changeConfigurationElement.appendChild(modeElement); + } + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + changeConfigurationElement.appendChild(extendedPropertiesDictionaryElement); + } + + if (parameters.getExtensionConfiguration() != null) { + Element extensionConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration"); + changeConfigurationElement.appendChild(extensionConfigurationElement); + + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + Element allRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles"); + for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration().getAllRoles()) { + Element extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + allRolesSequenceElement.appendChild(extensionElement); + + Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId())); + extensionElement.appendChild(idElement); + } + extensionConfigurationElement.appendChild(allRolesSequenceElement); + } + + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + Element namedRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles"); + for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration().getNamedRoles()) { + Element roleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Role"); + namedRolesSequenceElement.appendChild(roleElement); + + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName())); + roleElement.appendChild(roleNameElement); + + Element extensionsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions"); + for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) { + Element extensionElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + extensionsSequenceElement.appendChild(extensionElement2); + + Element idElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId())); + extensionElement2.appendChild(idElement2); + } + roleElement.appendChild(extensionsSequenceElement); + } + extensionConfigurationElement.appendChild(namedRolesSequenceElement); + } + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Changing Deployment Configuration By Slot operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginChangingConfigurationBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentChangeConfigurationParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginChangingConfigurationBySlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Begin Changing Deployment Configuration By Slot operation initiates a + * change to the deployment configuration. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Begin Changing + * Configuration Deployment By Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginChangingConfigurationBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfiguration() == null) { + throw new NullPointerException("parameters.Configuration"); + } + if (parameters.getExtensionConfiguration() != null) { + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration().getAllRoles()) { + if (allRolesParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id"); + } + } + } + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters.getExtensionConfiguration().getNamedRoles()) { + if (namedRolesParameterItem.getExtensions() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions"); + } + if (namedRolesParameterItem.getExtensions() != null) { + for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem.getExtensions()) { + if (extensionsParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions.Id"); + } + } + } + if (namedRolesParameterItem.getRoleName() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName"); + } + } + } + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginChangingConfigurationBySlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/" + "?" + "comp=config"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element changeConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ChangeConfiguration"); + requestDoc.appendChild(changeConfigurationElement); + + Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Configuration"); + configurationElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes()))); + changeConfigurationElement.appendChild(configurationElement); + + if (parameters.isTreatWarningsAsError() != null) { + Element treatWarningsAsErrorElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TreatWarningsAsError"); + treatWarningsAsErrorElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isTreatWarningsAsError()).toLowerCase())); + changeConfigurationElement.appendChild(treatWarningsAsErrorElement); + } + + if (parameters.getMode() != null) { + Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode"); + modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString())); + changeConfigurationElement.appendChild(modeElement); + } + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + changeConfigurationElement.appendChild(extendedPropertiesDictionaryElement); + } + + if (parameters.getExtensionConfiguration() != null) { + Element extensionConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration"); + changeConfigurationElement.appendChild(extensionConfigurationElement); + + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + Element allRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles"); + for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration().getAllRoles()) { + Element extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + allRolesSequenceElement.appendChild(extensionElement); + + Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId())); + extensionElement.appendChild(idElement); + } + extensionConfigurationElement.appendChild(allRolesSequenceElement); + } + + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + Element namedRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles"); + for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration().getNamedRoles()) { + Element roleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Role"); + namedRolesSequenceElement.appendChild(roleElement); + + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName())); + roleElement.appendChild(roleNameElement); + + Element extensionsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions"); + for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) { + Element extensionElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + extensionsSequenceElement.appendChild(extensionElement2); + + Element idElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId())); + extensionElement2.appendChild(idElement2); + } + roleElement.appendChild(extensionsSequenceElement); + } + extensionConfigurationElement.appendChild(namedRolesSequenceElement); + } + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Creating Deployment operation uploads a new service package and + * creates a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Begin Creating + * Deployment operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCreatingAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginCreating(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Begin Creating Deployment operation uploads a new service package and + * creates a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Begin Creating + * Deployment operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginCreating(String serviceName, DeploymentSlot deploymentSlot, DeploymentCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfiguration() == null) { + throw new NullPointerException("parameters.Configuration"); + } + if (parameters.getExtensionConfiguration() != null) { + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration().getAllRoles()) { + if (allRolesParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id"); + } + } + } + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters.getExtensionConfiguration().getNamedRoles()) { + if (namedRolesParameterItem.getExtensions() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions"); + } + if (namedRolesParameterItem.getExtensions() != null) { + for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem.getExtensions()) { + if (extensionsParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions.Id"); + } + } + } + if (namedRolesParameterItem.getRoleName() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName"); + } + } + } + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getLabel().length() > 100) { + throw new IllegalArgumentException("parameters.Label"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + if (parameters.getPackageUri() == null) { + throw new NullPointerException("parameters.PackageUri"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element createDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CreateDeployment"); + requestDoc.appendChild(createDeploymentElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + createDeploymentElement.appendChild(nameElement); + + Element packageUrlElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PackageUrl"); + packageUrlElement.appendChild(requestDoc.createTextNode(parameters.getPackageUri().toString())); + createDeploymentElement.appendChild(packageUrlElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + createDeploymentElement.appendChild(labelElement); + + Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Configuration"); + configurationElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes()))); + createDeploymentElement.appendChild(configurationElement); + + if (parameters.isStartDeployment() != null) { + Element startDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StartDeployment"); + startDeploymentElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isStartDeployment()).toLowerCase())); + createDeploymentElement.appendChild(startDeploymentElement); + } + + if (parameters.isTreatWarningsAsError() != null) { + Element treatWarningsAsErrorElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TreatWarningsAsError"); + treatWarningsAsErrorElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isTreatWarningsAsError()).toLowerCase())); + createDeploymentElement.appendChild(treatWarningsAsErrorElement); + } + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + createDeploymentElement.appendChild(extendedPropertiesDictionaryElement); + } + + if (parameters.getExtensionConfiguration() != null) { + Element extensionConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration"); + createDeploymentElement.appendChild(extensionConfigurationElement); + + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + Element allRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles"); + for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration().getAllRoles()) { + Element extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + allRolesSequenceElement.appendChild(extensionElement); + + Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId())); + extensionElement.appendChild(idElement); + } + extensionConfigurationElement.appendChild(allRolesSequenceElement); + } + + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + Element namedRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles"); + for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration().getNamedRoles()) { + Element roleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Role"); + namedRolesSequenceElement.appendChild(roleElement); + + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName())); + roleElement.appendChild(roleNameElement); + + Element extensionsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions"); + for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) { + Element extensionElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + extensionsSequenceElement.appendChild(extensionElement2); + + Element idElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId())); + extensionElement2.appendChild(idElement2); + } + roleElement.appendChild(extensionsSequenceElement); + } + extensionConfigurationElement.appendChild(namedRolesSequenceElement); + } + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Deleting Deployment By Name operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingByNameAsync(final String serviceName, final String deploymentName, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeletingByName(serviceName, deploymentName, deleteFromStorage); + } + }); + } + + /** + * The Begin Deleting Deployment By Name operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeletingByName(String serviceName, String deploymentName, boolean deleteFromStorage) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "beginDeletingByNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "?"; + if (deleteFromStorage == true) { + url = url + "comp=" + "media"; + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Deleting Deployment By Slot operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeletingBySlot(serviceName, deploymentSlot); + } + }); + } + + /** + * The Begin Deleting Deployment By Slot operation deletes the specified + * deployment. This operation is an asynchronous operation. To determine + * whether the Management service has finished processing the request, call + * Get Operation Status. For more information on asynchronous operations, + * see Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeletingBySlot(String serviceName, DeploymentSlot deploymentSlot) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + CloudTracing.enter(invocationId, this, "beginDeletingBySlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingRoleInstanceByBeploymentSlotAsync(final String serviceName, final String deploymentSlot, final DeploymentDeleteRoleInstanceParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeletingRoleInstanceByBeploymentSlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeletingRoleInstanceByBeploymentSlot(String serviceName, String deploymentSlot, DeploymentDeleteRoleInstanceParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentSlot == null) { + throw new NullPointerException("deploymentSlot"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginDeletingRoleInstanceByBeploymentSlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot.trim() + "/roleinstances/" + "?" + "comp=delete"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element deploymentDeleteRoleInstanceParametersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DeploymentDeleteRoleInstanceParameters"); + requestDoc.appendChild(deploymentDeleteRoleInstanceParametersElement); + + if (parameters.getName() != null) { + Element roleInstancesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleInstances"); + for (String roleInstancesItem : parameters.getName()) { + Element roleInstancesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + roleInstancesItemElement.appendChild(requestDoc.createTextNode(roleInstancesItem)); + roleInstancesSequenceElement.appendChild(roleInstancesItemElement); + } + deploymentDeleteRoleInstanceParametersElement.appendChild(roleInstancesSequenceElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param parameters Required. The parameters to delete the role. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingRoleInstanceByDeploymentNameAsync(final String serviceName, final String deploymentName, final DeploymentDeleteRoleInstanceParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeletingRoleInstanceByDeploymentName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param parameters Required. The parameters to delete the role. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeletingRoleInstanceByDeploymentName(String serviceName, String deploymentName, DeploymentDeleteRoleInstanceParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginDeletingRoleInstanceByDeploymentNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + "?" + "comp=delete"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element deploymentDeleteRoleInstanceParametersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DeploymentDeleteRoleInstanceParameters"); + requestDoc.appendChild(deploymentDeleteRoleInstanceParametersElement); + + if (parameters.getName() != null) { + Element roleInstancesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleInstances"); + for (String roleInstancesItem : parameters.getName()) { + Element roleInstancesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + roleInstancesItemElement.appendChild(requestDoc.createTextNode(roleInstancesItem)); + roleInstancesSequenceElement.appendChild(roleInstancesItemElement); + } + deploymentDeleteRoleInstanceParametersElement.appendChild(roleInstancesSequenceElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Rebooting Role Instance By Deployment Name operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginRebootingRoleInstanceByDeploymentNameAsync(final String serviceName, final String deploymentName, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginRebootingRoleInstanceByDeploymentName(serviceName, deploymentName, roleInstanceName); + } + }); + } + + /** + * The Begin Rebooting Role Instance By Deployment Name operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginRebootingRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (roleInstanceName == null) { + throw new NullPointerException("roleInstanceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "beginRebootingRoleInstanceByDeploymentNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + roleInstanceName.trim() + "?" + "comp=reboot"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Rebooting Role Instance By Deployment Slot operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginRebootingRoleInstanceByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginRebootingRoleInstanceByDeploymentSlot(serviceName, deploymentSlot, roleInstanceName); + } + }); + } + + /** + * The Begin Rebooting Role Instance By Deployment Slot operation requests a + * reboot of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginRebootingRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (roleInstanceName == null) { + throw new NullPointerException("roleInstanceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "beginRebootingRoleInstanceByDeploymentSlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/roleinstances/" + roleInstanceName.trim() + "?" + "comp=reboot"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Reimaging Role Instance By Deployment Name operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginReimagingRoleInstanceByDeploymentNameAsync(final String serviceName, final String deploymentName, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginReimagingRoleInstanceByDeploymentName(serviceName, deploymentName, roleInstanceName); + } + }); + } + + /** + * The Begin Reimaging Role Instance By Deployment Name operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginReimagingRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (roleInstanceName == null) { + throw new NullPointerException("roleInstanceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "beginReimagingRoleInstanceByDeploymentNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + roleInstanceName.trim() + "?" + "comp=reimage"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Reimaging Role Instance By Deployment Slot operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginReimagingRoleInstanceByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginReimagingRoleInstanceByDeploymentSlot(serviceName, deploymentSlot, roleInstanceName); + } + }); + } + + /** + * The Begin Reimaging Role Instance By Deployment Slot operation requests a + * reimage of a role instance that is running in a deployment. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginReimagingRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (roleInstanceName == null) { + throw new NullPointerException("roleInstanceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "beginReimagingRoleInstanceByDeploymentSlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/roleinstances/" + roleInstanceName.trim() + "?" + "comp=reimage"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Swapping Deployment operation initiates a virtual IP address + * swap between the staging and production deployment environments for a + * service. If the service is currently running in the staging environment, + * it will be swapped to the production environment. If it is running in + * the production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Begin Swapping + * Deployment operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginSwappingAsync(final String serviceName, final DeploymentSwapParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginSwapping(serviceName, parameters); + } + }); + } + + /** + * The Begin Swapping Deployment operation initiates a virtual IP address + * swap between the staging and production deployment environments for a + * service. If the service is currently running in the staging environment, + * it will be swapped to the production environment. If it is running in + * the production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Begin Swapping + * Deployment operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginSwapping(String serviceName, DeploymentSwapParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getSourceDeployment() == null) { + throw new NullPointerException("parameters.SourceDeployment"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginSwappingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element swapElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Swap"); + requestDoc.appendChild(swapElement); + + if (parameters.getProductionDeployment() != null) { + Element productionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Production"); + productionElement.appendChild(requestDoc.createTextNode(parameters.getProductionDeployment())); + swapElement.appendChild(productionElement); + } + + Element sourceDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDeployment"); + sourceDeploymentElement.appendChild(requestDoc.createTextNode(parameters.getSourceDeployment())); + swapElement.appendChild(sourceDeploymentElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Updating Deployment Status By Deployment Name operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginUpdatingStatusByDeploymentNameAsync(final String serviceName, final String deploymentName, final DeploymentUpdateStatusParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginUpdatingStatusByDeploymentName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Updating Deployment Status By Deployment Name operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginUpdatingStatusByDeploymentName(String serviceName, String deploymentName, DeploymentUpdateStatusParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginUpdatingStatusByDeploymentNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/" + "?" + "comp=status"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element updateDeploymentStatusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateDeploymentStatus"); + requestDoc.appendChild(updateDeploymentStatusElement); + + Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Status"); + statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString())); + updateDeploymentStatusElement.appendChild(statusElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Updating Deployment Status By Deployment Slot operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginUpdatingStatusByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentUpdateStatusParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginUpdatingStatusByDeploymentSlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Begin Updating Deployment Status By Deployment Slot operation + * initiates a change in the running status of a deployment. The status of + * a deployment can be running or suspended. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Updating + * Deployment Status By Deployment Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginUpdatingStatusByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpdateStatusParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginUpdatingStatusByDeploymentSlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/" + "?" + "comp=status"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element updateDeploymentStatusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateDeploymentStatus"); + requestDoc.appendChild(updateDeploymentStatusElement); + + Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Status"); + statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString())); + updateDeploymentStatusElement.appendChild(statusElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Upgrading Deployment By Name operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginUpgradingByNameAsync(final String serviceName, final String deploymentName, final DeploymentUpgradeParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginUpgradingByName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Upgrading Deployment By Name operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginUpgradingByName(String serviceName, String deploymentName, DeploymentUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfiguration() == null) { + throw new NullPointerException("parameters.Configuration"); + } + if (parameters.getExtensionConfiguration() != null) { + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration().getAllRoles()) { + if (allRolesParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id"); + } + } + } + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters.getExtensionConfiguration().getNamedRoles()) { + if (namedRolesParameterItem.getExtensions() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions"); + } + if (namedRolesParameterItem.getExtensions() != null) { + for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem.getExtensions()) { + if (extensionsParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions.Id"); + } + } + } + if (namedRolesParameterItem.getRoleName() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName"); + } + } + } + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getLabel().length() > 100) { + throw new IllegalArgumentException("parameters.Label"); + } + if (parameters.getPackageUri() == null) { + throw new NullPointerException("parameters.PackageUri"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginUpgradingByNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/" + "?" + "comp=upgrade"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element upgradeDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpgradeDeployment"); + requestDoc.appendChild(upgradeDeploymentElement); + + Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode"); + modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString())); + upgradeDeploymentElement.appendChild(modeElement); + + Element packageUrlElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PackageUrl"); + packageUrlElement.appendChild(requestDoc.createTextNode(parameters.getPackageUri().toString())); + upgradeDeploymentElement.appendChild(packageUrlElement); + + Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Configuration"); + configurationElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes()))); + upgradeDeploymentElement.appendChild(configurationElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + upgradeDeploymentElement.appendChild(labelElement); + + if (parameters.getRoleToUpgrade() != null) { + Element roleToUpgradeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleToUpgrade"); + roleToUpgradeElement.appendChild(requestDoc.createTextNode(parameters.getRoleToUpgrade())); + upgradeDeploymentElement.appendChild(roleToUpgradeElement); + } + + Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force"); + forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase())); + upgradeDeploymentElement.appendChild(forceElement); + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + upgradeDeploymentElement.appendChild(extendedPropertiesDictionaryElement); + } + + if (parameters.getExtensionConfiguration() != null) { + Element extensionConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration"); + upgradeDeploymentElement.appendChild(extensionConfigurationElement); + + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + Element allRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles"); + for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration().getAllRoles()) { + Element extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + allRolesSequenceElement.appendChild(extensionElement); + + Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId())); + extensionElement.appendChild(idElement); + } + extensionConfigurationElement.appendChild(allRolesSequenceElement); + } + + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + Element namedRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles"); + for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration().getNamedRoles()) { + Element roleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Role"); + namedRolesSequenceElement.appendChild(roleElement); + + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName())); + roleElement.appendChild(roleNameElement); + + Element extensionsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions"); + for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) { + Element extensionElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + extensionsSequenceElement.appendChild(extensionElement2); + + Element idElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId())); + extensionElement2.appendChild(idElement2); + } + roleElement.appendChild(extensionsSequenceElement); + } + extensionConfigurationElement.appendChild(namedRolesSequenceElement); + } + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Upgrading Deployment By Slot operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx.This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginUpgradingBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentUpgradeParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginUpgradingBySlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Begin Upgrading Deployment By Slot operation initiates an update of + * role instances in a deployment using the package and configuration that + * you specify. For more information about updating role instances, see + * Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx.This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Begin Upgrading + * Deployment By Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginUpgradingBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfiguration() == null) { + throw new NullPointerException("parameters.Configuration"); + } + if (parameters.getExtensionConfiguration() != null) { + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration().getAllRoles()) { + if (allRolesParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id"); + } + } + } + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters.getExtensionConfiguration().getNamedRoles()) { + if (namedRolesParameterItem.getExtensions() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions"); + } + if (namedRolesParameterItem.getExtensions() != null) { + for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem.getExtensions()) { + if (extensionsParameterItem.getId() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions.Id"); + } + } + } + if (namedRolesParameterItem.getRoleName() == null) { + throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName"); + } + } + } + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getLabel().length() > 100) { + throw new IllegalArgumentException("parameters.Label"); + } + if (parameters.getPackageUri() == null) { + throw new NullPointerException("parameters.PackageUri"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginUpgradingBySlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/" + "?" + "comp=upgrade"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element upgradeDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpgradeDeployment"); + requestDoc.appendChild(upgradeDeploymentElement); + + Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode"); + modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString())); + upgradeDeploymentElement.appendChild(modeElement); + + Element packageUrlElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PackageUrl"); + packageUrlElement.appendChild(requestDoc.createTextNode(parameters.getPackageUri().toString())); + upgradeDeploymentElement.appendChild(packageUrlElement); + + Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Configuration"); + configurationElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes()))); + upgradeDeploymentElement.appendChild(configurationElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + upgradeDeploymentElement.appendChild(labelElement); + + if (parameters.getRoleToUpgrade() != null) { + Element roleToUpgradeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleToUpgrade"); + roleToUpgradeElement.appendChild(requestDoc.createTextNode(parameters.getRoleToUpgrade())); + upgradeDeploymentElement.appendChild(roleToUpgradeElement); + } + + Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force"); + forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase())); + upgradeDeploymentElement.appendChild(forceElement); + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + upgradeDeploymentElement.appendChild(extendedPropertiesDictionaryElement); + } + + if (parameters.getExtensionConfiguration() != null) { + Element extensionConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration"); + upgradeDeploymentElement.appendChild(extensionConfigurationElement); + + if (parameters.getExtensionConfiguration().getAllRoles() != null) { + Element allRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles"); + for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration().getAllRoles()) { + Element extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + allRolesSequenceElement.appendChild(extensionElement); + + Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId())); + extensionElement.appendChild(idElement); + } + extensionConfigurationElement.appendChild(allRolesSequenceElement); + } + + if (parameters.getExtensionConfiguration().getNamedRoles() != null) { + Element namedRolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles"); + for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration().getNamedRoles()) { + Element roleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Role"); + namedRolesSequenceElement.appendChild(roleElement); + + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName())); + roleElement.appendChild(roleNameElement); + + Element extensionsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions"); + for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) { + Element extensionElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + extensionsSequenceElement.appendChild(extensionElement2); + + Element idElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId())); + extensionElement2.appendChild(idElement2); + } + roleElement.appendChild(extensionsSequenceElement); + } + extensionConfigurationElement.appendChild(namedRolesSequenceElement); + } + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Walking Upgrade Domain By Deployment Name operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginWalkingUpgradeDomainByDeploymentNameAsync(final String serviceName, final String deploymentName, final DeploymentWalkUpgradeDomainParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginWalkingUpgradeDomainByDeploymentName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Walking Upgrade Domain By Deployment Name operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginWalkingUpgradeDomainByDeploymentName(String serviceName, String deploymentName, DeploymentWalkUpgradeDomainParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginWalkingUpgradeDomainByDeploymentNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "?" + "comp=walkupgradedomain"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element walkUpgradeDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WalkUpgradeDomain"); + requestDoc.appendChild(walkUpgradeDomainElement); + + Element upgradeDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpgradeDomain"); + upgradeDomainElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getUpgradeDomain()))); + walkUpgradeDomainElement.appendChild(upgradeDomainElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Walking Upgrade Domain By Deployment Slot operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginWalkingUpgradeDomainByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentWalkUpgradeDomainParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginWalkingUpgradeDomainByDeploymentSlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Begin Walking Upgrade Domain By Deployment Slot operation specifies + * an update domain in which a role instance must be updated. For more + * information about updating role instances, see Update an Azure Service + * at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Begin Walking + * Upgrade Domain By Deployment Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginWalkingUpgradeDomainByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentWalkUpgradeDomainParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginWalkingUpgradeDomainByDeploymentSlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/" + "?" + "comp=walkupgradedomain"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element walkUpgradeDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WalkUpgradeDomain"); + requestDoc.appendChild(walkUpgradeDomainElement); + + Element upgradeDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpgradeDomain"); + upgradeDomainElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getUpgradeDomain()))); + walkUpgradeDomainElement.appendChild(upgradeDomainElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Change Deployment Configuration By Name operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Change + * ConfigurationDeployment By Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future changeConfigurationByNameAsync(final String serviceName, final String deploymentName, final DeploymentChangeConfigurationParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return changeConfigurationByName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Change Deployment Configuration By Name operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentName Required. The deployment to change configuration + * for. + * @param parameters Required. Parameters supplied to the Change + * ConfigurationDeployment By Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse changeConfigurationByName(String serviceName, String deploymentName, DeploymentChangeConfigurationParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "changeConfigurationByNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginChangingConfigurationByNameAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Change Deployment Configuration By Slot operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Change + * Configuration Deployment By Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future changeConfigurationBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentChangeConfigurationParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return changeConfigurationBySlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Change Deployment Configuration By Slot operation initiates a change + * to the deployment configuration. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx + * for more information) + * + * @param serviceName Required. The cloud service to change deployment + * configuration for. + * @param deploymentSlot Required. The slot to change deployment + * configuration for. + * @param parameters Required. Parameters supplied to the Change + * Configuration Deployment By Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse changeConfigurationBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentChangeConfigurationParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "changeConfigurationBySlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginChangingConfigurationBySlotAsync(serviceName, deploymentSlot, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Create Deployment operation uploads a new service package and creates + * a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Create Deployment + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future createAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return create(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Create Deployment operation uploads a new service package and creates + * a new deployment in the staging or production environments. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx + * for more information) + * + * @param serviceName Required. The cloud service to create a deployment for. + * @param deploymentSlot Required. The slot to create a deployment for. + * @param parameters Required. Parameters supplied to the Create Deployment + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse create(String serviceName, DeploymentSlot deploymentSlot, DeploymentCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginCreatingAsync(serviceName, deploymentSlot, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Deployment By Name operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteByNameAsync(final String serviceName, final String deploymentName, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return deleteByName(serviceName, deploymentName, deleteFromStorage); + } + }); + } + + /** + * The Delete Deployment By Name operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse deleteByName(String serviceName, String deploymentName, boolean deleteFromStorage) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "deleteByNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginDeletingByNameAsync(serviceName, deploymentName, deleteFromStorage).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Deployment By Slot operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return deleteBySlot(serviceName, deploymentSlot); + } + }); + } + + /** + * The Delete Deployment By Slot operation deletes the specified deployment. + * This operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse deleteBySlot(String serviceName, DeploymentSlot deploymentSlot) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + CloudTracing.enter(invocationId, this, "deleteBySlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginDeletingBySlotAsync(serviceName, deploymentSlot).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param roleInstanceName Required. The parameters to delete the role. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteRoleInstanceByDeploymentNameAsync(final String serviceName, final String deploymentName, final DeploymentDeleteRoleInstanceParameters roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return deleteRoleInstanceByDeploymentName(serviceName, deploymentName, roleInstanceName); + } + }); + } + + /** + * The Delete Role Instances operation deletes a role instance from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @param roleInstanceName Required. The parameters to delete the role. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse deleteRoleInstanceByDeploymentName(String serviceName, String deploymentName, DeploymentDeleteRoleInstanceParameters roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "deleteRoleInstanceByDeploymentNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginDeletingRoleInstanceByDeploymentNameAsync(serviceName, deploymentName, roleInstanceName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Role Instances operation deletes the role instances from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteRoleInstanceByDeploymentSlotAsync(final String serviceName, final String deploymentSlot, final DeploymentDeleteRoleInstanceParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return deleteRoleInstanceByDeploymentSlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Delete Role Instances operation deletes the role instances from a + * deployment in a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469418.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The name of the deployment slot. + * @param parameters Required. The parameters to delete the role. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse deleteRoleInstanceByDeploymentSlot(String serviceName, String deploymentSlot, DeploymentDeleteRoleInstanceParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "deleteRoleInstanceByDeploymentSlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationStatusResponse response = client2.getDeploymentsOperations().deleteRoleInstanceByDeploymentSlotAsync(serviceName, deploymentSlot, parameters).get(); + if (response.getStatus() == OperationStatus.Succeeded) { + return response; + } + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Get Deployment By Name operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @return A deployment that exists in the cloud service. + */ + @Override + public Future getByNameAsync(final String serviceName, final String deploymentName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DeploymentGetResponse call() throws Exception { + return getByName(serviceName, deploymentName); + } + }); + } + + /** + * The Get Deployment By Name operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of the deployment. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A deployment that exists in the cloud service. + */ + @Override + public DeploymentGetResponse getByName(String serviceName, String deploymentName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + CloudTracing.enter(invocationId, this, "getByNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DeploymentGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DeploymentGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element deploymentElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Deployment"); + if (deploymentElement != null) { + Element nameElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element deploymentSlotElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "DeploymentSlot"); + if (deploymentSlotElement != null) { + DeploymentSlot deploymentSlotInstance; + deploymentSlotInstance = DeploymentSlot.valueOf(deploymentSlotElement.getTextContent()); + result.setDeploymentSlot(deploymentSlotInstance); + } + + Element privateIDElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "PrivateID"); + if (privateIDElement != null) { + String privateIDInstance; + privateIDInstance = privateIDElement.getTextContent(); + result.setPrivateId(privateIDInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + DeploymentStatus statusInstance; + statusInstance = DeploymentStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + result.setLabel(labelInstance); + } + + Element urlElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + result.setUri(urlInstance); + } + + Element configurationElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Configuration"); + if (configurationElement != null) { + String configurationInstance; + configurationInstance = configurationElement.getTextContent() != null ? new String(Base64.decode(configurationElement.getTextContent())) : null; + result.setConfiguration(configurationInstance); + } + + Element roleInstanceListSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "RoleInstanceList"); + if (roleInstanceListSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleInstanceListSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleInstance").size(); i1 = i1 + 1) { + org.w3c.dom.Element roleInstanceListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleInstanceListSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleInstance").get(i1)); + RoleInstance roleInstanceInstance = new RoleInstance(); + result.getRoleInstances().add(roleInstanceInstance); + + Element roleNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + roleInstanceInstance.setRoleName(roleNameInstance); + } + + Element instanceNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceName"); + if (instanceNameElement != null) { + String instanceNameInstance; + instanceNameInstance = instanceNameElement.getTextContent(); + roleInstanceInstance.setInstanceName(instanceNameInstance); + } + + Element instanceStatusElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceStatus"); + if (instanceStatusElement != null) { + String instanceStatusInstance; + instanceStatusInstance = instanceStatusElement.getTextContent(); + roleInstanceInstance.setInstanceStatus(instanceStatusInstance); + } + + Element instanceUpgradeDomainElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceUpgradeDomain"); + if (instanceUpgradeDomainElement != null && (instanceUpgradeDomainElement.getTextContent() == null || instanceUpgradeDomainElement.getTextContent().isEmpty() == true) == false) { + int instanceUpgradeDomainInstance; + instanceUpgradeDomainInstance = DatatypeConverter.parseInt(instanceUpgradeDomainElement.getTextContent()); + roleInstanceInstance.setInstanceUpgradeDomain(instanceUpgradeDomainInstance); + } + + Element instanceFaultDomainElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceFaultDomain"); + if (instanceFaultDomainElement != null && (instanceFaultDomainElement.getTextContent() == null || instanceFaultDomainElement.getTextContent().isEmpty() == true) == false) { + int instanceFaultDomainInstance; + instanceFaultDomainInstance = DatatypeConverter.parseInt(instanceFaultDomainElement.getTextContent()); + roleInstanceInstance.setInstanceFaultDomain(instanceFaultDomainInstance); + } + + Element instanceSizeElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceSize"); + if (instanceSizeElement != null) { + String instanceSizeInstance; + instanceSizeInstance = instanceSizeElement.getTextContent(); + roleInstanceInstance.setInstanceSize(instanceSizeInstance); + } + + Element instanceStateDetailsElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceStateDetails"); + if (instanceStateDetailsElement != null) { + String instanceStateDetailsInstance; + instanceStateDetailsInstance = instanceStateDetailsElement.getTextContent(); + roleInstanceInstance.setInstanceStateDetails(instanceStateDetailsInstance); + } + + Element instanceErrorCodeElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceErrorCode"); + if (instanceErrorCodeElement != null) { + String instanceErrorCodeInstance; + instanceErrorCodeInstance = instanceErrorCodeElement.getTextContent(); + roleInstanceInstance.setInstanceErrorCode(instanceErrorCodeInstance); + } + + Element ipAddressElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "IpAddress"); + if (ipAddressElement != null) { + InetAddress ipAddressInstance; + ipAddressInstance = InetAddress.getByName(ipAddressElement.getTextContent()); + roleInstanceInstance.setIPAddress(ipAddressInstance); + } + + Element instanceEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoints"); + if (instanceEndpointsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(instanceEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoint").size(); i2 = i2 + 1) { + org.w3c.dom.Element instanceEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(instanceEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoint").get(i2)); + InstanceEndpoint instanceEndpointInstance = new InstanceEndpoint(); + roleInstanceInstance.getInstanceEndpoints().add(instanceEndpointInstance); + + Element localPortElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LocalPort"); + if (localPortElement != null && (localPortElement.getTextContent() == null || localPortElement.getTextContent().isEmpty() == true) == false) { + int localPortInstance; + localPortInstance = DatatypeConverter.parseInt(localPortElement.getTextContent()); + instanceEndpointInstance.setLocalPort(localPortInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + instanceEndpointInstance.setName(nameInstance2); + } + + Element publicPortElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "PublicPort"); + if (publicPortElement != null) { + int publicPortInstance; + publicPortInstance = DatatypeConverter.parseInt(publicPortElement.getTextContent()); + instanceEndpointInstance.setPort(publicPortInstance); + } + + Element protocolElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement != null) { + String protocolInstance; + protocolInstance = protocolElement.getTextContent(); + instanceEndpointInstance.setProtocol(protocolInstance); + } + + Element vipElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Vip"); + if (vipElement != null) { + InetAddress vipInstance; + vipInstance = InetAddress.getByName(vipElement.getTextContent()); + instanceEndpointInstance.setVirtualIPAddress(vipInstance); + } + } + } + + Element guestAgentStatusElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "GuestAgentStatus"); + if (guestAgentStatusElement != null) { + GuestAgentStatus guestAgentStatusInstance = new GuestAgentStatus(); + roleInstanceInstance.setGuestAgentStatus(guestAgentStatusInstance); + + Element protocolVersionElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "ProtocolVersion"); + if (protocolVersionElement != null) { + String protocolVersionInstance; + protocolVersionInstance = protocolVersionElement.getTextContent(); + guestAgentStatusInstance.setProtocolVersion(protocolVersionInstance); + } + + Element timestampElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement != null && (timestampElement.getTextContent() == null || timestampElement.getTextContent().isEmpty() == true) == false) { + Calendar timestampInstance; + timestampInstance = DatatypeConverter.parseDateTime(timestampElement.getTextContent()); + guestAgentStatusInstance.setTimestamp(timestampInstance); + } + + Element guestAgentVersionElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "GuestAgentVersion"); + if (guestAgentVersionElement != null) { + String guestAgentVersionInstance; + guestAgentVersionInstance = guestAgentVersionElement.getTextContent(); + guestAgentStatusInstance.setGuestAgentVersion(guestAgentVersionInstance); + } + + Element statusElement2 = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement2 != null) { + String statusInstance2; + statusInstance2 = statusElement2.getTextContent(); + guestAgentStatusInstance.setStatus(statusInstance2); + } + + Element codeElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null && (codeElement.getTextContent() == null || codeElement.getTextContent().isEmpty() == true) == false) { + int codeInstance; + codeInstance = DatatypeConverter.parseInt(codeElement.getTextContent()); + guestAgentStatusInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + GuestAgentMessage messageInstance = new GuestAgentMessage(); + guestAgentStatusInstance.setMessage(messageInstance); + + Element messageResourceIdElement = XmlUtility.getElementByTagNameNS(messageElement, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement != null) { + String messageResourceIdInstance; + messageResourceIdInstance = messageResourceIdElement.getTextContent(); + messageInstance.setMessageResourceId(messageResourceIdInstance); + } + + Element paramListSequenceElement = XmlUtility.getElementByTagNameNS(messageElement, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Param").size(); i3 = i3 + 1) { + org.w3c.dom.Element paramListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Param").get(i3)); + messageInstance.getParamList().add(paramListElement.getTextContent()); + } + } + } + + Element formattedMessageElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement != null) { + GuestAgentFormattedMessage formattedMessageInstance = new GuestAgentFormattedMessage(); + guestAgentStatusInstance.setFormattedMessage(formattedMessageInstance); + + Element languageElement = XmlUtility.getElementByTagNameNS(formattedMessageElement, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement != null) { + String languageInstance; + languageInstance = languageElement.getTextContent(); + formattedMessageInstance.setLanguage(languageInstance); + } + + Element messageElement2 = XmlUtility.getElementByTagNameNS(formattedMessageElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement2 != null) { + String messageInstance2; + messageInstance2 = messageElement2.getTextContent(); + formattedMessageInstance.setMessage(messageInstance2); + } + } + } + + Element resourceExtensionStatusListSequenceElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatusList"); + if (resourceExtensionStatusListSequenceElement != null) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatus").size(); i4 = i4 + 1) { + org.w3c.dom.Element resourceExtensionStatusListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatus").get(i4)); + ResourceExtensionStatus resourceExtensionStatusInstance = new ResourceExtensionStatus(); + roleInstanceInstance.getResourceExtensionStatusList().add(resourceExtensionStatusInstance); + + Element handlerNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "HandlerName"); + if (handlerNameElement != null) { + String handlerNameInstance; + handlerNameInstance = handlerNameElement.getTextContent(); + resourceExtensionStatusInstance.setHandlerName(handlerNameInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + resourceExtensionStatusInstance.setVersion(versionInstance); + } + + Element statusElement3 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement3 != null) { + String statusInstance3; + statusInstance3 = statusElement3.getTextContent(); + resourceExtensionStatusInstance.setStatus(statusInstance3); + } + + Element codeElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement2 != null && (codeElement2.getTextContent() == null || codeElement2.getTextContent().isEmpty() == true) == false) { + int codeInstance2; + codeInstance2 = DatatypeConverter.parseInt(codeElement2.getTextContent()); + resourceExtensionStatusInstance.setCode(codeInstance2); + } + + Element messageElement3 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement3 != null) { + GuestAgentMessage messageInstance3 = new GuestAgentMessage(); + resourceExtensionStatusInstance.setMessage(messageInstance3); + + Element messageResourceIdElement2 = XmlUtility.getElementByTagNameNS(messageElement3, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement2 != null) { + String messageResourceIdInstance2; + messageResourceIdInstance2 = messageResourceIdElement2.getTextContent(); + messageInstance3.setMessageResourceId(messageResourceIdInstance2); + } + + Element paramListSequenceElement2 = XmlUtility.getElementByTagNameNS(messageElement3, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement2 != null) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Param").size(); i5 = i5 + 1) { + org.w3c.dom.Element paramListElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Param").get(i5)); + messageInstance3.getParamList().add(paramListElement2.getTextContent()); + } + } + } + + Element formattedMessageElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement2 != null) { + GuestAgentFormattedMessage formattedMessageInstance2 = new GuestAgentFormattedMessage(); + resourceExtensionStatusInstance.setFormattedMessage(formattedMessageInstance2); + + Element languageElement2 = XmlUtility.getElementByTagNameNS(formattedMessageElement2, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement2 != null) { + String languageInstance2; + languageInstance2 = languageElement2.getTextContent(); + formattedMessageInstance2.setLanguage(languageInstance2); + } + + Element messageElement4 = XmlUtility.getElementByTagNameNS(formattedMessageElement2, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement4 != null) { + String messageInstance4; + messageInstance4 = messageElement4.getTextContent(); + formattedMessageInstance2.setMessage(messageInstance4); + } + } + + Element extensionSettingStatusElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "ExtensionSettingStatus"); + if (extensionSettingStatusElement != null) { + ResourceExtensionConfigurationStatus extensionSettingStatusInstance = new ResourceExtensionConfigurationStatus(); + resourceExtensionStatusInstance.setExtensionSettingStatus(extensionSettingStatusInstance); + + Element timestampElement2 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement2 != null && (timestampElement2.getTextContent() == null || timestampElement2.getTextContent().isEmpty() == true) == false) { + Calendar timestampInstance2; + timestampInstance2 = DatatypeConverter.parseDateTime(timestampElement2.getTextContent()); + extensionSettingStatusInstance.setTimestamp(timestampInstance2); + } + + Element configurationAppliedTimeElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationAppliedTime"); + if (configurationAppliedTimeElement != null && (configurationAppliedTimeElement.getTextContent() == null || configurationAppliedTimeElement.getTextContent().isEmpty() == true) == false) { + Calendar configurationAppliedTimeInstance; + configurationAppliedTimeInstance = DatatypeConverter.parseDateTime(configurationAppliedTimeElement.getTextContent()); + extensionSettingStatusInstance.setConfigurationAppliedTime(configurationAppliedTimeInstance); + } + + Element nameElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement3 != null) { + String nameInstance3; + nameInstance3 = nameElement3.getTextContent(); + extensionSettingStatusInstance.setName(nameInstance3); + } + + Element operationElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + String operationInstance; + operationInstance = operationElement.getTextContent(); + extensionSettingStatusInstance.setOperation(operationInstance); + } + + Element statusElement4 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement4 != null) { + String statusInstance4; + statusInstance4 = statusElement4.getTextContent(); + extensionSettingStatusInstance.setStatus(statusInstance4); + } + + Element codeElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement3 != null && (codeElement3.getTextContent() == null || codeElement3.getTextContent().isEmpty() == true) == false) { + int codeInstance3; + codeInstance3 = DatatypeConverter.parseInt(codeElement3.getTextContent()); + extensionSettingStatusInstance.setCode(codeInstance3); + } + + Element messageElement5 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement5 != null) { + GuestAgentMessage messageInstance5 = new GuestAgentMessage(); + extensionSettingStatusInstance.setMessage(messageInstance5); + + Element messageResourceIdElement3 = XmlUtility.getElementByTagNameNS(messageElement5, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement3 != null) { + String messageResourceIdInstance3; + messageResourceIdInstance3 = messageResourceIdElement3.getTextContent(); + messageInstance5.setMessageResourceId(messageResourceIdInstance3); + } + + Element paramListSequenceElement3 = XmlUtility.getElementByTagNameNS(messageElement5, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement3 != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement3, "http://schemas.microsoft.com/windowsazure", "Param").size(); i6 = i6 + 1) { + org.w3c.dom.Element paramListElement3 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement3, "http://schemas.microsoft.com/windowsazure", "Param").get(i6)); + messageInstance5.getParamList().add(paramListElement3.getTextContent()); + } + } + } + + Element formattedMessageElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement3 != null) { + GuestAgentFormattedMessage formattedMessageInstance3 = new GuestAgentFormattedMessage(); + extensionSettingStatusInstance.setFormattedMessage(formattedMessageInstance3); + + Element languageElement3 = XmlUtility.getElementByTagNameNS(formattedMessageElement3, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement3 != null) { + String languageInstance3; + languageInstance3 = languageElement3.getTextContent(); + formattedMessageInstance3.setLanguage(languageInstance3); + } + + Element messageElement6 = XmlUtility.getElementByTagNameNS(formattedMessageElement3, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement6 != null) { + String messageInstance6; + messageInstance6 = messageElement6.getTextContent(); + formattedMessageInstance3.setMessage(messageInstance6); + } + } + + Element subStatusListSequenceElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "SubStatusList"); + if (subStatusListSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubStatus").size(); i7 = i7 + 1) { + org.w3c.dom.Element subStatusListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubStatus").get(i7)); + ResourceExtensionSubStatus subStatusInstance = new ResourceExtensionSubStatus(); + extensionSettingStatusInstance.getSubStatusList().add(subStatusInstance); + + Element nameElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement4 != null) { + String nameInstance4; + nameInstance4 = nameElement4.getTextContent(); + subStatusInstance.setName(nameInstance4); + } + + Element statusElement5 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement5 != null) { + String statusInstance5; + statusInstance5 = statusElement5.getTextContent(); + subStatusInstance.setStatus(statusInstance5); + } + + Element codeElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement4 != null && (codeElement4.getTextContent() == null || codeElement4.getTextContent().isEmpty() == true) == false) { + int codeInstance4; + codeInstance4 = DatatypeConverter.parseInt(codeElement4.getTextContent()); + subStatusInstance.setCode(codeInstance4); + } + + Element messageElement7 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement7 != null) { + GuestAgentMessage messageInstance7 = new GuestAgentMessage(); + subStatusInstance.setMessage(messageInstance7); + + Element messageResourceIdElement4 = XmlUtility.getElementByTagNameNS(messageElement7, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement4 != null) { + String messageResourceIdInstance4; + messageResourceIdInstance4 = messageResourceIdElement4.getTextContent(); + messageInstance7.setMessageResourceId(messageResourceIdInstance4); + } + + Element paramListSequenceElement4 = XmlUtility.getElementByTagNameNS(messageElement7, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement4 != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement4, "http://schemas.microsoft.com/windowsazure", "Param").size(); i8 = i8 + 1) { + org.w3c.dom.Element paramListElement4 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement4, "http://schemas.microsoft.com/windowsazure", "Param").get(i8)); + messageInstance7.getParamList().add(paramListElement4.getTextContent()); + } + } + } + + Element formattedMessageElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement4 != null) { + GuestAgentFormattedMessage formattedMessageInstance4 = new GuestAgentFormattedMessage(); + subStatusInstance.setFormattedMessage(formattedMessageInstance4); + + Element languageElement4 = XmlUtility.getElementByTagNameNS(formattedMessageElement4, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement4 != null) { + String languageInstance4; + languageInstance4 = languageElement4.getTextContent(); + formattedMessageInstance4.setLanguage(languageInstance4); + } + + Element messageElement8 = XmlUtility.getElementByTagNameNS(formattedMessageElement4, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement8 != null) { + String messageInstance8; + messageInstance8 = messageElement8.getTextContent(); + formattedMessageInstance4.setMessage(messageInstance8); + } + } + } + } + } + } + } + + Element powerStateElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "PowerState"); + if (powerStateElement != null) { + RoleInstancePowerState powerStateInstance; + powerStateInstance = RoleInstancePowerState.valueOf(powerStateElement.getTextContent()); + roleInstanceInstance.setPowerState(powerStateInstance); + } + + Element hostNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "HostName"); + if (hostNameElement != null) { + String hostNameInstance; + hostNameInstance = hostNameElement.getTextContent(); + roleInstanceInstance.setHostName(hostNameInstance); + } + + Element remoteAccessCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "RemoteAccessCertificateThumbprint"); + if (remoteAccessCertificateThumbprintElement != null) { + String remoteAccessCertificateThumbprintInstance; + remoteAccessCertificateThumbprintInstance = remoteAccessCertificateThumbprintElement.getTextContent(); + roleInstanceInstance.setRemoteAccessCertificateThumbprint(remoteAccessCertificateThumbprintInstance); + } + } + } + + Element upgradeStatusElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "UpgradeStatus"); + if (upgradeStatusElement != null) { + UpgradeStatus upgradeStatusInstance = new UpgradeStatus(); + result.setUpgradeStatus(upgradeStatusInstance); + + Element upgradeTypeElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "UpgradeType"); + if (upgradeTypeElement != null) { + DeploymentUpgradeType upgradeTypeInstance; + upgradeTypeInstance = DeploymentUpgradeType.valueOf(upgradeTypeElement.getTextContent()); + upgradeStatusInstance.setUpgradeType(upgradeTypeInstance); + } + + Element currentUpgradeDomainStateElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "CurrentUpgradeDomainState"); + if (currentUpgradeDomainStateElement != null) { + UpgradeDomainState currentUpgradeDomainStateInstance; + currentUpgradeDomainStateInstance = UpgradeDomainState.valueOf(currentUpgradeDomainStateElement.getTextContent()); + upgradeStatusInstance.setCurrentUpgradeDomainState(currentUpgradeDomainStateInstance); + } + + Element currentUpgradeDomainElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "CurrentUpgradeDomain"); + if (currentUpgradeDomainElement != null) { + int currentUpgradeDomainInstance; + currentUpgradeDomainInstance = DatatypeConverter.parseInt(currentUpgradeDomainElement.getTextContent()); + upgradeStatusInstance.setCurrentUpgradeDomain(currentUpgradeDomainInstance); + } + } + + Element upgradeDomainCountElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "UpgradeDomainCount"); + if (upgradeDomainCountElement != null) { + int upgradeDomainCountInstance; + upgradeDomainCountInstance = DatatypeConverter.parseInt(upgradeDomainCountElement.getTextContent()); + result.setUpgradeDomainCount(upgradeDomainCountInstance); + } + + Element roleListSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "RoleList"); + if (roleListSequenceElement != null) { + for (int i9 = 0; i9 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").size(); i9 = i9 + 1) { + org.w3c.dom.Element roleListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").get(i9)); + Role roleInstance = new Role(); + result.getRoles().add(roleInstance); + + Element roleNameElement2 = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement2 != null) { + String roleNameInstance2; + roleNameInstance2 = roleNameElement2.getTextContent(); + roleInstance.setRoleName(roleNameInstance2); + } + + Element osVersionElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "OsVersion"); + if (osVersionElement != null) { + String osVersionInstance; + osVersionInstance = osVersionElement.getTextContent(); + roleInstance.setOSVersion(osVersionInstance); + } + + Element roleTypeElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleType"); + if (roleTypeElement != null) { + String roleTypeInstance; + roleTypeInstance = roleTypeElement.getTextContent(); + roleInstance.setRoleType(roleTypeInstance); + } + + Element configurationSetsSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSets"); + if (configurationSetsSequenceElement != null) { + for (int i10 = 0; i10 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").size(); i10 = i10 + 1) { + org.w3c.dom.Element configurationSetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").get(i10)); + ConfigurationSet configurationSetInstance = new ConfigurationSet(); + roleInstance.getConfigurationSets().add(configurationSetInstance); + + Element configurationSetTypeElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + if (configurationSetTypeElement != null) { + String configurationSetTypeInstance; + configurationSetTypeInstance = configurationSetTypeElement.getTextContent(); + configurationSetInstance.setConfigurationSetType(configurationSetTypeInstance); + } + + Element inputEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + if (inputEndpointsSequenceElement != null) { + for (int i11 = 0; i11 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").size(); i11 = i11 + 1) { + org.w3c.dom.Element inputEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").get(i11)); + InputEndpoint inputEndpointInstance = new InputEndpoint(); + configurationSetInstance.getInputEndpoints().add(inputEndpointInstance); + + Element loadBalancedEndpointSetNameElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + if (loadBalancedEndpointSetNameElement != null) { + String loadBalancedEndpointSetNameInstance; + loadBalancedEndpointSetNameInstance = loadBalancedEndpointSetNameElement.getTextContent(); + inputEndpointInstance.setLoadBalancedEndpointSetName(loadBalancedEndpointSetNameInstance); + } + + Element localPortElement2 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LocalPort"); + if (localPortElement2 != null && (localPortElement2.getTextContent() == null || localPortElement2.getTextContent().isEmpty() == true) == false) { + int localPortInstance2; + localPortInstance2 = DatatypeConverter.parseInt(localPortElement2.getTextContent()); + inputEndpointInstance.setLocalPort(localPortInstance2); + } + + Element nameElement5 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement5 != null) { + String nameInstance5; + nameInstance5 = nameElement5.getTextContent(); + inputEndpointInstance.setName(nameInstance5); + } + + Element portElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement != null && (portElement.getTextContent() == null || portElement.getTextContent().isEmpty() == true) == false) { + int portInstance; + portInstance = DatatypeConverter.parseInt(portElement.getTextContent()); + inputEndpointInstance.setPort(portInstance); + } + + Element loadBalancerProbeElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + if (loadBalancerProbeElement != null) { + LoadBalancerProbe loadBalancerProbeInstance = new LoadBalancerProbe(); + inputEndpointInstance.setLoadBalancerProbe(loadBalancerProbeInstance); + + Element pathElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement != null) { + String pathInstance; + pathInstance = pathElement.getTextContent(); + loadBalancerProbeInstance.setPath(pathInstance); + } + + Element portElement2 = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement2 != null) { + int portInstance2; + portInstance2 = DatatypeConverter.parseInt(portElement2.getTextContent()); + loadBalancerProbeInstance.setPort(portInstance2); + } + + Element protocolElement2 = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement2 != null) { + LoadBalancerProbeTransportProtocol protocolInstance2; + protocolInstance2 = com.microsoft.windowsazure.management.compute.ComputeManagementClientImpl.parseLoadBalancerProbeTransportProtocol(protocolElement2.getTextContent()); + loadBalancerProbeInstance.setProtocol(protocolInstance2); + } + + Element intervalInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + if (intervalInSecondsElement != null && (intervalInSecondsElement.getTextContent() == null || intervalInSecondsElement.getTextContent().isEmpty() == true) == false) { + int intervalInSecondsInstance; + intervalInSecondsInstance = DatatypeConverter.parseInt(intervalInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setIntervalInSeconds(intervalInSecondsInstance); + } + + Element timeoutInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + if (timeoutInSecondsElement != null && (timeoutInSecondsElement.getTextContent() == null || timeoutInSecondsElement.getTextContent().isEmpty() == true) == false) { + int timeoutInSecondsInstance; + timeoutInSecondsInstance = DatatypeConverter.parseInt(timeoutInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setTimeoutInSeconds(timeoutInSecondsInstance); + } + } + + Element protocolElement3 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement3 != null) { + String protocolInstance3; + protocolInstance3 = protocolElement3.getTextContent(); + inputEndpointInstance.setProtocol(protocolInstance3); + } + + Element vipElement2 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Vip"); + if (vipElement2 != null) { + InetAddress vipInstance2; + vipInstance2 = InetAddress.getByName(vipElement2.getTextContent()); + inputEndpointInstance.setVirtualIPAddress(vipInstance2); + } + + Element enableDirectServerReturnElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + if (enableDirectServerReturnElement != null && (enableDirectServerReturnElement.getTextContent() == null || enableDirectServerReturnElement.getTextContent().isEmpty() == true) == false) { + boolean enableDirectServerReturnInstance; + enableDirectServerReturnInstance = DatatypeConverter.parseBoolean(enableDirectServerReturnElement.getTextContent().toLowerCase()); + inputEndpointInstance.setEnableDirectServerReturn(enableDirectServerReturnInstance); + } + + Element endpointAclElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + if (endpointAclElement != null) { + EndpointAcl endpointAclInstance = new EndpointAcl(); + inputEndpointInstance.setEndpointAcl(endpointAclInstance); + + Element rulesSequenceElement = XmlUtility.getElementByTagNameNS(endpointAclElement, "http://schemas.microsoft.com/windowsazure", "Rules"); + if (rulesSequenceElement != null) { + for (int i12 = 0; i12 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").size(); i12 = i12 + 1) { + org.w3c.dom.Element rulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").get(i12)); + AccessControlListRule ruleInstance = new AccessControlListRule(); + endpointAclInstance.getRules().add(ruleInstance); + + Element orderElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Order"); + if (orderElement != null && (orderElement.getTextContent() == null || orderElement.getTextContent().isEmpty() == true) == false) { + int orderInstance; + orderInstance = DatatypeConverter.parseInt(orderElement.getTextContent()); + ruleInstance.setOrder(orderInstance); + } + + Element actionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Action"); + if (actionElement != null) { + String actionInstance; + actionInstance = actionElement.getTextContent(); + ruleInstance.setAction(actionInstance); + } + + Element remoteSubnetElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + if (remoteSubnetElement != null) { + String remoteSubnetInstance; + remoteSubnetInstance = remoteSubnetElement.getTextContent(); + ruleInstance.setRemoteSubnet(remoteSubnetInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + ruleInstance.setDescription(descriptionInstance); + } + } + } + } + } + } + + Element subnetNamesSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SubnetNames"); + if (subnetNamesSequenceElement != null) { + for (int i13 = 0; i13 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").size(); i13 = i13 + 1) { + org.w3c.dom.Element subnetNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").get(i13)); + configurationSetInstance.getSubnetNames().add(subnetNamesElement.getTextContent()); + } + } + + Element staticVirtualNetworkIPAddressElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + if (staticVirtualNetworkIPAddressElement != null) { + String staticVirtualNetworkIPAddressInstance; + staticVirtualNetworkIPAddressInstance = staticVirtualNetworkIPAddressElement.getTextContent(); + configurationSetInstance.setStaticVirtualNetworkIPAddress(staticVirtualNetworkIPAddressInstance); + } + + Element computerNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ComputerName"); + if (computerNameElement != null) { + String computerNameInstance; + computerNameInstance = computerNameElement.getTextContent(); + configurationSetInstance.setComputerName(computerNameInstance); + } + + Element adminPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminPassword"); + if (adminPasswordElement != null) { + String adminPasswordInstance; + adminPasswordInstance = adminPasswordElement.getTextContent(); + configurationSetInstance.setAdminPassword(adminPasswordInstance); + } + + Element resetPasswordOnFirstLogonElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + if (resetPasswordOnFirstLogonElement != null && (resetPasswordOnFirstLogonElement.getTextContent() == null || resetPasswordOnFirstLogonElement.getTextContent().isEmpty() == true) == false) { + boolean resetPasswordOnFirstLogonInstance; + resetPasswordOnFirstLogonInstance = DatatypeConverter.parseBoolean(resetPasswordOnFirstLogonElement.getTextContent().toLowerCase()); + configurationSetInstance.setResetPasswordOnFirstLogon(resetPasswordOnFirstLogonInstance); + } + + Element enableAutomaticUpdatesElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + if (enableAutomaticUpdatesElement != null && (enableAutomaticUpdatesElement.getTextContent() == null || enableAutomaticUpdatesElement.getTextContent().isEmpty() == true) == false) { + boolean enableAutomaticUpdatesInstance; + enableAutomaticUpdatesInstance = DatatypeConverter.parseBoolean(enableAutomaticUpdatesElement.getTextContent().toLowerCase()); + configurationSetInstance.setEnableAutomaticUpdates(enableAutomaticUpdatesInstance); + } + + Element timeZoneElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "TimeZone"); + if (timeZoneElement != null) { + String timeZoneInstance; + timeZoneInstance = timeZoneElement.getTextContent(); + configurationSetInstance.setTimeZone(timeZoneInstance); + } + + Element domainJoinElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DomainJoin"); + if (domainJoinElement != null) { + DomainJoinSettings domainJoinInstance = new DomainJoinSettings(); + configurationSetInstance.setDomainJoin(domainJoinInstance); + + Element credentialsElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Credentials"); + if (credentialsElement != null) { + DomainJoinCredentials credentialsInstance = new DomainJoinCredentials(); + domainJoinInstance.setCredentials(credentialsInstance); + + Element domainElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Domain"); + if (domainElement != null) { + String domainInstance; + domainInstance = domainElement.getTextContent(); + credentialsInstance.setDomain(domainInstance); + } + + Element usernameElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Username"); + if (usernameElement != null) { + String usernameInstance; + usernameInstance = usernameElement.getTextContent(); + credentialsInstance.setUserName(usernameInstance); + } + + Element passwordElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement != null) { + String passwordInstance; + passwordInstance = passwordElement.getTextContent(); + credentialsInstance.setPassword(passwordInstance); + } + } + + Element joinDomainElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "JoinDomain"); + if (joinDomainElement != null) { + String joinDomainInstance; + joinDomainInstance = joinDomainElement.getTextContent(); + domainJoinInstance.setDomainToJoin(joinDomainInstance); + } + + Element machineObjectOUElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + if (machineObjectOUElement != null) { + String machineObjectOUInstance; + machineObjectOUInstance = machineObjectOUElement.getTextContent(); + domainJoinInstance.setLdapMachineObjectOU(machineObjectOUInstance); + } + + Element provisioningElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Provisioning"); + if (provisioningElement != null) { + DomainJoinProvisioning provisioningInstance = new DomainJoinProvisioning(); + domainJoinInstance.setProvisioning(provisioningInstance); + + Element accountDataElement = XmlUtility.getElementByTagNameNS(provisioningElement, "http://schemas.microsoft.com/windowsazure", "AccountData"); + if (accountDataElement != null) { + String accountDataInstance; + accountDataInstance = accountDataElement.getTextContent(); + provisioningInstance.setAccountData(accountDataInstance); + } + } + } + + Element storedCertificateSettingsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + if (storedCertificateSettingsSequenceElement != null) { + for (int i14 = 0; i14 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").size(); i14 = i14 + 1) { + org.w3c.dom.Element storedCertificateSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").get(i14)); + StoredCertificateSettings certificateSettingInstance = new StoredCertificateSettings(); + configurationSetInstance.getStoredCertificateSettings().add(certificateSettingInstance); + + Element storeLocationElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreLocation"); + if (storeLocationElement != null) { + } + + Element storeNameElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreName"); + if (storeNameElement != null) { + String storeNameInstance; + storeNameInstance = storeNameElement.getTextContent(); + certificateSettingInstance.setStoreName(storeNameInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + certificateSettingInstance.setThumbprint(thumbprintInstance); + } + } + } + + Element winRMElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "WinRM"); + if (winRMElement != null) { + WindowsRemoteManagementSettings winRMInstance = new WindowsRemoteManagementSettings(); + configurationSetInstance.setWindowsRemoteManagement(winRMInstance); + + Element listenersSequenceElement = XmlUtility.getElementByTagNameNS(winRMElement, "http://schemas.microsoft.com/windowsazure", "Listeners"); + if (listenersSequenceElement != null) { + for (int i15 = 0; i15 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").size(); i15 = i15 + 1) { + org.w3c.dom.Element listenersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").get(i15)); + WindowsRemoteManagementListener listenerInstance = new WindowsRemoteManagementListener(); + winRMInstance.getListeners().add(listenerInstance); + + Element protocolElement4 = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement4 != null) { + VirtualMachineWindowsRemoteManagementListenerType protocolInstance4; + protocolInstance4 = VirtualMachineWindowsRemoteManagementListenerType.valueOf(protocolElement4.getTextContent()); + listenerInstance.setListenerType(protocolInstance4); + } + + Element certificateThumbprintElement = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + if (certificateThumbprintElement != null) { + String certificateThumbprintInstance; + certificateThumbprintInstance = certificateThumbprintElement.getTextContent(); + listenerInstance.setCertificateThumbprint(certificateThumbprintInstance); + } + } + } + } + + Element adminUsernameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminUsername"); + if (adminUsernameElement != null) { + String adminUsernameInstance; + adminUsernameInstance = adminUsernameElement.getTextContent(); + configurationSetInstance.setAdminUserName(adminUsernameInstance); + } + + Element hostNameElement2 = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "HostName"); + if (hostNameElement2 != null) { + String hostNameInstance2; + hostNameInstance2 = hostNameElement2.getTextContent(); + configurationSetInstance.setHostName(hostNameInstance2); + } + + Element userNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserName"); + if (userNameElement != null) { + String userNameInstance; + userNameInstance = userNameElement.getTextContent(); + configurationSetInstance.setUserName(userNameInstance); + } + + Element userPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserPassword"); + if (userPasswordElement != null) { + String userPasswordInstance; + userPasswordInstance = userPasswordElement.getTextContent(); + configurationSetInstance.setUserPassword(userPasswordInstance); + } + + Element disableSshPasswordAuthenticationElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + if (disableSshPasswordAuthenticationElement != null && (disableSshPasswordAuthenticationElement.getTextContent() == null || disableSshPasswordAuthenticationElement.getTextContent().isEmpty() == true) == false) { + boolean disableSshPasswordAuthenticationInstance; + disableSshPasswordAuthenticationInstance = DatatypeConverter.parseBoolean(disableSshPasswordAuthenticationElement.getTextContent().toLowerCase()); + configurationSetInstance.setDisableSshPasswordAuthentication(disableSshPasswordAuthenticationInstance); + } + + Element sSHElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SSH"); + if (sSHElement != null) { + SshSettings sSHInstance = new SshSettings(); + configurationSetInstance.setSshSettings(sSHInstance); + + Element publicKeysSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "PublicKeys"); + if (publicKeysSequenceElement != null) { + for (int i16 = 0; i16 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").size(); i16 = i16 + 1) { + org.w3c.dom.Element publicKeysElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").get(i16)); + SshSettingPublicKey publicKeyInstance = new SshSettingPublicKey(); + sSHInstance.getPublicKeys().add(publicKeyInstance); + + Element fingerprintElement = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement != null) { + String fingerprintInstance; + fingerprintInstance = fingerprintElement.getTextContent(); + publicKeyInstance.setFingerprint(fingerprintInstance); + } + + Element pathElement2 = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement2 != null) { + String pathInstance2; + pathInstance2 = pathElement2.getTextContent(); + publicKeyInstance.setPath(pathInstance2); + } + } + } + + Element keyPairsSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "KeyPairs"); + if (keyPairsSequenceElement != null) { + for (int i17 = 0; i17 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").size(); i17 = i17 + 1) { + org.w3c.dom.Element keyPairsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").get(i17)); + SshSettingKeyPair keyPairInstance = new SshSettingKeyPair(); + sSHInstance.getKeyPairs().add(keyPairInstance); + + Element fingerprintElement2 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement2 != null) { + String fingerprintInstance2; + fingerprintInstance2 = fingerprintElement2.getTextContent(); + keyPairInstance.setFingerprint(fingerprintInstance2); + } + + Element pathElement3 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement3 != null) { + String pathInstance3; + pathInstance3 = pathElement3.getTextContent(); + keyPairInstance.setPath(pathInstance3); + } + } + } + } + + Element customDataElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "CustomData"); + if (customDataElement != null) { + String customDataInstance; + customDataInstance = customDataElement.getTextContent(); + configurationSetInstance.setCustomData(customDataInstance); + } + } + } + + Element resourceExtensionReferencesSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences"); + if (resourceExtensionReferencesSequenceElement != null) { + for (int i18 = 0; i18 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionReferencesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference").size(); i18 = i18 + 1) { + org.w3c.dom.Element resourceExtensionReferencesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionReferencesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference").get(i18)); + ResourceExtensionReference resourceExtensionReferenceInstance = new ResourceExtensionReference(); + roleInstance.getResourceExtensionReferences().add(resourceExtensionReferenceInstance); + + Element referenceNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "ReferenceName"); + if (referenceNameElement != null) { + String referenceNameInstance; + referenceNameInstance = referenceNameElement.getTextContent(); + resourceExtensionReferenceInstance.setReferenceName(referenceNameInstance); + } + + Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Publisher"); + if (publisherElement != null) { + String publisherInstance; + publisherInstance = publisherElement.getTextContent(); + resourceExtensionReferenceInstance.setPublisher(publisherInstance); + } + + Element nameElement6 = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement6 != null) { + String nameInstance6; + nameInstance6 = nameElement6.getTextContent(); + resourceExtensionReferenceInstance.setName(nameInstance6); + } + + Element versionElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement2 != null) { + String versionInstance2; + versionInstance2 = versionElement2.getTextContent(); + resourceExtensionReferenceInstance.setVersion(versionInstance2); + } + + Element resourceExtensionParameterValuesSequenceElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValues"); + if (resourceExtensionParameterValuesSequenceElement != null) { + for (int i19 = 0; i19 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionParameterValuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue").size(); i19 = i19 + 1) { + org.w3c.dom.Element resourceExtensionParameterValuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionParameterValuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue").get(i19)); + ResourceExtensionParameterValue resourceExtensionParameterValueInstance = new ResourceExtensionParameterValue(); + resourceExtensionReferenceInstance.getResourceExtensionParameterValues().add(resourceExtensionParameterValueInstance); + + Element keyElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Key"); + if (keyElement != null) { + String keyInstance; + keyInstance = keyElement.getTextContent(); + resourceExtensionParameterValueInstance.setKey(keyInstance); + } + + Element valueElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Value"); + if (valueElement != null) { + String valueInstance; + valueInstance = valueElement.getTextContent() != null ? new String(Base64.decode(valueElement.getTextContent())) : null; + resourceExtensionParameterValueInstance.setValue(valueInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + resourceExtensionParameterValueInstance.setType(typeInstance); + } + } + } + + Element stateElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + resourceExtensionReferenceInstance.setState(stateInstance); + } + } + } + + Element vMImageNameElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "VMImageName"); + if (vMImageNameElement != null) { + String vMImageNameInstance; + vMImageNameInstance = vMImageNameElement.getTextContent(); + roleInstance.setVMImageName(vMImageNameInstance); + } + + Element availabilitySetNameElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "AvailabilitySetName"); + if (availabilitySetNameElement != null) { + String availabilitySetNameInstance; + availabilitySetNameInstance = availabilitySetNameElement.getTextContent(); + roleInstance.setAvailabilitySetName(availabilitySetNameInstance); + } + + Element dataVirtualHardDisksSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks"); + if (dataVirtualHardDisksSequenceElement != null) { + for (int i20 = 0; i20 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").size(); i20 = i20 + 1) { + org.w3c.dom.Element dataVirtualHardDisksElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").get(i20)); + DataVirtualHardDisk dataVirtualHardDiskInstance = new DataVirtualHardDisk(); + roleInstance.getDataVirtualHardDisks().add(dataVirtualHardDiskInstance); + + Element hostCachingElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement != null && (hostCachingElement.getTextContent() == null || hostCachingElement.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance; + hostCachingInstance = VirtualHardDiskHostCaching.valueOf(hostCachingElement.getTextContent()); + dataVirtualHardDiskInstance.setHostCaching(hostCachingInstance); + } + + Element diskLabelElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement != null) { + String diskLabelInstance; + diskLabelInstance = diskLabelElement.getTextContent(); + dataVirtualHardDiskInstance.setLabel(diskLabelInstance); + } + + Element diskNameElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement != null) { + String diskNameInstance; + diskNameInstance = diskNameElement.getTextContent(); + dataVirtualHardDiskInstance.setName(diskNameInstance); + } + + Element lunElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "Lun"); + if (lunElement != null && (lunElement.getTextContent() == null || lunElement.getTextContent().isEmpty() == true) == false) { + int lunInstance; + lunInstance = DatatypeConverter.parseInt(lunElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalUnitNumber(lunInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null && (logicalDiskSizeInGBElement.getTextContent() == null || logicalDiskSizeInGBElement.getTextContent().isEmpty() == true) == false) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setMediaLink(mediaLinkInstance); + } + + Element sourceMediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + if (sourceMediaLinkElement != null) { + URI sourceMediaLinkInstance; + sourceMediaLinkInstance = new URI(sourceMediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setSourceMediaLink(sourceMediaLinkInstance); + } + } + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance2; + labelInstance2 = labelElement2.getTextContent(); + roleInstance.setLabel(labelInstance2); + } + + Element oSVirtualHardDiskElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk"); + if (oSVirtualHardDiskElement != null) { + OSVirtualHardDisk oSVirtualHardDiskInstance = new OSVirtualHardDisk(); + roleInstance.setOSVirtualHardDisk(oSVirtualHardDiskInstance); + + Element hostCachingElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement2 != null && (hostCachingElement2.getTextContent() == null || hostCachingElement2.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance2; + hostCachingInstance2 = VirtualHardDiskHostCaching.valueOf(hostCachingElement2.getTextContent()); + oSVirtualHardDiskInstance.setHostCaching(hostCachingInstance2); + } + + Element diskLabelElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement2 != null) { + String diskLabelInstance2; + diskLabelInstance2 = diskLabelElement2.getTextContent(); + oSVirtualHardDiskInstance.setLabel(diskLabelInstance2); + } + + Element diskNameElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement2 != null) { + String diskNameInstance2; + diskNameInstance2 = diskNameElement2.getTextContent(); + oSVirtualHardDiskInstance.setName(diskNameInstance2); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance2; + mediaLinkInstance2 = new URI(mediaLinkElement2.getTextContent()); + oSVirtualHardDiskInstance.setMediaLink(mediaLinkInstance2); + } + + Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); + if (sourceImageNameElement != null) { + String sourceImageNameInstance; + sourceImageNameInstance = sourceImageNameElement.getTextContent(); + oSVirtualHardDiskInstance.setSourceImageName(sourceImageNameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + oSVirtualHardDiskInstance.setOperatingSystem(osInstance); + } + } + + Element roleSizeElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleSize"); + if (roleSizeElement != null) { + String roleSizeInstance; + roleSizeInstance = roleSizeElement.getTextContent(); + roleInstance.setRoleSize(roleSizeInstance); + } + + Element provisionGuestAgentElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent"); + if (provisionGuestAgentElement != null && (provisionGuestAgentElement.getTextContent() == null || provisionGuestAgentElement.getTextContent().isEmpty() == true) == false) { + boolean provisionGuestAgentInstance; + provisionGuestAgentInstance = DatatypeConverter.parseBoolean(provisionGuestAgentElement.getTextContent().toLowerCase()); + roleInstance.setProvisionGuestAgent(provisionGuestAgentInstance); + } + + Element defaultWinRmCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "DefaultWinRmCertificateThumbprint"); + if (defaultWinRmCertificateThumbprintElement != null) { + String defaultWinRmCertificateThumbprintInstance; + defaultWinRmCertificateThumbprintInstance = defaultWinRmCertificateThumbprintElement.getTextContent(); + roleInstance.setDefaultWinRmCertificateThumbprint(defaultWinRmCertificateThumbprintInstance); + } + } + } + + Element sdkVersionElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "SdkVersion"); + if (sdkVersionElement != null) { + String sdkVersionInstance; + sdkVersionInstance = sdkVersionElement.getTextContent(); + result.setSdkVersion(sdkVersionInstance); + } + + Element lockedElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Locked"); + if (lockedElement != null) { + boolean lockedInstance; + lockedInstance = DatatypeConverter.parseBoolean(lockedElement.getTextContent().toLowerCase()); + result.setLocked(lockedInstance); + } + + Element rollbackAllowedElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "RollbackAllowed"); + if (rollbackAllowedElement != null) { + boolean rollbackAllowedInstance; + rollbackAllowedInstance = DatatypeConverter.parseBoolean(rollbackAllowedElement.getTextContent().toLowerCase()); + result.setRollbackAllowed(rollbackAllowedInstance); + } + + Element createdTimeElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); + if (createdTimeElement != null) { + Calendar createdTimeInstance; + createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); + result.setCreatedTime(createdTimeInstance); + } + + Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "LastModifiedTime"); + if (lastModifiedTimeElement != null) { + Calendar lastModifiedTimeInstance; + lastModifiedTimeInstance = DatatypeConverter.parseDateTime(lastModifiedTimeElement.getTextContent()); + result.setLastModifiedTime(lastModifiedTimeInstance); + } + + Element virtualNetworkNameElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "VirtualNetworkName"); + if (virtualNetworkNameElement != null) { + String virtualNetworkNameInstance; + virtualNetworkNameInstance = virtualNetworkNameElement.getTextContent(); + result.setVirtualNetworkName(virtualNetworkNameInstance); + } + + Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement != null) { + for (int i21 = 0; i21 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i21 = i21 + 1) { + org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i21)); + String extendedPropertiesKey = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + result.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); + } + } + + Element persistentVMDowntimeElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "PersistentVMDowntime"); + if (persistentVMDowntimeElement != null) { + PersistentVMDowntime persistentVMDowntimeInstance = new PersistentVMDowntime(); + result.setPersistentVMDowntime(persistentVMDowntimeInstance); + + Element startTimeElement = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); + if (startTimeElement != null) { + Calendar startTimeInstance; + startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); + persistentVMDowntimeInstance.setStartTime(startTimeInstance); + } + + Element endTimeElement = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "EndTime"); + if (endTimeElement != null) { + Calendar endTimeInstance; + endTimeInstance = DatatypeConverter.parseDateTime(endTimeElement.getTextContent()); + persistentVMDowntimeInstance.setEndTime(endTimeInstance); + } + + Element statusElement6 = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement6 != null) { + String statusInstance6; + statusInstance6 = statusElement6.getTextContent(); + persistentVMDowntimeInstance.setStatus(statusInstance6); + } + } + + Element virtualIPsSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "VirtualIPs"); + if (virtualIPsSequenceElement != null) { + for (int i22 = 0; i22 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP").size(); i22 = i22 + 1) { + org.w3c.dom.Element virtualIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP").get(i22)); + VirtualIPAddress virtualIPInstance = new VirtualIPAddress(); + result.getVirtualIPAddresses().add(virtualIPInstance); + + Element addressElement = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement != null) { + InetAddress addressInstance; + addressInstance = InetAddress.getByName(addressElement.getTextContent()); + virtualIPInstance.setAddress(addressInstance); + } + + Element nameElement7 = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement7 != null) { + String nameInstance7; + nameInstance7 = nameElement7.getTextContent(); + virtualIPInstance.setName(nameInstance7); + } + + Element isDnsProgrammedElement = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "IsDnsProgrammed"); + if (isDnsProgrammedElement != null && (isDnsProgrammedElement.getTextContent() == null || isDnsProgrammedElement.getTextContent().isEmpty() == true) == false) { + boolean isDnsProgrammedInstance; + isDnsProgrammedInstance = DatatypeConverter.parseBoolean(isDnsProgrammedElement.getTextContent().toLowerCase()); + virtualIPInstance.setIsDnsProgrammed(isDnsProgrammedInstance); + } + } + } + + Element reservedIPNameElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "ReservedIPName"); + if (reservedIPNameElement != null) { + String reservedIPNameInstance; + reservedIPNameInstance = reservedIPNameElement.getTextContent(); + result.setReservedIPName(reservedIPNameInstance); + } + + Element dnsElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Dns"); + if (dnsElement != null) { + DnsSettings dnsInstance = new DnsSettings(); + result.setDnsSettings(dnsInstance); + + Element dnsServersSequenceElement = XmlUtility.getElementByTagNameNS(dnsElement, "http://schemas.microsoft.com/windowsazure", "DnsServers"); + if (dnsServersSequenceElement != null) { + for (int i23 = 0; i23 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").size(); i23 = i23 + 1) { + org.w3c.dom.Element dnsServersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").get(i23)); + DnsServer dnsServerInstance = new DnsServer(); + dnsInstance.getDnsServers().add(dnsServerInstance); + + Element nameElement8 = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement8 != null) { + String nameInstance8; + nameInstance8 = nameElement8.getTextContent(); + dnsServerInstance.setName(nameInstance8); + } + + Element addressElement2 = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement2 != null) { + InetAddress addressInstance2; + addressInstance2 = InetAddress.getByName(addressElement2.getTextContent()); + dnsServerInstance.setAddress(addressInstance2); + } + } + } + } + + Element extensionConfigurationElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration"); + if (extensionConfigurationElement != null) { + ExtensionConfiguration extensionConfigurationInstance = new ExtensionConfiguration(); + result.setExtensionConfiguration(extensionConfigurationInstance); + + Element allRolesSequenceElement = XmlUtility.getElementByTagNameNS(extensionConfigurationElement, "http://schemas.microsoft.com/windowsazure", "AllRoles"); + if (allRolesSequenceElement != null) { + for (int i24 = 0; i24 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(allRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").size(); i24 = i24 + 1) { + org.w3c.dom.Element allRolesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(allRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").get(i24)); + ExtensionConfiguration.Extension extensionInstance = new ExtensionConfiguration.Extension(); + extensionConfigurationInstance.getAllRoles().add(extensionInstance); + + Element idElement = XmlUtility.getElementByTagNameNS(allRolesElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + extensionInstance.setId(idInstance); + } + } + } + + Element namedRolesSequenceElement = XmlUtility.getElementByTagNameNS(extensionConfigurationElement, "http://schemas.microsoft.com/windowsazure", "NamedRoles"); + if (namedRolesSequenceElement != null) { + for (int i25 = 0; i25 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(namedRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").size(); i25 = i25 + 1) { + org.w3c.dom.Element namedRolesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(namedRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").get(i25)); + ExtensionConfiguration.NamedRole roleInstance2 = new ExtensionConfiguration.NamedRole(); + extensionConfigurationInstance.getNamedRoles().add(roleInstance2); + + Element roleNameElement3 = XmlUtility.getElementByTagNameNS(namedRolesElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement3 != null) { + String roleNameInstance3; + roleNameInstance3 = roleNameElement3.getTextContent(); + roleInstance2.setRoleName(roleNameInstance3); + } + + Element extensionsSequenceElement = XmlUtility.getElementByTagNameNS(namedRolesElement, "http://schemas.microsoft.com/windowsazure", "Extensions"); + if (extensionsSequenceElement != null) { + for (int i26 = 0; i26 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").size(); i26 = i26 + 1) { + org.w3c.dom.Element extensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").get(i26)); + ExtensionConfiguration.Extension extensionInstance2 = new ExtensionConfiguration.Extension(); + roleInstance2.getExtensions().add(extensionInstance2); + + Element idElement2 = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement2 != null) { + String idInstance2; + idInstance2 = idElement2.getTextContent(); + extensionInstance2.setId(idInstance2); + } + } + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Deployment By Slot operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @return A deployment that exists in the cloud service. + */ + @Override + public Future getBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DeploymentGetResponse call() throws Exception { + return getBySlot(serviceName, deploymentSlot); + } + }); + } + + /** + * The Get Deployment By Slot operation returns configuration information, + * status, and system properties for a deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A deployment that exists in the cloud service. + */ + @Override + public DeploymentGetResponse getBySlot(String serviceName, DeploymentSlot deploymentSlot) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + CloudTracing.enter(invocationId, this, "getBySlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DeploymentGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DeploymentGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element deploymentElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Deployment"); + if (deploymentElement != null) { + Element nameElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element deploymentSlotElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "DeploymentSlot"); + if (deploymentSlotElement != null) { + DeploymentSlot deploymentSlotInstance; + deploymentSlotInstance = DeploymentSlot.valueOf(deploymentSlotElement.getTextContent()); + result.setDeploymentSlot(deploymentSlotInstance); + } + + Element privateIDElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "PrivateID"); + if (privateIDElement != null) { + String privateIDInstance; + privateIDInstance = privateIDElement.getTextContent(); + result.setPrivateId(privateIDInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + DeploymentStatus statusInstance; + statusInstance = DeploymentStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + result.setLabel(labelInstance); + } + + Element urlElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + result.setUri(urlInstance); + } + + Element configurationElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Configuration"); + if (configurationElement != null) { + String configurationInstance; + configurationInstance = configurationElement.getTextContent() != null ? new String(Base64.decode(configurationElement.getTextContent())) : null; + result.setConfiguration(configurationInstance); + } + + Element roleInstanceListSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "RoleInstanceList"); + if (roleInstanceListSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleInstanceListSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleInstance").size(); i1 = i1 + 1) { + org.w3c.dom.Element roleInstanceListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleInstanceListSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleInstance").get(i1)); + RoleInstance roleInstanceInstance = new RoleInstance(); + result.getRoleInstances().add(roleInstanceInstance); + + Element roleNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + roleInstanceInstance.setRoleName(roleNameInstance); + } + + Element instanceNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceName"); + if (instanceNameElement != null) { + String instanceNameInstance; + instanceNameInstance = instanceNameElement.getTextContent(); + roleInstanceInstance.setInstanceName(instanceNameInstance); + } + + Element instanceStatusElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceStatus"); + if (instanceStatusElement != null) { + String instanceStatusInstance; + instanceStatusInstance = instanceStatusElement.getTextContent(); + roleInstanceInstance.setInstanceStatus(instanceStatusInstance); + } + + Element instanceUpgradeDomainElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceUpgradeDomain"); + if (instanceUpgradeDomainElement != null && (instanceUpgradeDomainElement.getTextContent() == null || instanceUpgradeDomainElement.getTextContent().isEmpty() == true) == false) { + int instanceUpgradeDomainInstance; + instanceUpgradeDomainInstance = DatatypeConverter.parseInt(instanceUpgradeDomainElement.getTextContent()); + roleInstanceInstance.setInstanceUpgradeDomain(instanceUpgradeDomainInstance); + } + + Element instanceFaultDomainElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceFaultDomain"); + if (instanceFaultDomainElement != null && (instanceFaultDomainElement.getTextContent() == null || instanceFaultDomainElement.getTextContent().isEmpty() == true) == false) { + int instanceFaultDomainInstance; + instanceFaultDomainInstance = DatatypeConverter.parseInt(instanceFaultDomainElement.getTextContent()); + roleInstanceInstance.setInstanceFaultDomain(instanceFaultDomainInstance); + } + + Element instanceSizeElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceSize"); + if (instanceSizeElement != null) { + String instanceSizeInstance; + instanceSizeInstance = instanceSizeElement.getTextContent(); + roleInstanceInstance.setInstanceSize(instanceSizeInstance); + } + + Element instanceStateDetailsElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceStateDetails"); + if (instanceStateDetailsElement != null) { + String instanceStateDetailsInstance; + instanceStateDetailsInstance = instanceStateDetailsElement.getTextContent(); + roleInstanceInstance.setInstanceStateDetails(instanceStateDetailsInstance); + } + + Element instanceErrorCodeElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceErrorCode"); + if (instanceErrorCodeElement != null) { + String instanceErrorCodeInstance; + instanceErrorCodeInstance = instanceErrorCodeElement.getTextContent(); + roleInstanceInstance.setInstanceErrorCode(instanceErrorCodeInstance); + } + + Element ipAddressElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "IpAddress"); + if (ipAddressElement != null) { + InetAddress ipAddressInstance; + ipAddressInstance = InetAddress.getByName(ipAddressElement.getTextContent()); + roleInstanceInstance.setIPAddress(ipAddressInstance); + } + + Element instanceEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoints"); + if (instanceEndpointsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(instanceEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoint").size(); i2 = i2 + 1) { + org.w3c.dom.Element instanceEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(instanceEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoint").get(i2)); + InstanceEndpoint instanceEndpointInstance = new InstanceEndpoint(); + roleInstanceInstance.getInstanceEndpoints().add(instanceEndpointInstance); + + Element localPortElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LocalPort"); + if (localPortElement != null && (localPortElement.getTextContent() == null || localPortElement.getTextContent().isEmpty() == true) == false) { + int localPortInstance; + localPortInstance = DatatypeConverter.parseInt(localPortElement.getTextContent()); + instanceEndpointInstance.setLocalPort(localPortInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + instanceEndpointInstance.setName(nameInstance2); + } + + Element publicPortElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "PublicPort"); + if (publicPortElement != null) { + int publicPortInstance; + publicPortInstance = DatatypeConverter.parseInt(publicPortElement.getTextContent()); + instanceEndpointInstance.setPort(publicPortInstance); + } + + Element protocolElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement != null) { + String protocolInstance; + protocolInstance = protocolElement.getTextContent(); + instanceEndpointInstance.setProtocol(protocolInstance); + } + + Element vipElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Vip"); + if (vipElement != null) { + InetAddress vipInstance; + vipInstance = InetAddress.getByName(vipElement.getTextContent()); + instanceEndpointInstance.setVirtualIPAddress(vipInstance); + } + } + } + + Element guestAgentStatusElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "GuestAgentStatus"); + if (guestAgentStatusElement != null) { + GuestAgentStatus guestAgentStatusInstance = new GuestAgentStatus(); + roleInstanceInstance.setGuestAgentStatus(guestAgentStatusInstance); + + Element protocolVersionElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "ProtocolVersion"); + if (protocolVersionElement != null) { + String protocolVersionInstance; + protocolVersionInstance = protocolVersionElement.getTextContent(); + guestAgentStatusInstance.setProtocolVersion(protocolVersionInstance); + } + + Element timestampElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement != null && (timestampElement.getTextContent() == null || timestampElement.getTextContent().isEmpty() == true) == false) { + Calendar timestampInstance; + timestampInstance = DatatypeConverter.parseDateTime(timestampElement.getTextContent()); + guestAgentStatusInstance.setTimestamp(timestampInstance); + } + + Element guestAgentVersionElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "GuestAgentVersion"); + if (guestAgentVersionElement != null) { + String guestAgentVersionInstance; + guestAgentVersionInstance = guestAgentVersionElement.getTextContent(); + guestAgentStatusInstance.setGuestAgentVersion(guestAgentVersionInstance); + } + + Element statusElement2 = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement2 != null) { + String statusInstance2; + statusInstance2 = statusElement2.getTextContent(); + guestAgentStatusInstance.setStatus(statusInstance2); + } + + Element codeElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null && (codeElement.getTextContent() == null || codeElement.getTextContent().isEmpty() == true) == false) { + int codeInstance; + codeInstance = DatatypeConverter.parseInt(codeElement.getTextContent()); + guestAgentStatusInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + GuestAgentMessage messageInstance = new GuestAgentMessage(); + guestAgentStatusInstance.setMessage(messageInstance); + + Element messageResourceIdElement = XmlUtility.getElementByTagNameNS(messageElement, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement != null) { + String messageResourceIdInstance; + messageResourceIdInstance = messageResourceIdElement.getTextContent(); + messageInstance.setMessageResourceId(messageResourceIdInstance); + } + + Element paramListSequenceElement = XmlUtility.getElementByTagNameNS(messageElement, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Param").size(); i3 = i3 + 1) { + org.w3c.dom.Element paramListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Param").get(i3)); + messageInstance.getParamList().add(paramListElement.getTextContent()); + } + } + } + + Element formattedMessageElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement != null) { + GuestAgentFormattedMessage formattedMessageInstance = new GuestAgentFormattedMessage(); + guestAgentStatusInstance.setFormattedMessage(formattedMessageInstance); + + Element languageElement = XmlUtility.getElementByTagNameNS(formattedMessageElement, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement != null) { + String languageInstance; + languageInstance = languageElement.getTextContent(); + formattedMessageInstance.setLanguage(languageInstance); + } + + Element messageElement2 = XmlUtility.getElementByTagNameNS(formattedMessageElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement2 != null) { + String messageInstance2; + messageInstance2 = messageElement2.getTextContent(); + formattedMessageInstance.setMessage(messageInstance2); + } + } + } + + Element resourceExtensionStatusListSequenceElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatusList"); + if (resourceExtensionStatusListSequenceElement != null) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatus").size(); i4 = i4 + 1) { + org.w3c.dom.Element resourceExtensionStatusListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatus").get(i4)); + ResourceExtensionStatus resourceExtensionStatusInstance = new ResourceExtensionStatus(); + roleInstanceInstance.getResourceExtensionStatusList().add(resourceExtensionStatusInstance); + + Element handlerNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "HandlerName"); + if (handlerNameElement != null) { + String handlerNameInstance; + handlerNameInstance = handlerNameElement.getTextContent(); + resourceExtensionStatusInstance.setHandlerName(handlerNameInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + resourceExtensionStatusInstance.setVersion(versionInstance); + } + + Element statusElement3 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement3 != null) { + String statusInstance3; + statusInstance3 = statusElement3.getTextContent(); + resourceExtensionStatusInstance.setStatus(statusInstance3); + } + + Element codeElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement2 != null && (codeElement2.getTextContent() == null || codeElement2.getTextContent().isEmpty() == true) == false) { + int codeInstance2; + codeInstance2 = DatatypeConverter.parseInt(codeElement2.getTextContent()); + resourceExtensionStatusInstance.setCode(codeInstance2); + } + + Element messageElement3 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement3 != null) { + GuestAgentMessage messageInstance3 = new GuestAgentMessage(); + resourceExtensionStatusInstance.setMessage(messageInstance3); + + Element messageResourceIdElement2 = XmlUtility.getElementByTagNameNS(messageElement3, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement2 != null) { + String messageResourceIdInstance2; + messageResourceIdInstance2 = messageResourceIdElement2.getTextContent(); + messageInstance3.setMessageResourceId(messageResourceIdInstance2); + } + + Element paramListSequenceElement2 = XmlUtility.getElementByTagNameNS(messageElement3, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement2 != null) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Param").size(); i5 = i5 + 1) { + org.w3c.dom.Element paramListElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Param").get(i5)); + messageInstance3.getParamList().add(paramListElement2.getTextContent()); + } + } + } + + Element formattedMessageElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement2 != null) { + GuestAgentFormattedMessage formattedMessageInstance2 = new GuestAgentFormattedMessage(); + resourceExtensionStatusInstance.setFormattedMessage(formattedMessageInstance2); + + Element languageElement2 = XmlUtility.getElementByTagNameNS(formattedMessageElement2, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement2 != null) { + String languageInstance2; + languageInstance2 = languageElement2.getTextContent(); + formattedMessageInstance2.setLanguage(languageInstance2); + } + + Element messageElement4 = XmlUtility.getElementByTagNameNS(formattedMessageElement2, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement4 != null) { + String messageInstance4; + messageInstance4 = messageElement4.getTextContent(); + formattedMessageInstance2.setMessage(messageInstance4); + } + } + + Element extensionSettingStatusElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "ExtensionSettingStatus"); + if (extensionSettingStatusElement != null) { + ResourceExtensionConfigurationStatus extensionSettingStatusInstance = new ResourceExtensionConfigurationStatus(); + resourceExtensionStatusInstance.setExtensionSettingStatus(extensionSettingStatusInstance); + + Element timestampElement2 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement2 != null && (timestampElement2.getTextContent() == null || timestampElement2.getTextContent().isEmpty() == true) == false) { + Calendar timestampInstance2; + timestampInstance2 = DatatypeConverter.parseDateTime(timestampElement2.getTextContent()); + extensionSettingStatusInstance.setTimestamp(timestampInstance2); + } + + Element configurationAppliedTimeElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationAppliedTime"); + if (configurationAppliedTimeElement != null && (configurationAppliedTimeElement.getTextContent() == null || configurationAppliedTimeElement.getTextContent().isEmpty() == true) == false) { + Calendar configurationAppliedTimeInstance; + configurationAppliedTimeInstance = DatatypeConverter.parseDateTime(configurationAppliedTimeElement.getTextContent()); + extensionSettingStatusInstance.setConfigurationAppliedTime(configurationAppliedTimeInstance); + } + + Element nameElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement3 != null) { + String nameInstance3; + nameInstance3 = nameElement3.getTextContent(); + extensionSettingStatusInstance.setName(nameInstance3); + } + + Element operationElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + String operationInstance; + operationInstance = operationElement.getTextContent(); + extensionSettingStatusInstance.setOperation(operationInstance); + } + + Element statusElement4 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement4 != null) { + String statusInstance4; + statusInstance4 = statusElement4.getTextContent(); + extensionSettingStatusInstance.setStatus(statusInstance4); + } + + Element codeElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement3 != null && (codeElement3.getTextContent() == null || codeElement3.getTextContent().isEmpty() == true) == false) { + int codeInstance3; + codeInstance3 = DatatypeConverter.parseInt(codeElement3.getTextContent()); + extensionSettingStatusInstance.setCode(codeInstance3); + } + + Element messageElement5 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement5 != null) { + GuestAgentMessage messageInstance5 = new GuestAgentMessage(); + extensionSettingStatusInstance.setMessage(messageInstance5); + + Element messageResourceIdElement3 = XmlUtility.getElementByTagNameNS(messageElement5, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement3 != null) { + String messageResourceIdInstance3; + messageResourceIdInstance3 = messageResourceIdElement3.getTextContent(); + messageInstance5.setMessageResourceId(messageResourceIdInstance3); + } + + Element paramListSequenceElement3 = XmlUtility.getElementByTagNameNS(messageElement5, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement3 != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement3, "http://schemas.microsoft.com/windowsazure", "Param").size(); i6 = i6 + 1) { + org.w3c.dom.Element paramListElement3 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement3, "http://schemas.microsoft.com/windowsazure", "Param").get(i6)); + messageInstance5.getParamList().add(paramListElement3.getTextContent()); + } + } + } + + Element formattedMessageElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement3 != null) { + GuestAgentFormattedMessage formattedMessageInstance3 = new GuestAgentFormattedMessage(); + extensionSettingStatusInstance.setFormattedMessage(formattedMessageInstance3); + + Element languageElement3 = XmlUtility.getElementByTagNameNS(formattedMessageElement3, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement3 != null) { + String languageInstance3; + languageInstance3 = languageElement3.getTextContent(); + formattedMessageInstance3.setLanguage(languageInstance3); + } + + Element messageElement6 = XmlUtility.getElementByTagNameNS(formattedMessageElement3, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement6 != null) { + String messageInstance6; + messageInstance6 = messageElement6.getTextContent(); + formattedMessageInstance3.setMessage(messageInstance6); + } + } + + Element subStatusListSequenceElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "SubStatusList"); + if (subStatusListSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubStatus").size(); i7 = i7 + 1) { + org.w3c.dom.Element subStatusListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubStatus").get(i7)); + ResourceExtensionSubStatus subStatusInstance = new ResourceExtensionSubStatus(); + extensionSettingStatusInstance.getSubStatusList().add(subStatusInstance); + + Element nameElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement4 != null) { + String nameInstance4; + nameInstance4 = nameElement4.getTextContent(); + subStatusInstance.setName(nameInstance4); + } + + Element statusElement5 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement5 != null) { + String statusInstance5; + statusInstance5 = statusElement5.getTextContent(); + subStatusInstance.setStatus(statusInstance5); + } + + Element codeElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement4 != null && (codeElement4.getTextContent() == null || codeElement4.getTextContent().isEmpty() == true) == false) { + int codeInstance4; + codeInstance4 = DatatypeConverter.parseInt(codeElement4.getTextContent()); + subStatusInstance.setCode(codeInstance4); + } + + Element messageElement7 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement7 != null) { + GuestAgentMessage messageInstance7 = new GuestAgentMessage(); + subStatusInstance.setMessage(messageInstance7); + + Element messageResourceIdElement4 = XmlUtility.getElementByTagNameNS(messageElement7, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement4 != null) { + String messageResourceIdInstance4; + messageResourceIdInstance4 = messageResourceIdElement4.getTextContent(); + messageInstance7.setMessageResourceId(messageResourceIdInstance4); + } + + Element paramListSequenceElement4 = XmlUtility.getElementByTagNameNS(messageElement7, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement4 != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement4, "http://schemas.microsoft.com/windowsazure", "Param").size(); i8 = i8 + 1) { + org.w3c.dom.Element paramListElement4 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement4, "http://schemas.microsoft.com/windowsazure", "Param").get(i8)); + messageInstance7.getParamList().add(paramListElement4.getTextContent()); + } + } + } + + Element formattedMessageElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement4 != null) { + GuestAgentFormattedMessage formattedMessageInstance4 = new GuestAgentFormattedMessage(); + subStatusInstance.setFormattedMessage(formattedMessageInstance4); + + Element languageElement4 = XmlUtility.getElementByTagNameNS(formattedMessageElement4, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement4 != null) { + String languageInstance4; + languageInstance4 = languageElement4.getTextContent(); + formattedMessageInstance4.setLanguage(languageInstance4); + } + + Element messageElement8 = XmlUtility.getElementByTagNameNS(formattedMessageElement4, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement8 != null) { + String messageInstance8; + messageInstance8 = messageElement8.getTextContent(); + formattedMessageInstance4.setMessage(messageInstance8); + } + } + } + } + } + } + } + + Element powerStateElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "PowerState"); + if (powerStateElement != null) { + RoleInstancePowerState powerStateInstance; + powerStateInstance = RoleInstancePowerState.valueOf(powerStateElement.getTextContent()); + roleInstanceInstance.setPowerState(powerStateInstance); + } + + Element hostNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "HostName"); + if (hostNameElement != null) { + String hostNameInstance; + hostNameInstance = hostNameElement.getTextContent(); + roleInstanceInstance.setHostName(hostNameInstance); + } + + Element remoteAccessCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "RemoteAccessCertificateThumbprint"); + if (remoteAccessCertificateThumbprintElement != null) { + String remoteAccessCertificateThumbprintInstance; + remoteAccessCertificateThumbprintInstance = remoteAccessCertificateThumbprintElement.getTextContent(); + roleInstanceInstance.setRemoteAccessCertificateThumbprint(remoteAccessCertificateThumbprintInstance); + } + } + } + + Element upgradeStatusElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "UpgradeStatus"); + if (upgradeStatusElement != null) { + UpgradeStatus upgradeStatusInstance = new UpgradeStatus(); + result.setUpgradeStatus(upgradeStatusInstance); + + Element upgradeTypeElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "UpgradeType"); + if (upgradeTypeElement != null) { + DeploymentUpgradeType upgradeTypeInstance; + upgradeTypeInstance = DeploymentUpgradeType.valueOf(upgradeTypeElement.getTextContent()); + upgradeStatusInstance.setUpgradeType(upgradeTypeInstance); + } + + Element currentUpgradeDomainStateElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "CurrentUpgradeDomainState"); + if (currentUpgradeDomainStateElement != null) { + UpgradeDomainState currentUpgradeDomainStateInstance; + currentUpgradeDomainStateInstance = UpgradeDomainState.valueOf(currentUpgradeDomainStateElement.getTextContent()); + upgradeStatusInstance.setCurrentUpgradeDomainState(currentUpgradeDomainStateInstance); + } + + Element currentUpgradeDomainElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "CurrentUpgradeDomain"); + if (currentUpgradeDomainElement != null) { + int currentUpgradeDomainInstance; + currentUpgradeDomainInstance = DatatypeConverter.parseInt(currentUpgradeDomainElement.getTextContent()); + upgradeStatusInstance.setCurrentUpgradeDomain(currentUpgradeDomainInstance); + } + } + + Element upgradeDomainCountElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "UpgradeDomainCount"); + if (upgradeDomainCountElement != null) { + int upgradeDomainCountInstance; + upgradeDomainCountInstance = DatatypeConverter.parseInt(upgradeDomainCountElement.getTextContent()); + result.setUpgradeDomainCount(upgradeDomainCountInstance); + } + + Element roleListSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "RoleList"); + if (roleListSequenceElement != null) { + for (int i9 = 0; i9 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").size(); i9 = i9 + 1) { + org.w3c.dom.Element roleListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").get(i9)); + Role roleInstance = new Role(); + result.getRoles().add(roleInstance); + + Element roleNameElement2 = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement2 != null) { + String roleNameInstance2; + roleNameInstance2 = roleNameElement2.getTextContent(); + roleInstance.setRoleName(roleNameInstance2); + } + + Element osVersionElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "OsVersion"); + if (osVersionElement != null) { + String osVersionInstance; + osVersionInstance = osVersionElement.getTextContent(); + roleInstance.setOSVersion(osVersionInstance); + } + + Element roleTypeElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleType"); + if (roleTypeElement != null) { + String roleTypeInstance; + roleTypeInstance = roleTypeElement.getTextContent(); + roleInstance.setRoleType(roleTypeInstance); + } + + Element configurationSetsSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSets"); + if (configurationSetsSequenceElement != null) { + for (int i10 = 0; i10 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").size(); i10 = i10 + 1) { + org.w3c.dom.Element configurationSetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").get(i10)); + ConfigurationSet configurationSetInstance = new ConfigurationSet(); + roleInstance.getConfigurationSets().add(configurationSetInstance); + + Element configurationSetTypeElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + if (configurationSetTypeElement != null) { + String configurationSetTypeInstance; + configurationSetTypeInstance = configurationSetTypeElement.getTextContent(); + configurationSetInstance.setConfigurationSetType(configurationSetTypeInstance); + } + + Element inputEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + if (inputEndpointsSequenceElement != null) { + for (int i11 = 0; i11 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").size(); i11 = i11 + 1) { + org.w3c.dom.Element inputEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").get(i11)); + InputEndpoint inputEndpointInstance = new InputEndpoint(); + configurationSetInstance.getInputEndpoints().add(inputEndpointInstance); + + Element loadBalancedEndpointSetNameElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + if (loadBalancedEndpointSetNameElement != null) { + String loadBalancedEndpointSetNameInstance; + loadBalancedEndpointSetNameInstance = loadBalancedEndpointSetNameElement.getTextContent(); + inputEndpointInstance.setLoadBalancedEndpointSetName(loadBalancedEndpointSetNameInstance); + } + + Element localPortElement2 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LocalPort"); + if (localPortElement2 != null && (localPortElement2.getTextContent() == null || localPortElement2.getTextContent().isEmpty() == true) == false) { + int localPortInstance2; + localPortInstance2 = DatatypeConverter.parseInt(localPortElement2.getTextContent()); + inputEndpointInstance.setLocalPort(localPortInstance2); + } + + Element nameElement5 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement5 != null) { + String nameInstance5; + nameInstance5 = nameElement5.getTextContent(); + inputEndpointInstance.setName(nameInstance5); + } + + Element portElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement != null && (portElement.getTextContent() == null || portElement.getTextContent().isEmpty() == true) == false) { + int portInstance; + portInstance = DatatypeConverter.parseInt(portElement.getTextContent()); + inputEndpointInstance.setPort(portInstance); + } + + Element loadBalancerProbeElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + if (loadBalancerProbeElement != null) { + LoadBalancerProbe loadBalancerProbeInstance = new LoadBalancerProbe(); + inputEndpointInstance.setLoadBalancerProbe(loadBalancerProbeInstance); + + Element pathElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement != null) { + String pathInstance; + pathInstance = pathElement.getTextContent(); + loadBalancerProbeInstance.setPath(pathInstance); + } + + Element portElement2 = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement2 != null) { + int portInstance2; + portInstance2 = DatatypeConverter.parseInt(portElement2.getTextContent()); + loadBalancerProbeInstance.setPort(portInstance2); + } + + Element protocolElement2 = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement2 != null) { + LoadBalancerProbeTransportProtocol protocolInstance2; + protocolInstance2 = com.microsoft.windowsazure.management.compute.ComputeManagementClientImpl.parseLoadBalancerProbeTransportProtocol(protocolElement2.getTextContent()); + loadBalancerProbeInstance.setProtocol(protocolInstance2); + } + + Element intervalInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + if (intervalInSecondsElement != null && (intervalInSecondsElement.getTextContent() == null || intervalInSecondsElement.getTextContent().isEmpty() == true) == false) { + int intervalInSecondsInstance; + intervalInSecondsInstance = DatatypeConverter.parseInt(intervalInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setIntervalInSeconds(intervalInSecondsInstance); + } + + Element timeoutInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + if (timeoutInSecondsElement != null && (timeoutInSecondsElement.getTextContent() == null || timeoutInSecondsElement.getTextContent().isEmpty() == true) == false) { + int timeoutInSecondsInstance; + timeoutInSecondsInstance = DatatypeConverter.parseInt(timeoutInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setTimeoutInSeconds(timeoutInSecondsInstance); + } + } + + Element protocolElement3 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement3 != null) { + String protocolInstance3; + protocolInstance3 = protocolElement3.getTextContent(); + inputEndpointInstance.setProtocol(protocolInstance3); + } + + Element vipElement2 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Vip"); + if (vipElement2 != null) { + InetAddress vipInstance2; + vipInstance2 = InetAddress.getByName(vipElement2.getTextContent()); + inputEndpointInstance.setVirtualIPAddress(vipInstance2); + } + + Element enableDirectServerReturnElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + if (enableDirectServerReturnElement != null && (enableDirectServerReturnElement.getTextContent() == null || enableDirectServerReturnElement.getTextContent().isEmpty() == true) == false) { + boolean enableDirectServerReturnInstance; + enableDirectServerReturnInstance = DatatypeConverter.parseBoolean(enableDirectServerReturnElement.getTextContent().toLowerCase()); + inputEndpointInstance.setEnableDirectServerReturn(enableDirectServerReturnInstance); + } + + Element endpointAclElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + if (endpointAclElement != null) { + EndpointAcl endpointAclInstance = new EndpointAcl(); + inputEndpointInstance.setEndpointAcl(endpointAclInstance); + + Element rulesSequenceElement = XmlUtility.getElementByTagNameNS(endpointAclElement, "http://schemas.microsoft.com/windowsazure", "Rules"); + if (rulesSequenceElement != null) { + for (int i12 = 0; i12 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").size(); i12 = i12 + 1) { + org.w3c.dom.Element rulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").get(i12)); + AccessControlListRule ruleInstance = new AccessControlListRule(); + endpointAclInstance.getRules().add(ruleInstance); + + Element orderElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Order"); + if (orderElement != null && (orderElement.getTextContent() == null || orderElement.getTextContent().isEmpty() == true) == false) { + int orderInstance; + orderInstance = DatatypeConverter.parseInt(orderElement.getTextContent()); + ruleInstance.setOrder(orderInstance); + } + + Element actionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Action"); + if (actionElement != null) { + String actionInstance; + actionInstance = actionElement.getTextContent(); + ruleInstance.setAction(actionInstance); + } + + Element remoteSubnetElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + if (remoteSubnetElement != null) { + String remoteSubnetInstance; + remoteSubnetInstance = remoteSubnetElement.getTextContent(); + ruleInstance.setRemoteSubnet(remoteSubnetInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + ruleInstance.setDescription(descriptionInstance); + } + } + } + } + } + } + + Element subnetNamesSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SubnetNames"); + if (subnetNamesSequenceElement != null) { + for (int i13 = 0; i13 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").size(); i13 = i13 + 1) { + org.w3c.dom.Element subnetNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").get(i13)); + configurationSetInstance.getSubnetNames().add(subnetNamesElement.getTextContent()); + } + } + + Element staticVirtualNetworkIPAddressElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + if (staticVirtualNetworkIPAddressElement != null) { + String staticVirtualNetworkIPAddressInstance; + staticVirtualNetworkIPAddressInstance = staticVirtualNetworkIPAddressElement.getTextContent(); + configurationSetInstance.setStaticVirtualNetworkIPAddress(staticVirtualNetworkIPAddressInstance); + } + + Element computerNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ComputerName"); + if (computerNameElement != null) { + String computerNameInstance; + computerNameInstance = computerNameElement.getTextContent(); + configurationSetInstance.setComputerName(computerNameInstance); + } + + Element adminPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminPassword"); + if (adminPasswordElement != null) { + String adminPasswordInstance; + adminPasswordInstance = adminPasswordElement.getTextContent(); + configurationSetInstance.setAdminPassword(adminPasswordInstance); + } + + Element resetPasswordOnFirstLogonElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + if (resetPasswordOnFirstLogonElement != null && (resetPasswordOnFirstLogonElement.getTextContent() == null || resetPasswordOnFirstLogonElement.getTextContent().isEmpty() == true) == false) { + boolean resetPasswordOnFirstLogonInstance; + resetPasswordOnFirstLogonInstance = DatatypeConverter.parseBoolean(resetPasswordOnFirstLogonElement.getTextContent().toLowerCase()); + configurationSetInstance.setResetPasswordOnFirstLogon(resetPasswordOnFirstLogonInstance); + } + + Element enableAutomaticUpdatesElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + if (enableAutomaticUpdatesElement != null && (enableAutomaticUpdatesElement.getTextContent() == null || enableAutomaticUpdatesElement.getTextContent().isEmpty() == true) == false) { + boolean enableAutomaticUpdatesInstance; + enableAutomaticUpdatesInstance = DatatypeConverter.parseBoolean(enableAutomaticUpdatesElement.getTextContent().toLowerCase()); + configurationSetInstance.setEnableAutomaticUpdates(enableAutomaticUpdatesInstance); + } + + Element timeZoneElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "TimeZone"); + if (timeZoneElement != null) { + String timeZoneInstance; + timeZoneInstance = timeZoneElement.getTextContent(); + configurationSetInstance.setTimeZone(timeZoneInstance); + } + + Element domainJoinElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DomainJoin"); + if (domainJoinElement != null) { + DomainJoinSettings domainJoinInstance = new DomainJoinSettings(); + configurationSetInstance.setDomainJoin(domainJoinInstance); + + Element credentialsElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Credentials"); + if (credentialsElement != null) { + DomainJoinCredentials credentialsInstance = new DomainJoinCredentials(); + domainJoinInstance.setCredentials(credentialsInstance); + + Element domainElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Domain"); + if (domainElement != null) { + String domainInstance; + domainInstance = domainElement.getTextContent(); + credentialsInstance.setDomain(domainInstance); + } + + Element usernameElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Username"); + if (usernameElement != null) { + String usernameInstance; + usernameInstance = usernameElement.getTextContent(); + credentialsInstance.setUserName(usernameInstance); + } + + Element passwordElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement != null) { + String passwordInstance; + passwordInstance = passwordElement.getTextContent(); + credentialsInstance.setPassword(passwordInstance); + } + } + + Element joinDomainElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "JoinDomain"); + if (joinDomainElement != null) { + String joinDomainInstance; + joinDomainInstance = joinDomainElement.getTextContent(); + domainJoinInstance.setDomainToJoin(joinDomainInstance); + } + + Element machineObjectOUElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + if (machineObjectOUElement != null) { + String machineObjectOUInstance; + machineObjectOUInstance = machineObjectOUElement.getTextContent(); + domainJoinInstance.setLdapMachineObjectOU(machineObjectOUInstance); + } + + Element provisioningElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Provisioning"); + if (provisioningElement != null) { + DomainJoinProvisioning provisioningInstance = new DomainJoinProvisioning(); + domainJoinInstance.setProvisioning(provisioningInstance); + + Element accountDataElement = XmlUtility.getElementByTagNameNS(provisioningElement, "http://schemas.microsoft.com/windowsazure", "AccountData"); + if (accountDataElement != null) { + String accountDataInstance; + accountDataInstance = accountDataElement.getTextContent(); + provisioningInstance.setAccountData(accountDataInstance); + } + } + } + + Element storedCertificateSettingsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + if (storedCertificateSettingsSequenceElement != null) { + for (int i14 = 0; i14 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").size(); i14 = i14 + 1) { + org.w3c.dom.Element storedCertificateSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").get(i14)); + StoredCertificateSettings certificateSettingInstance = new StoredCertificateSettings(); + configurationSetInstance.getStoredCertificateSettings().add(certificateSettingInstance); + + Element storeLocationElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreLocation"); + if (storeLocationElement != null) { + } + + Element storeNameElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreName"); + if (storeNameElement != null) { + String storeNameInstance; + storeNameInstance = storeNameElement.getTextContent(); + certificateSettingInstance.setStoreName(storeNameInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + certificateSettingInstance.setThumbprint(thumbprintInstance); + } + } + } + + Element winRMElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "WinRM"); + if (winRMElement != null) { + WindowsRemoteManagementSettings winRMInstance = new WindowsRemoteManagementSettings(); + configurationSetInstance.setWindowsRemoteManagement(winRMInstance); + + Element listenersSequenceElement = XmlUtility.getElementByTagNameNS(winRMElement, "http://schemas.microsoft.com/windowsazure", "Listeners"); + if (listenersSequenceElement != null) { + for (int i15 = 0; i15 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").size(); i15 = i15 + 1) { + org.w3c.dom.Element listenersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").get(i15)); + WindowsRemoteManagementListener listenerInstance = new WindowsRemoteManagementListener(); + winRMInstance.getListeners().add(listenerInstance); + + Element protocolElement4 = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement4 != null) { + VirtualMachineWindowsRemoteManagementListenerType protocolInstance4; + protocolInstance4 = VirtualMachineWindowsRemoteManagementListenerType.valueOf(protocolElement4.getTextContent()); + listenerInstance.setListenerType(protocolInstance4); + } + + Element certificateThumbprintElement = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + if (certificateThumbprintElement != null) { + String certificateThumbprintInstance; + certificateThumbprintInstance = certificateThumbprintElement.getTextContent(); + listenerInstance.setCertificateThumbprint(certificateThumbprintInstance); + } + } + } + } + + Element adminUsernameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminUsername"); + if (adminUsernameElement != null) { + String adminUsernameInstance; + adminUsernameInstance = adminUsernameElement.getTextContent(); + configurationSetInstance.setAdminUserName(adminUsernameInstance); + } + + Element hostNameElement2 = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "HostName"); + if (hostNameElement2 != null) { + String hostNameInstance2; + hostNameInstance2 = hostNameElement2.getTextContent(); + configurationSetInstance.setHostName(hostNameInstance2); + } + + Element userNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserName"); + if (userNameElement != null) { + String userNameInstance; + userNameInstance = userNameElement.getTextContent(); + configurationSetInstance.setUserName(userNameInstance); + } + + Element userPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserPassword"); + if (userPasswordElement != null) { + String userPasswordInstance; + userPasswordInstance = userPasswordElement.getTextContent(); + configurationSetInstance.setUserPassword(userPasswordInstance); + } + + Element disableSshPasswordAuthenticationElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + if (disableSshPasswordAuthenticationElement != null && (disableSshPasswordAuthenticationElement.getTextContent() == null || disableSshPasswordAuthenticationElement.getTextContent().isEmpty() == true) == false) { + boolean disableSshPasswordAuthenticationInstance; + disableSshPasswordAuthenticationInstance = DatatypeConverter.parseBoolean(disableSshPasswordAuthenticationElement.getTextContent().toLowerCase()); + configurationSetInstance.setDisableSshPasswordAuthentication(disableSshPasswordAuthenticationInstance); + } + + Element sSHElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SSH"); + if (sSHElement != null) { + SshSettings sSHInstance = new SshSettings(); + configurationSetInstance.setSshSettings(sSHInstance); + + Element publicKeysSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "PublicKeys"); + if (publicKeysSequenceElement != null) { + for (int i16 = 0; i16 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").size(); i16 = i16 + 1) { + org.w3c.dom.Element publicKeysElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").get(i16)); + SshSettingPublicKey publicKeyInstance = new SshSettingPublicKey(); + sSHInstance.getPublicKeys().add(publicKeyInstance); + + Element fingerprintElement = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement != null) { + String fingerprintInstance; + fingerprintInstance = fingerprintElement.getTextContent(); + publicKeyInstance.setFingerprint(fingerprintInstance); + } + + Element pathElement2 = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement2 != null) { + String pathInstance2; + pathInstance2 = pathElement2.getTextContent(); + publicKeyInstance.setPath(pathInstance2); + } + } + } + + Element keyPairsSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "KeyPairs"); + if (keyPairsSequenceElement != null) { + for (int i17 = 0; i17 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").size(); i17 = i17 + 1) { + org.w3c.dom.Element keyPairsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").get(i17)); + SshSettingKeyPair keyPairInstance = new SshSettingKeyPair(); + sSHInstance.getKeyPairs().add(keyPairInstance); + + Element fingerprintElement2 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement2 != null) { + String fingerprintInstance2; + fingerprintInstance2 = fingerprintElement2.getTextContent(); + keyPairInstance.setFingerprint(fingerprintInstance2); + } + + Element pathElement3 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement3 != null) { + String pathInstance3; + pathInstance3 = pathElement3.getTextContent(); + keyPairInstance.setPath(pathInstance3); + } + } + } + } + + Element customDataElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "CustomData"); + if (customDataElement != null) { + String customDataInstance; + customDataInstance = customDataElement.getTextContent(); + configurationSetInstance.setCustomData(customDataInstance); + } + } + } + + Element resourceExtensionReferencesSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences"); + if (resourceExtensionReferencesSequenceElement != null) { + for (int i18 = 0; i18 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionReferencesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference").size(); i18 = i18 + 1) { + org.w3c.dom.Element resourceExtensionReferencesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionReferencesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference").get(i18)); + ResourceExtensionReference resourceExtensionReferenceInstance = new ResourceExtensionReference(); + roleInstance.getResourceExtensionReferences().add(resourceExtensionReferenceInstance); + + Element referenceNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "ReferenceName"); + if (referenceNameElement != null) { + String referenceNameInstance; + referenceNameInstance = referenceNameElement.getTextContent(); + resourceExtensionReferenceInstance.setReferenceName(referenceNameInstance); + } + + Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Publisher"); + if (publisherElement != null) { + String publisherInstance; + publisherInstance = publisherElement.getTextContent(); + resourceExtensionReferenceInstance.setPublisher(publisherInstance); + } + + Element nameElement6 = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement6 != null) { + String nameInstance6; + nameInstance6 = nameElement6.getTextContent(); + resourceExtensionReferenceInstance.setName(nameInstance6); + } + + Element versionElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement2 != null) { + String versionInstance2; + versionInstance2 = versionElement2.getTextContent(); + resourceExtensionReferenceInstance.setVersion(versionInstance2); + } + + Element resourceExtensionParameterValuesSequenceElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValues"); + if (resourceExtensionParameterValuesSequenceElement != null) { + for (int i19 = 0; i19 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionParameterValuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue").size(); i19 = i19 + 1) { + org.w3c.dom.Element resourceExtensionParameterValuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionParameterValuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue").get(i19)); + ResourceExtensionParameterValue resourceExtensionParameterValueInstance = new ResourceExtensionParameterValue(); + resourceExtensionReferenceInstance.getResourceExtensionParameterValues().add(resourceExtensionParameterValueInstance); + + Element keyElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Key"); + if (keyElement != null) { + String keyInstance; + keyInstance = keyElement.getTextContent(); + resourceExtensionParameterValueInstance.setKey(keyInstance); + } + + Element valueElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Value"); + if (valueElement != null) { + String valueInstance; + valueInstance = valueElement.getTextContent() != null ? new String(Base64.decode(valueElement.getTextContent())) : null; + resourceExtensionParameterValueInstance.setValue(valueInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + resourceExtensionParameterValueInstance.setType(typeInstance); + } + } + } + + Element stateElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + resourceExtensionReferenceInstance.setState(stateInstance); + } + } + } + + Element vMImageNameElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "VMImageName"); + if (vMImageNameElement != null) { + String vMImageNameInstance; + vMImageNameInstance = vMImageNameElement.getTextContent(); + roleInstance.setVMImageName(vMImageNameInstance); + } + + Element availabilitySetNameElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "AvailabilitySetName"); + if (availabilitySetNameElement != null) { + String availabilitySetNameInstance; + availabilitySetNameInstance = availabilitySetNameElement.getTextContent(); + roleInstance.setAvailabilitySetName(availabilitySetNameInstance); + } + + Element dataVirtualHardDisksSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks"); + if (dataVirtualHardDisksSequenceElement != null) { + for (int i20 = 0; i20 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").size(); i20 = i20 + 1) { + org.w3c.dom.Element dataVirtualHardDisksElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").get(i20)); + DataVirtualHardDisk dataVirtualHardDiskInstance = new DataVirtualHardDisk(); + roleInstance.getDataVirtualHardDisks().add(dataVirtualHardDiskInstance); + + Element hostCachingElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement != null && (hostCachingElement.getTextContent() == null || hostCachingElement.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance; + hostCachingInstance = VirtualHardDiskHostCaching.valueOf(hostCachingElement.getTextContent()); + dataVirtualHardDiskInstance.setHostCaching(hostCachingInstance); + } + + Element diskLabelElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement != null) { + String diskLabelInstance; + diskLabelInstance = diskLabelElement.getTextContent(); + dataVirtualHardDiskInstance.setLabel(diskLabelInstance); + } + + Element diskNameElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement != null) { + String diskNameInstance; + diskNameInstance = diskNameElement.getTextContent(); + dataVirtualHardDiskInstance.setName(diskNameInstance); + } + + Element lunElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "Lun"); + if (lunElement != null && (lunElement.getTextContent() == null || lunElement.getTextContent().isEmpty() == true) == false) { + int lunInstance; + lunInstance = DatatypeConverter.parseInt(lunElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalUnitNumber(lunInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null && (logicalDiskSizeInGBElement.getTextContent() == null || logicalDiskSizeInGBElement.getTextContent().isEmpty() == true) == false) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setMediaLink(mediaLinkInstance); + } + + Element sourceMediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + if (sourceMediaLinkElement != null) { + URI sourceMediaLinkInstance; + sourceMediaLinkInstance = new URI(sourceMediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setSourceMediaLink(sourceMediaLinkInstance); + } + } + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance2; + labelInstance2 = labelElement2.getTextContent(); + roleInstance.setLabel(labelInstance2); + } + + Element oSVirtualHardDiskElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk"); + if (oSVirtualHardDiskElement != null) { + OSVirtualHardDisk oSVirtualHardDiskInstance = new OSVirtualHardDisk(); + roleInstance.setOSVirtualHardDisk(oSVirtualHardDiskInstance); + + Element hostCachingElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement2 != null && (hostCachingElement2.getTextContent() == null || hostCachingElement2.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance2; + hostCachingInstance2 = VirtualHardDiskHostCaching.valueOf(hostCachingElement2.getTextContent()); + oSVirtualHardDiskInstance.setHostCaching(hostCachingInstance2); + } + + Element diskLabelElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement2 != null) { + String diskLabelInstance2; + diskLabelInstance2 = diskLabelElement2.getTextContent(); + oSVirtualHardDiskInstance.setLabel(diskLabelInstance2); + } + + Element diskNameElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement2 != null) { + String diskNameInstance2; + diskNameInstance2 = diskNameElement2.getTextContent(); + oSVirtualHardDiskInstance.setName(diskNameInstance2); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance2; + mediaLinkInstance2 = new URI(mediaLinkElement2.getTextContent()); + oSVirtualHardDiskInstance.setMediaLink(mediaLinkInstance2); + } + + Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); + if (sourceImageNameElement != null) { + String sourceImageNameInstance; + sourceImageNameInstance = sourceImageNameElement.getTextContent(); + oSVirtualHardDiskInstance.setSourceImageName(sourceImageNameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + oSVirtualHardDiskInstance.setOperatingSystem(osInstance); + } + } + + Element roleSizeElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleSize"); + if (roleSizeElement != null) { + String roleSizeInstance; + roleSizeInstance = roleSizeElement.getTextContent(); + roleInstance.setRoleSize(roleSizeInstance); + } + + Element provisionGuestAgentElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent"); + if (provisionGuestAgentElement != null && (provisionGuestAgentElement.getTextContent() == null || provisionGuestAgentElement.getTextContent().isEmpty() == true) == false) { + boolean provisionGuestAgentInstance; + provisionGuestAgentInstance = DatatypeConverter.parseBoolean(provisionGuestAgentElement.getTextContent().toLowerCase()); + roleInstance.setProvisionGuestAgent(provisionGuestAgentInstance); + } + + Element defaultWinRmCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "DefaultWinRmCertificateThumbprint"); + if (defaultWinRmCertificateThumbprintElement != null) { + String defaultWinRmCertificateThumbprintInstance; + defaultWinRmCertificateThumbprintInstance = defaultWinRmCertificateThumbprintElement.getTextContent(); + roleInstance.setDefaultWinRmCertificateThumbprint(defaultWinRmCertificateThumbprintInstance); + } + } + } + + Element sdkVersionElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "SdkVersion"); + if (sdkVersionElement != null) { + String sdkVersionInstance; + sdkVersionInstance = sdkVersionElement.getTextContent(); + result.setSdkVersion(sdkVersionInstance); + } + + Element lockedElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Locked"); + if (lockedElement != null) { + boolean lockedInstance; + lockedInstance = DatatypeConverter.parseBoolean(lockedElement.getTextContent().toLowerCase()); + result.setLocked(lockedInstance); + } + + Element rollbackAllowedElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "RollbackAllowed"); + if (rollbackAllowedElement != null) { + boolean rollbackAllowedInstance; + rollbackAllowedInstance = DatatypeConverter.parseBoolean(rollbackAllowedElement.getTextContent().toLowerCase()); + result.setRollbackAllowed(rollbackAllowedInstance); + } + + Element createdTimeElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); + if (createdTimeElement != null) { + Calendar createdTimeInstance; + createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); + result.setCreatedTime(createdTimeInstance); + } + + Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "LastModifiedTime"); + if (lastModifiedTimeElement != null) { + Calendar lastModifiedTimeInstance; + lastModifiedTimeInstance = DatatypeConverter.parseDateTime(lastModifiedTimeElement.getTextContent()); + result.setLastModifiedTime(lastModifiedTimeInstance); + } + + Element virtualNetworkNameElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "VirtualNetworkName"); + if (virtualNetworkNameElement != null) { + String virtualNetworkNameInstance; + virtualNetworkNameInstance = virtualNetworkNameElement.getTextContent(); + result.setVirtualNetworkName(virtualNetworkNameInstance); + } + + Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement != null) { + for (int i21 = 0; i21 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i21 = i21 + 1) { + org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i21)); + String extendedPropertiesKey = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + result.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); + } + } + + Element persistentVMDowntimeElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "PersistentVMDowntime"); + if (persistentVMDowntimeElement != null) { + PersistentVMDowntime persistentVMDowntimeInstance = new PersistentVMDowntime(); + result.setPersistentVMDowntime(persistentVMDowntimeInstance); + + Element startTimeElement = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); + if (startTimeElement != null) { + Calendar startTimeInstance; + startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); + persistentVMDowntimeInstance.setStartTime(startTimeInstance); + } + + Element endTimeElement = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "EndTime"); + if (endTimeElement != null) { + Calendar endTimeInstance; + endTimeInstance = DatatypeConverter.parseDateTime(endTimeElement.getTextContent()); + persistentVMDowntimeInstance.setEndTime(endTimeInstance); + } + + Element statusElement6 = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement6 != null) { + String statusInstance6; + statusInstance6 = statusElement6.getTextContent(); + persistentVMDowntimeInstance.setStatus(statusInstance6); + } + } + + Element virtualIPsSequenceElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "VirtualIPs"); + if (virtualIPsSequenceElement != null) { + for (int i22 = 0; i22 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP").size(); i22 = i22 + 1) { + org.w3c.dom.Element virtualIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP").get(i22)); + VirtualIPAddress virtualIPInstance = new VirtualIPAddress(); + result.getVirtualIPAddresses().add(virtualIPInstance); + + Element addressElement = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement != null) { + InetAddress addressInstance; + addressInstance = InetAddress.getByName(addressElement.getTextContent()); + virtualIPInstance.setAddress(addressInstance); + } + + Element nameElement7 = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement7 != null) { + String nameInstance7; + nameInstance7 = nameElement7.getTextContent(); + virtualIPInstance.setName(nameInstance7); + } + + Element isDnsProgrammedElement = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "IsDnsProgrammed"); + if (isDnsProgrammedElement != null && (isDnsProgrammedElement.getTextContent() == null || isDnsProgrammedElement.getTextContent().isEmpty() == true) == false) { + boolean isDnsProgrammedInstance; + isDnsProgrammedInstance = DatatypeConverter.parseBoolean(isDnsProgrammedElement.getTextContent().toLowerCase()); + virtualIPInstance.setIsDnsProgrammed(isDnsProgrammedInstance); + } + } + } + + Element reservedIPNameElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "ReservedIPName"); + if (reservedIPNameElement != null) { + String reservedIPNameInstance; + reservedIPNameInstance = reservedIPNameElement.getTextContent(); + result.setReservedIPName(reservedIPNameInstance); + } + + Element dnsElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "Dns"); + if (dnsElement != null) { + DnsSettings dnsInstance = new DnsSettings(); + result.setDnsSettings(dnsInstance); + + Element dnsServersSequenceElement = XmlUtility.getElementByTagNameNS(dnsElement, "http://schemas.microsoft.com/windowsazure", "DnsServers"); + if (dnsServersSequenceElement != null) { + for (int i23 = 0; i23 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").size(); i23 = i23 + 1) { + org.w3c.dom.Element dnsServersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").get(i23)); + DnsServer dnsServerInstance = new DnsServer(); + dnsInstance.getDnsServers().add(dnsServerInstance); + + Element nameElement8 = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement8 != null) { + String nameInstance8; + nameInstance8 = nameElement8.getTextContent(); + dnsServerInstance.setName(nameInstance8); + } + + Element addressElement2 = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement2 != null) { + InetAddress addressInstance2; + addressInstance2 = InetAddress.getByName(addressElement2.getTextContent()); + dnsServerInstance.setAddress(addressInstance2); + } + } + } + } + + Element extensionConfigurationElement = XmlUtility.getElementByTagNameNS(deploymentElement, "http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration"); + if (extensionConfigurationElement != null) { + ExtensionConfiguration extensionConfigurationInstance = new ExtensionConfiguration(); + result.setExtensionConfiguration(extensionConfigurationInstance); + + Element allRolesSequenceElement = XmlUtility.getElementByTagNameNS(extensionConfigurationElement, "http://schemas.microsoft.com/windowsazure", "AllRoles"); + if (allRolesSequenceElement != null) { + for (int i24 = 0; i24 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(allRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").size(); i24 = i24 + 1) { + org.w3c.dom.Element allRolesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(allRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").get(i24)); + ExtensionConfiguration.Extension extensionInstance = new ExtensionConfiguration.Extension(); + extensionConfigurationInstance.getAllRoles().add(extensionInstance); + + Element idElement = XmlUtility.getElementByTagNameNS(allRolesElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + extensionInstance.setId(idInstance); + } + } + } + + Element namedRolesSequenceElement = XmlUtility.getElementByTagNameNS(extensionConfigurationElement, "http://schemas.microsoft.com/windowsazure", "NamedRoles"); + if (namedRolesSequenceElement != null) { + for (int i25 = 0; i25 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(namedRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").size(); i25 = i25 + 1) { + org.w3c.dom.Element namedRolesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(namedRolesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").get(i25)); + ExtensionConfiguration.NamedRole roleInstance2 = new ExtensionConfiguration.NamedRole(); + extensionConfigurationInstance.getNamedRoles().add(roleInstance2); + + Element roleNameElement3 = XmlUtility.getElementByTagNameNS(namedRolesElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement3 != null) { + String roleNameInstance3; + roleNameInstance3 = roleNameElement3.getTextContent(); + roleInstance2.setRoleName(roleNameInstance3); + } + + Element extensionsSequenceElement = XmlUtility.getElementByTagNameNS(namedRolesElement, "http://schemas.microsoft.com/windowsazure", "Extensions"); + if (extensionsSequenceElement != null) { + for (int i26 = 0; i26 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").size(); i26 = i26 + 1) { + org.w3c.dom.Element extensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").get(i26)); + ExtensionConfiguration.Extension extensionInstance2 = new ExtensionConfiguration.Extension(); + roleInstance2.getExtensions().add(extensionInstance2); + + Element idElement2 = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement2 != null) { + String idInstance2; + idInstance2 = idElement2.getTextContent(); + extensionInstance2.setId(idInstance2); + } + } + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Package By Name operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Get Package By + * Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future getPackageByNameAsync(final String serviceName, final String deploymentName, final DeploymentGetPackageParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return getPackageByName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Get Package By Name operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Get Package By + * Name operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse getPackageByName(String serviceName, String deploymentName, DeploymentGetPackageParameters parameters) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getContainerUri() == null) { + throw new NullPointerException("parameters.ContainerUri"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "getPackageByNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/package" + "?"; + url = url + "containerUri=" + URLEncoder.encode(parameters.getContainerUri().toString(), "UTF-8") + " +"; + if (parameters.isOverwriteExisting() != null) { + url = url + "&" + "overwriteExisting=" + URLEncoder.encode(Boolean.toString(parameters.isOverwriteExisting()).toLowerCase(), "UTF-8"); + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Package By Slot operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Get Package By + * Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future getPackageBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentGetPackageParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return getPackageBySlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Get Package By Slot operation retrieves a cloud service package for a + * deployment and stores the package files in Azure Blob storage. The + * following package files are placed in storage: the cloud service + * configuration file (.cscfg), providing configuration settings for the + * cloud service and individual roles, including the number of role + * instances; and the service package (.cspkg), containing the application + * code and the service definition file. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154121.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Get Package By + * Slot operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse getPackageBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentGetPackageParameters parameters) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getContainerUri() == null) { + throw new NullPointerException("parameters.ContainerUri"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "getPackageBySlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/package" + "?"; + url = url + "containerUri=" + URLEncoder.encode(parameters.getContainerUri().toString(), "UTF-8") + " +"; + if (parameters.isOverwriteExisting() != null) { + url = url + "&" + "overwriteExisting=" + URLEncoder.encode(Boolean.toString(parameters.isOverwriteExisting()).toLowerCase(), "UTF-8"); + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Reboot Role Instance By Deployment Name operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future rebootRoleInstanceByDeploymentNameAsync(final String serviceName, final String deploymentName, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return rebootRoleInstanceByDeploymentName(serviceName, deploymentName, roleInstanceName); + } + }); + } + + /** + * The Reboot Role Instance By Deployment Name operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse rebootRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "rebootRoleInstanceByDeploymentNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginRebootingRoleInstanceByDeploymentNameAsync(serviceName, deploymentName, roleInstanceName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Reboot Role Instance By Deployment Slot operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future rebootRoleInstanceByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return rebootRoleInstanceByDeploymentSlot(serviceName, deploymentSlot, roleInstanceName); + } + }); + } + + /** + * The Reboot Role Instance By Deployment Slot operation requests a reboot + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441298.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse rebootRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "rebootRoleInstanceByDeploymentSlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginRebootingRoleInstanceByDeploymentSlotAsync(serviceName, deploymentSlot, roleInstanceName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Reimage Role Instance By Deployment Name operation requests a reimage + * of a role instance that is running in a deployment.This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future reimageRoleInstanceByDeploymentNameAsync(final String serviceName, final String deploymentName, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return reimageRoleInstanceByDeploymentName(serviceName, deploymentName, roleInstanceName); + } + }); + } + + /** + * The Reimage Role Instance By Deployment Name operation requests a reimage + * of a role instance that is running in a deployment.This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse reimageRoleInstanceByDeploymentName(String serviceName, String deploymentName, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "reimageRoleInstanceByDeploymentNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginReimagingRoleInstanceByDeploymentNameAsync(serviceName, deploymentName, roleInstanceName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Reimage Role Instance By Deployment Slot operation requests a reimage + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future reimageRoleInstanceByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final String roleInstanceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return reimageRoleInstanceByDeploymentSlot(serviceName, deploymentSlot, roleInstanceName); + } + }); + } + + /** + * The Reimage Role Instance By Deployment Slot operation requests a reimage + * of a role instance that is running in a deployment. This operation is an + * asynchronous operation. To determine whether the Management service has + * finished processing the request, call Get Operation Status. For more + * information on asynchronous operations, see Tracking Asynchronous + * Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441292.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param roleInstanceName Required. The name of your role instance. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse reimageRoleInstanceByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, String roleInstanceName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("roleInstanceName", roleInstanceName); + CloudTracing.enter(invocationId, this, "reimageRoleInstanceByDeploymentSlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginReimagingRoleInstanceByDeploymentSlotAsync(serviceName, deploymentSlot, roleInstanceName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Rollback Update Or Upgrade By Deployment Name operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Name operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future rollbackUpdateOrUpgradeByDeploymentNameAsync(final String serviceName, final String deploymentName, final DeploymentRollbackUpdateOrUpgradeParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return rollbackUpdateOrUpgradeByDeploymentName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Rollback Update Or Upgrade By Deployment Name operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Name operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse rollbackUpdateOrUpgradeByDeploymentName(String serviceName, String deploymentName, DeploymentRollbackUpdateOrUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "rollbackUpdateOrUpgradeByDeploymentNameAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/" + "?" + "comp=rollback"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element rollbackUpdateOrUpgradeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RollbackUpdateOrUpgrade"); + requestDoc.appendChild(rollbackUpdateOrUpgradeElement); + + Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode"); + modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString())); + rollbackUpdateOrUpgradeElement.appendChild(modeElement); + + Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force"); + forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase())); + rollbackUpdateOrUpgradeElement.appendChild(forceElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Rollback Update Or Upgrade By Deployment Slot operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Slot operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future rollbackUpdateOrUpgradeByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentRollbackUpdateOrUpgradeParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return rollbackUpdateOrUpgradeByDeploymentSlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Rollback Update Or Upgrade By Deployment Slot operation cancels an + * in-progress configuration update and returns the deployment to its state + * before the update was started. This operation can only be called when an + * update is in progress on the deployment. The deployment status can be + * detected by calling the Get Deployment operation or Get Hosted Service + * Properties operation and inspecting the RollbackAllowed element. If the + * value returned is true a rollback can be performed. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for + * more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Rollback Update Or + * Upgrade By Deployment Slot operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse rollbackUpdateOrUpgradeByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentRollbackUpdateOrUpgradeParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "rollbackUpdateOrUpgradeByDeploymentSlotAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deploymentslots/" + deploymentSlot + "/" + "?" + "comp=rollback"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element rollbackUpdateOrUpgradeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RollbackUpdateOrUpgrade"); + requestDoc.appendChild(rollbackUpdateOrUpgradeElement); + + Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode"); + modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString())); + rollbackUpdateOrUpgradeElement.appendChild(modeElement); + + Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force"); + forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase())); + rollbackUpdateOrUpgradeElement.appendChild(forceElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Swap Deployment operation initiates a virtual IP address swap between + * the staging and production deployment environments for a service. If the + * service is currently running in the staging environment, it will be + * swapped to the production environment. If it is running in the + * production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Swap Deployment + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future swapAsync(final String serviceName, final DeploymentSwapParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return swap(serviceName, parameters); + } + }); + } + + /** + * The Swap Deployment operation initiates a virtual IP address swap between + * the staging and production deployment environments for a service. If the + * service is currently running in the staging environment, it will be + * swapped to the production environment. If it is running in the + * production environment, it will be swapped to staging. For more + * information on this type of upgrade, see Performing Virtual IP Swap + * Upgrades at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee517253.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460814.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param parameters Required. Parameters supplied to the Swap Deployment + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse swap(String serviceName, DeploymentSwapParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "swapAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginSwappingAsync(serviceName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Update Deployment Status By Deployment Name operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future updateStatusByDeploymentNameAsync(final String serviceName, final String deploymentName, final DeploymentUpdateStatusParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return updateStatusByDeploymentName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Update Deployment Status By Deployment Name operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse updateStatusByDeploymentName(String serviceName, String deploymentName, DeploymentUpdateStatusParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateStatusByDeploymentNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginUpdatingStatusByDeploymentNameAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Update Deployment Status By Deployment Slot operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future updateStatusByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentUpdateStatusParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return updateStatusByDeploymentSlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Update Deployment Status By Deployment Slot operation initiates a + * change in the running status of a deployment. The status of a deployment + * can be running or suspended. This operation is an asynchronous + * operation. To determine whether the Management service has finished + * processing the request, call Get Operation Status. For more information + * on asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx + * for more information) + * + * @param serviceName Required. The cloud service to swap deployments for. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Update Deployment + * Status By Deployment Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse updateStatusByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpdateStatusParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateStatusByDeploymentSlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginUpdatingStatusByDeploymentSlotAsync(serviceName, deploymentSlot, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Upgrade Deployment By Name operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future upgradeByNameAsync(final String serviceName, final String deploymentName, final DeploymentUpgradeParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return upgradeByName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Upgrade Deployment By Name operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentName Required. The deployment to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse upgradeByName(String serviceName, String deploymentName, DeploymentUpgradeParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "upgradeByNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginUpgradingByNameAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Upgrade Deployment By Slot operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future upgradeBySlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentUpgradeParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return upgradeBySlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Upgrade Deployment By Slot operation initiates an update of role + * instances in a deployment using the package and configuration that you + * specify. For more information about updating role instances, see Update + * an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the request + * has been processed, call Get Operation Status. For more information on + * asynchronous operations, see Tracking Asynchronous Service Management + * Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To + * perform an automatic update of a deployment, call Upgrade Deployment or + * Change Deployment Configuration with the Mode element set to automatic. + * The update proceeds from that point without a need for further input. + * You can call Get Operation Status to determine when the update is + * complete. To perform a manual update, first call Upgrade Deployment with + * the Mode element set to manual. Next, call Walk Upgrade Domain to update + * each domain within the deployment. You should make sure that the + * operation is complete by calling Get Operation Status before updating + * the next domain. Important: An update that adds or removes role + * instances will result in a configuration update to all roles that are + * deployed in the cloud service. Existing role instances need to be + * notified of new role instances so that all role instances can + * communicate together in the cloud service. By default, a cloud service + * is deployed with five update domains, which are updated one at a time + * during an in-place update. For information on modifying the number of + * update domains in the service definition file, see the Azure Service + * Definition Schema (.csdef File). To determine the update domain in which + * a particular instance is running in Windows Azure, use the UpdateDomain + * property of the RoleInstance class. See the Azure Managed Library + * Reference at + * http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for + * more information. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for + * more information) + * + * @param serviceName Required. The cloud service to upgrade. + * @param deploymentSlot Required. The slot to upgrade. + * @param parameters Required. Parameters supplied to the Upgrade Deployment + * By Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse upgradeBySlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentUpgradeParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "upgradeBySlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginUpgradingBySlotAsync(serviceName, deploymentSlot, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Walk Upgrade Domain By Deployment Name operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Name operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future walkUpgradeDomainByDeploymentNameAsync(final String serviceName, final String deploymentName, final DeploymentWalkUpgradeDomainParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return walkUpgradeDomainByDeploymentName(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Walk Upgrade Domain By Deployment Name operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Name operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse walkUpgradeDomainByDeploymentName(String serviceName, String deploymentName, DeploymentWalkUpgradeDomainParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "walkUpgradeDomainByDeploymentNameAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginWalkingUpgradeDomainByDeploymentNameAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Walk Upgrade Domain By Deployment Slot operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Slot operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future walkUpgradeDomainByDeploymentSlotAsync(final String serviceName, final DeploymentSlot deploymentSlot, final DeploymentWalkUpgradeDomainParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return walkUpgradeDomainByDeploymentSlot(serviceName, deploymentSlot, parameters); + } + }); + } + + /** + * The Walk Upgrade Domain By Deployment Slot operation specifies an update + * domain in which a role instance must be updated. For more information + * about updating role instances, see Update an Azure Service at + * http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This + * operation is an asynchronous operation. To determine whether the + * Management service has finished processing the request, call Get + * Operation Status. For more information on asynchronous operations, see + * Tracking Asynchronous Service Management Requests at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. + * Prior to calling the Walk Upgrade Domain operation you must have called + * Upgrade Deployment, Change Deployment Configuration, or Rollback Update + * Or Upgrade. By default, a service is deployed with five update domains, + * which are updated one at a time during an in-place update. For + * information on modifying the number of update domains in the service + * definition file, see the Azure Service Definition Schema (.csdef File). + * To perform a manual update of your deployment, proceed in this order: + * Call Upgrade Deployment with the Mode element set to manual. Call Walk + * Upgrade Domain to update each domain within the deployment. Update + * domains must be updated in order. For example, begin with domain 0, + * proceed to domain 1, and so on. Important: An update that adds or + * removes role instances will result in a configuration update to all + * roles that are deployed in the cloud service. Existing role instances + * need to be notified of new role instances so that all role instances can + * communicate together in the cloud service. While an update is in + * progress, call Get Deployment to determine its status. If the update is + * in progress, Get Deployment returns an UpgradeStatus element that + * contains information about the update. If the update is complete, or if + * no update is in progress, then the UpgradeStatus element is null. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param deploymentSlot Required. The deployment slot. + * @param parameters Required. Parameters supplied to the Walk Upgrade + * Domain By Deployment Slot operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse walkUpgradeDomainByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot, DeploymentWalkUpgradeDomainParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentSlot", deploymentSlot); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "walkUpgradeDomainByDeploymentSlotAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getDeploymentsOperations().beginWalkingUpgradeDomainByDeploymentSlotAsync(serviceName, deploymentSlot, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/Exports.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/Exports.java new file mode 100644 index 0000000000000..cc341b95f8a30 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/Exports.java @@ -0,0 +1,31 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.Builder; + +/** + * The Class Exports. + */ +public class Exports implements Builder.Exports { + /* (non-Javadoc) + * @see com.microsoft.windowsazure.services.core.Builder.Exports#register(com.microsoft.windowsazure.services.core.Builder.Registry) + */ + @Override + public void register(Builder.Registry registry) { + // provide contract implementation + registry.add(ComputeManagementClient.class, ComputeManagementClientImpl.class); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/HostedServiceOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/HostedServiceOperations.java new file mode 100644 index 0000000000000..fbafb37ab61f8 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/HostedServiceOperations.java @@ -0,0 +1,724 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.HostedServiceAddExtensionParameters; +import com.microsoft.windowsazure.management.compute.models.HostedServiceCheckNameAvailabilityResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceCreateParameters; +import com.microsoft.windowsazure.management.compute.models.HostedServiceGetDetailedResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceGetExtensionResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceGetResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceListAvailableExtensionsResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceListExtensionsResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceListResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceUpdateParameters; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the hosted +* services beneath your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for more +* information) +*/ +public interface HostedServiceOperations { + /** + * The Add Extension operation adds an available extension to your cloud + * service. In Azure, a process can run as an extension of a cloud service. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as extensions to the cloud service. You can find the available + * extension by using the List Available Extensions operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Add Extension + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse addExtension(String serviceName, HostedServiceAddExtensionParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Add Extension operation adds an available extension to your cloud + * service. In Azure, a process can run as an extension of a cloud service. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as extensions to the cloud service. You can find the available + * extension by using the List Available Extensions operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Add Extension + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future addExtensionAsync(String serviceName, HostedServiceAddExtensionParameters parameters); + + /** + * The Begin Adding Extension operation adds an available extension to your + * cloud service. In Azure, a process can run as an extension of a cloud + * service. For example, Remote Desktop Access or the Azure Diagnostics + * Agent can run as extensions to the cloud service. You can find the + * available extension by using the List Available Extensions operation. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Begin Adding + * Extension operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginAddingExtension(String serviceName, HostedServiceAddExtensionParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Adding Extension operation adds an available extension to your + * cloud service. In Azure, a process can run as an extension of a cloud + * service. For example, Remote Desktop Access or the Azure Diagnostics + * Agent can run as extensions to the cloud service. You can find the + * available extension by using the List Available Extensions operation. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Begin Adding + * Extension operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginAddingExtensionAsync(String serviceName, HostedServiceAddExtensionParameters parameters); + + /** + * The Begin Deleting All Hosted Service operation deletes the specified + * cloud service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeletingAll(String serviceName) throws IOException, ServiceException; + + /** + * The Begin Deleting All Hosted Service operation deletes the specified + * cloud service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingAllAsync(String serviceName); + + /** + * The Begin Deleting Extension operation deletes the specified extension + * from a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeletingExtension(String serviceName, String extensionId) throws IOException, ServiceException; + + /** + * The Begin Deleting Extension operation deletes the specified extension + * from a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingExtensionAsync(String serviceName, String extensionId); + + /** + * The Check Hosted Service Name Availability operation checks for the + * availability of the specified cloud service name. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx for + * more information) + * + * @param serviceName Required. The cloud service name that you would like + * to use. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Check Hosted Service Name Availability operation response. + */ + HostedServiceCheckNameAvailabilityResponse checkNameAvailability(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Check Hosted Service Name Availability operation checks for the + * availability of the specified cloud service name. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx for + * more information) + * + * @param serviceName Required. The cloud service name that you would like + * to use. + * @return The Check Hosted Service Name Availability operation response. + */ + Future checkNameAvailabilityAsync(String serviceName); + + /** + * The Create Hosted Service operation creates a new cloud service in Azure. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Hosted + * Service operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse create(HostedServiceCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException; + + /** + * The Create Hosted Service operation creates a new cloud service in Azure. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Hosted + * Service operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future createAsync(HostedServiceCreateParameters parameters); + + /** + * The Delete Hosted Service operation deletes the specified cloud service + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String serviceName) throws IOException, ServiceException, InterruptedException, ExecutionException; + + /** + * The Delete Hosted Service operation deletes the specified cloud service + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String serviceName); + + /** + * The Delete All Hosted Service operation deletes the specified cloud + * service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse deleteAll(String serviceName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Delete All Hosted Service operation deletes the specified cloud + * service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteAllAsync(String serviceName); + + /** + * The Delete Extension operation deletes the specified extension from a + * cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse deleteExtension(String serviceName, String extensionId) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Delete Extension operation deletes the specified extension from a + * cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteExtensionAsync(String serviceName, String extensionId); + + /** + * The Get Hosted Service Properties operation retrieves system properties + * for the specified cloud service. These properties include the service + * name and service type; and the name of the affinity group to which the + * service belongs, or its location if it is not part of an affinity group. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Hosted Service operation response. + */ + HostedServiceGetResponse get(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Hosted Service Properties operation retrieves system properties + * for the specified cloud service. These properties include the service + * name and service type; and the name of the affinity group to which the + * service belongs, or its location if it is not part of an affinity group. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The Get Hosted Service operation response. + */ + Future getAsync(String serviceName); + + /** + * The Get Detailed Hosted Service Properties operation retrieves system + * properties for the specified cloud service. These properties include the + * service name and service type; the name of the affinity group to which + * the service belongs, or its location if it is not part of an affinity + * group; and information on the deployments of the service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The detailed Get Hosted Service operation response. + */ + HostedServiceGetDetailedResponse getDetailed(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Detailed Hosted Service Properties operation retrieves system + * properties for the specified cloud service. These properties include the + * service name and service type; the name of the affinity group to which + * the service belongs, or its location if it is not part of an affinity + * group; and information on the deployments of the service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The detailed Get Hosted Service operation response. + */ + Future getDetailedAsync(String serviceName); + + /** + * The Get Extension operation retrieves information about a specified + * extension that was added to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169557.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Extension operation response. + */ + HostedServiceGetExtensionResponse getExtension(String serviceName, String extensionId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Extension operation retrieves information about a specified + * extension that was added to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169557.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @return The Get Extension operation response. + */ + Future getExtensionAsync(String serviceName, String extensionId); + + /** + * The List Hosted Services operation lists the cloud services available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Hosted Service operation response. + */ + HostedServiceListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Hosted Services operation lists the cloud services available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx for + * more information) + * + * @return The List Hosted Service operation response. + */ + Future listAsync(); + + /** + * The List Available Extensions operation lists the extensions that are + * available to add to your cloud service. In Windows Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Available Extensions operation response. + */ + HostedServiceListAvailableExtensionsResponse listAvailableExtensions() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Available Extensions operation lists the extensions that are + * available to add to your cloud service. In Windows Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx for + * more information) + * + * @return The List Available Extensions operation response. + */ + Future listAvailableExtensionsAsync(); + + /** + * The List Extensions operation lists all of the extensions that were added + * to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169561.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Extensions operation response. + */ + HostedServiceListExtensionsResponse listExtensions(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Extensions operation lists all of the extensions that were added + * to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169561.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The List Extensions operation response. + */ + Future listExtensionsAsync(String serviceName); + + /** + * The List Extension Versions operation lists the versions of an extension + * that are available to add to a cloud service. In Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495437.aspx for + * more information) + * + * @param providerNamespace Required. The provider namespace. + * @param extensionType Required. The extension type name. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Available Extensions operation response. + */ + HostedServiceListAvailableExtensionsResponse listExtensionVersions(String providerNamespace, String extensionType) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Extension Versions operation lists the versions of an extension + * that are available to add to a cloud service. In Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495437.aspx for + * more information) + * + * @param providerNamespace Required. The provider namespace. + * @param extensionType Required. The extension type name. + * @return The List Available Extensions operation response. + */ + Future listExtensionVersionsAsync(String providerNamespace, String extensionType); + + /** + * The Update Hosted Service operation can update the label or description + * of a cloud service in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Update Hosted + * Service operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse update(String serviceName, HostedServiceUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, InterruptedException, ExecutionException, URISyntaxException; + + /** + * The Update Hosted Service operation can update the label or description + * of a cloud service in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Update Hosted + * Service operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future updateAsync(String serviceName, HostedServiceUpdateParameters parameters); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/HostedServiceOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/HostedServiceOperationsImpl.java new file mode 100644 index 0000000000000..47347a56d513d --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/HostedServiceOperationsImpl.java @@ -0,0 +1,4370 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.AccessControlListRule; +import com.microsoft.windowsazure.management.compute.models.ConfigurationSet; +import com.microsoft.windowsazure.management.compute.models.DataVirtualHardDisk; +import com.microsoft.windowsazure.management.compute.models.DeploymentSlot; +import com.microsoft.windowsazure.management.compute.models.DeploymentStatus; +import com.microsoft.windowsazure.management.compute.models.DeploymentUpgradeType; +import com.microsoft.windowsazure.management.compute.models.DnsServer; +import com.microsoft.windowsazure.management.compute.models.DnsSettings; +import com.microsoft.windowsazure.management.compute.models.DomainJoinCredentials; +import com.microsoft.windowsazure.management.compute.models.DomainJoinProvisioning; +import com.microsoft.windowsazure.management.compute.models.DomainJoinSettings; +import com.microsoft.windowsazure.management.compute.models.EndpointAcl; +import com.microsoft.windowsazure.management.compute.models.GuestAgentFormattedMessage; +import com.microsoft.windowsazure.management.compute.models.GuestAgentMessage; +import com.microsoft.windowsazure.management.compute.models.GuestAgentStatus; +import com.microsoft.windowsazure.management.compute.models.HostedServiceAddExtensionParameters; +import com.microsoft.windowsazure.management.compute.models.HostedServiceCheckNameAvailabilityResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceCreateParameters; +import com.microsoft.windowsazure.management.compute.models.HostedServiceGetDetailedResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceGetExtensionResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceGetResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceListAvailableExtensionsResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceListExtensionsResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceListResponse; +import com.microsoft.windowsazure.management.compute.models.HostedServiceProperties; +import com.microsoft.windowsazure.management.compute.models.HostedServiceStatus; +import com.microsoft.windowsazure.management.compute.models.HostedServiceUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.InputEndpoint; +import com.microsoft.windowsazure.management.compute.models.InstanceEndpoint; +import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbe; +import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbeTransportProtocol; +import com.microsoft.windowsazure.management.compute.models.OSVirtualHardDisk; +import com.microsoft.windowsazure.management.compute.models.PersistentVMDowntime; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionConfigurationStatus; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionParameterValue; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionReference; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionStatus; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionSubStatus; +import com.microsoft.windowsazure.management.compute.models.Role; +import com.microsoft.windowsazure.management.compute.models.RoleInstance; +import com.microsoft.windowsazure.management.compute.models.RoleInstancePowerState; +import com.microsoft.windowsazure.management.compute.models.SshSettingKeyPair; +import com.microsoft.windowsazure.management.compute.models.SshSettingPublicKey; +import com.microsoft.windowsazure.management.compute.models.SshSettings; +import com.microsoft.windowsazure.management.compute.models.StoredCertificateSettings; +import com.microsoft.windowsazure.management.compute.models.UpgradeDomainState; +import com.microsoft.windowsazure.management.compute.models.UpgradeStatus; +import com.microsoft.windowsazure.management.compute.models.VirtualHardDiskHostCaching; +import com.microsoft.windowsazure.management.compute.models.VirtualIPAddress; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineWindowsRemoteManagementListenerType; +import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementListener; +import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementSettings; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the hosted +* services beneath your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for more +* information) +*/ +public class HostedServiceOperationsImpl implements ServiceOperations, HostedServiceOperations { + /** + * Initializes a new instance of the HostedServiceOperationsImpl class. + * + * @param client Reference to the service client. + */ + HostedServiceOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The Add Extension operation adds an available extension to your cloud + * service. In Azure, a process can run as an extension of a cloud service. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as extensions to the cloud service. You can find the available + * extension by using the List Available Extensions operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Add Extension + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future addExtensionAsync(final String serviceName, final HostedServiceAddExtensionParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return addExtension(serviceName, parameters); + } + }); + } + + /** + * The Add Extension operation adds an available extension to your cloud + * service. In Azure, a process can run as an extension of a cloud service. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as extensions to the cloud service. You can find the available + * extension by using the List Available Extensions operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Add Extension + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse addExtension(String serviceName, HostedServiceAddExtensionParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "addExtensionAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getHostedServicesOperations().beginAddingExtensionAsync(serviceName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Begin Adding Extension operation adds an available extension to your + * cloud service. In Azure, a process can run as an extension of a cloud + * service. For example, Remote Desktop Access or the Azure Diagnostics + * Agent can run as extensions to the cloud service. You can find the + * available extension by using the List Available Extensions operation. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Begin Adding + * Extension operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginAddingExtensionAsync(final String serviceName, final HostedServiceAddExtensionParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginAddingExtension(serviceName, parameters); + } + }); + } + + /** + * The Begin Adding Extension operation adds an available extension to your + * cloud service. In Azure, a process can run as an extension of a cloud + * service. For example, Remote Desktop Access or the Azure Diagnostics + * Agent can run as extensions to the cloud service. You can find the + * available extension by using the List Available Extensions operation. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Begin Adding + * Extension operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginAddingExtension(String serviceName, HostedServiceAddExtensionParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getId() == null) { + throw new NullPointerException("parameters.Id"); + } + if (parameters.getType() == null) { + throw new NullPointerException("parameters.Type"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginAddingExtensionAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/extensions"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + requestDoc.appendChild(extensionElement); + + if (parameters.getProviderNamespace() != null) { + Element providerNameSpaceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ProviderNameSpace"); + providerNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getProviderNamespace())); + extensionElement.appendChild(providerNameSpaceElement); + } + + Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); + typeElement.appendChild(requestDoc.createTextNode(parameters.getType())); + extensionElement.appendChild(typeElement); + + Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement.appendChild(requestDoc.createTextNode(parameters.getId())); + extensionElement.appendChild(idElement); + + if (parameters.getThumbprint() != null) { + Element thumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + thumbprintElement.appendChild(requestDoc.createTextNode(parameters.getThumbprint())); + extensionElement.appendChild(thumbprintElement); + } + + if (parameters.getThumbprintAlgorithm() != null) { + Element thumbprintAlgorithmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm"); + thumbprintAlgorithmElement.appendChild(requestDoc.createTextNode(parameters.getThumbprintAlgorithm())); + extensionElement.appendChild(thumbprintAlgorithmElement); + } + + if (parameters.getPublicConfiguration() != null) { + Element publicConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicConfiguration"); + publicConfigurationElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getPublicConfiguration().getBytes()))); + extensionElement.appendChild(publicConfigurationElement); + } + + if (parameters.getPrivateConfiguration() != null) { + Element privateConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PrivateConfiguration"); + privateConfigurationElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getPrivateConfiguration().getBytes()))); + extensionElement.appendChild(privateConfigurationElement); + } + + if (parameters.getVersion() != null) { + Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version"); + versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion())); + extensionElement.appendChild(versionElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Deleting All Hosted Service operation deletes the specified + * cloud service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingAllAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeletingAll(serviceName); + } + }); + } + + /** + * The Begin Deleting All Hosted Service operation deletes the specified + * cloud service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeletingAll(String serviceName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "beginDeletingAllAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "?" + "comp=media"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Deleting Extension operation deletes the specified extension + * from a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingExtensionAsync(final String serviceName, final String extensionId) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeletingExtension(serviceName, extensionId); + } + }); + } + + /** + * The Begin Deleting Extension operation deletes the specified extension + * from a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeletingExtension(String serviceName, String extensionId) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (extensionId == null) { + throw new NullPointerException("extensionId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("extensionId", extensionId); + CloudTracing.enter(invocationId, this, "beginDeletingExtensionAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/extensions/" + extensionId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Check Hosted Service Name Availability operation checks for the + * availability of the specified cloud service name. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx for + * more information) + * + * @param serviceName Required. The cloud service name that you would like + * to use. + * @return The Check Hosted Service Name Availability operation response. + */ + @Override + public Future checkNameAvailabilityAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceCheckNameAvailabilityResponse call() throws Exception { + return checkNameAvailability(serviceName); + } + }); + } + + /** + * The Check Hosted Service Name Availability operation checks for the + * availability of the specified cloud service name. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx for + * more information) + * + * @param serviceName Required. The cloud service name that you would like + * to use. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Check Hosted Service Name Availability operation response. + */ + @Override + public HostedServiceCheckNameAvailabilityResponse checkNameAvailability(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "checkNameAvailabilityAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/operations/isavailable/" + serviceName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceCheckNameAvailabilityResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceCheckNameAvailabilityResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element availabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "AvailabilityResponse"); + if (availabilityResponseElement != null) { + Element resultElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "Result"); + if (resultElement != null) { + boolean resultInstance; + resultInstance = DatatypeConverter.parseBoolean(resultElement.getTextContent().toLowerCase()); + result.setIsAvailable(resultInstance); + } + + Element reasonElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "Reason"); + if (reasonElement != null) { + String reasonInstance; + reasonInstance = reasonElement.getTextContent(); + result.setReason(reasonInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Create Hosted Service operation creates a new cloud service in Azure. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Hosted + * Service operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future createAsync(final HostedServiceCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return create(parameters); + } + }); + } + + /** + * The Create Hosted Service operation creates a new cloud service in Azure. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Hosted + * Service operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse create(HostedServiceCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { + throw new IllegalArgumentException("parameters.Description"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getServiceName() == null) { + throw new NullPointerException("parameters.ServiceName"); + } + // TODO: Validate parameters.ServiceName is a valid DNS name. + int locationCount = (parameters.getAffinityGroup() != null ? 1 : 0) + (parameters.getLocation() != null ? 1 : 0); + if (locationCount != 1) { + throw new IllegalArgumentException("Only one of parameters.AffinityGroup, parameters.Location may be provided."); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element createHostedServiceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CreateHostedService"); + requestDoc.appendChild(createHostedServiceElement); + + Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceName"); + serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName())); + createHostedServiceElement.appendChild(serviceNameElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + createHostedServiceElement.appendChild(labelElement); + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + createHostedServiceElement.appendChild(descriptionElement); + } + + if (parameters.getLocation() != null) { + Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Location"); + locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation())); + createHostedServiceElement.appendChild(locationElement); + } + + if (parameters.getAffinityGroup() != null) { + Element affinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + affinityGroupElement.appendChild(requestDoc.createTextNode(parameters.getAffinityGroup())); + createHostedServiceElement.appendChild(affinityGroupElement); + } + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + createHostedServiceElement.appendChild(extendedPropertiesDictionaryElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Hosted Service operation deletes the specified cloud service + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(serviceName); + } + }); + } + + /** + * The Delete Hosted Service operation deletes the specified cloud service + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String serviceName) throws IOException, ServiceException, InterruptedException, ExecutionException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete All Hosted Service operation deletes the specified cloud + * service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteAllAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return deleteAll(serviceName); + } + }); + } + + /** + * The Delete All Hosted Service operation deletes the specified cloud + * service from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse deleteAll(String serviceName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "deleteAllAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getHostedServicesOperations().beginDeletingAllAsync(serviceName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Extension operation deletes the specified extension from a + * cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteExtensionAsync(final String serviceName, final String extensionId) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return deleteExtension(serviceName, extensionId); + } + }); + } + + /** + * The Delete Extension operation deletes the specified extension from a + * cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse deleteExtension(String serviceName, String extensionId) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("extensionId", extensionId); + CloudTracing.enter(invocationId, this, "deleteExtensionAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getHostedServicesOperations().beginDeletingExtensionAsync(serviceName, extensionId).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Get Hosted Service Properties operation retrieves system properties + * for the specified cloud service. These properties include the service + * name and service type; and the name of the affinity group to which the + * service belongs, or its location if it is not part of an affinity group. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The Get Hosted Service operation response. + */ + @Override + public Future getAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceGetResponse call() throws Exception { + return get(serviceName); + } + }); + } + + /** + * The Get Hosted Service Properties operation retrieves system properties + * for the specified cloud service. These properties include the service + * name and service type; and the name of the affinity group to which the + * service belongs, or its location if it is not part of an affinity group. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx + * for more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Hosted Service operation response. + */ + @Override + public HostedServiceGetResponse get(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element hostedServiceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "HostedService"); + if (hostedServiceElement != null) { + Element urlElement = XmlUtility.getElementByTagNameNS(hostedServiceElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + result.setUri(urlInstance); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(hostedServiceElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + result.setServiceName(serviceNameInstance); + } + + Element hostedServicePropertiesElement = XmlUtility.getElementByTagNameNS(hostedServiceElement, "http://schemas.microsoft.com/windowsazure", "HostedServiceProperties"); + if (hostedServicePropertiesElement != null) { + HostedServiceProperties hostedServicePropertiesInstance = new HostedServiceProperties(); + result.setProperties(hostedServicePropertiesInstance); + + Element descriptionElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + hostedServicePropertiesInstance.setDescription(descriptionInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + hostedServicePropertiesInstance.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + hostedServicePropertiesInstance.setLocation(locationInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + hostedServicePropertiesInstance.setLabel(labelInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + HostedServiceStatus statusInstance; + statusInstance = HostedServiceStatus.valueOf(statusElement.getTextContent()); + hostedServicePropertiesInstance.setStatus(statusInstance); + } + + Element dateCreatedElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "DateCreated"); + if (dateCreatedElement != null) { + Calendar dateCreatedInstance; + dateCreatedInstance = DatatypeConverter.parseDateTime(dateCreatedElement.getTextContent()); + hostedServicePropertiesInstance.setDateCreated(dateCreatedInstance); + } + + Element dateLastModifiedElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "DateLastModified"); + if (dateLastModifiedElement != null) { + Calendar dateLastModifiedInstance; + dateLastModifiedInstance = DatatypeConverter.parseDateTime(dateLastModifiedElement.getTextContent()); + hostedServicePropertiesInstance.setDateLastModified(dateLastModifiedInstance); + } + + Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i1 = i1 + 1) { + org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i1)); + String extendedPropertiesKey = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + hostedServicePropertiesInstance.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Detailed Hosted Service Properties operation retrieves system + * properties for the specified cloud service. These properties include the + * service name and service type; the name of the affinity group to which + * the service belongs, or its location if it is not part of an affinity + * group; and information on the deployments of the service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The detailed Get Hosted Service operation response. + */ + @Override + public Future getDetailedAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceGetDetailedResponse call() throws Exception { + return getDetailed(serviceName); + } + }); + } + + /** + * The Get Detailed Hosted Service Properties operation retrieves system + * properties for the specified cloud service. These properties include the + * service name and service type; the name of the affinity group to which + * the service belongs, or its location if it is not part of an affinity + * group; and information on the deployments of the service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The detailed Get Hosted Service operation response. + */ + @Override + public HostedServiceGetDetailedResponse getDetailed(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "getDetailedAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "?" + "embed-detail=true"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceGetDetailedResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceGetDetailedResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element hostedServiceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "HostedService"); + if (hostedServiceElement != null) { + Element deploymentsSequenceElement = XmlUtility.getElementByTagNameNS(hostedServiceElement, "http://schemas.microsoft.com/windowsazure", "Deployments"); + if (deploymentsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(deploymentsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Deployment").size(); i1 = i1 + 1) { + org.w3c.dom.Element deploymentsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(deploymentsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Deployment").get(i1)); + HostedServiceGetDetailedResponse.Deployment deploymentInstance = new HostedServiceGetDetailedResponse.Deployment(); + result.getDeployments().add(deploymentInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + deploymentInstance.setName(nameInstance); + } + + Element deploymentSlotElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "DeploymentSlot"); + if (deploymentSlotElement != null) { + DeploymentSlot deploymentSlotInstance; + deploymentSlotInstance = DeploymentSlot.valueOf(deploymentSlotElement.getTextContent()); + deploymentInstance.setDeploymentSlot(deploymentSlotInstance); + } + + Element privateIDElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "PrivateID"); + if (privateIDElement != null) { + String privateIDInstance; + privateIDInstance = privateIDElement.getTextContent(); + deploymentInstance.setPrivateId(privateIDInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + DeploymentStatus statusInstance; + statusInstance = DeploymentStatus.valueOf(statusElement.getTextContent()); + deploymentInstance.setStatus(statusInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + deploymentInstance.setLabel(labelInstance); + } + + Element urlElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + deploymentInstance.setUri(urlInstance); + } + + Element configurationElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "Configuration"); + if (configurationElement != null) { + String configurationInstance; + configurationInstance = configurationElement.getTextContent() != null ? new String(Base64.decode(configurationElement.getTextContent())) : null; + deploymentInstance.setConfiguration(configurationInstance); + } + + Element roleInstanceListSequenceElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "RoleInstanceList"); + if (roleInstanceListSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleInstanceListSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleInstance").size(); i2 = i2 + 1) { + org.w3c.dom.Element roleInstanceListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleInstanceListSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleInstance").get(i2)); + RoleInstance roleInstanceInstance = new RoleInstance(); + deploymentInstance.getRoleInstances().add(roleInstanceInstance); + + Element roleNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + roleInstanceInstance.setRoleName(roleNameInstance); + } + + Element instanceNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceName"); + if (instanceNameElement != null) { + String instanceNameInstance; + instanceNameInstance = instanceNameElement.getTextContent(); + roleInstanceInstance.setInstanceName(instanceNameInstance); + } + + Element instanceStatusElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceStatus"); + if (instanceStatusElement != null) { + String instanceStatusInstance; + instanceStatusInstance = instanceStatusElement.getTextContent(); + roleInstanceInstance.setInstanceStatus(instanceStatusInstance); + } + + Element instanceUpgradeDomainElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceUpgradeDomain"); + if (instanceUpgradeDomainElement != null && (instanceUpgradeDomainElement.getTextContent() == null || instanceUpgradeDomainElement.getTextContent().isEmpty() == true) == false) { + int instanceUpgradeDomainInstance; + instanceUpgradeDomainInstance = DatatypeConverter.parseInt(instanceUpgradeDomainElement.getTextContent()); + roleInstanceInstance.setInstanceUpgradeDomain(instanceUpgradeDomainInstance); + } + + Element instanceFaultDomainElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceFaultDomain"); + if (instanceFaultDomainElement != null && (instanceFaultDomainElement.getTextContent() == null || instanceFaultDomainElement.getTextContent().isEmpty() == true) == false) { + int instanceFaultDomainInstance; + instanceFaultDomainInstance = DatatypeConverter.parseInt(instanceFaultDomainElement.getTextContent()); + roleInstanceInstance.setInstanceFaultDomain(instanceFaultDomainInstance); + } + + Element instanceSizeElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceSize"); + if (instanceSizeElement != null) { + String instanceSizeInstance; + instanceSizeInstance = instanceSizeElement.getTextContent(); + roleInstanceInstance.setInstanceSize(instanceSizeInstance); + } + + Element instanceStateDetailsElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceStateDetails"); + if (instanceStateDetailsElement != null) { + String instanceStateDetailsInstance; + instanceStateDetailsInstance = instanceStateDetailsElement.getTextContent(); + roleInstanceInstance.setInstanceStateDetails(instanceStateDetailsInstance); + } + + Element instanceErrorCodeElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceErrorCode"); + if (instanceErrorCodeElement != null) { + String instanceErrorCodeInstance; + instanceErrorCodeInstance = instanceErrorCodeElement.getTextContent(); + roleInstanceInstance.setInstanceErrorCode(instanceErrorCodeInstance); + } + + Element ipAddressElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "IpAddress"); + if (ipAddressElement != null) { + InetAddress ipAddressInstance; + ipAddressInstance = InetAddress.getByName(ipAddressElement.getTextContent()); + roleInstanceInstance.setIPAddress(ipAddressInstance); + } + + Element instanceEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoints"); + if (instanceEndpointsSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(instanceEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoint").size(); i3 = i3 + 1) { + org.w3c.dom.Element instanceEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(instanceEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InstanceEndpoint").get(i3)); + InstanceEndpoint instanceEndpointInstance = new InstanceEndpoint(); + roleInstanceInstance.getInstanceEndpoints().add(instanceEndpointInstance); + + Element localPortElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LocalPort"); + if (localPortElement != null && (localPortElement.getTextContent() == null || localPortElement.getTextContent().isEmpty() == true) == false) { + int localPortInstance; + localPortInstance = DatatypeConverter.parseInt(localPortElement.getTextContent()); + instanceEndpointInstance.setLocalPort(localPortInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + instanceEndpointInstance.setName(nameInstance2); + } + + Element publicPortElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "PublicPort"); + if (publicPortElement != null) { + int publicPortInstance; + publicPortInstance = DatatypeConverter.parseInt(publicPortElement.getTextContent()); + instanceEndpointInstance.setPort(publicPortInstance); + } + + Element protocolElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement != null) { + String protocolInstance; + protocolInstance = protocolElement.getTextContent(); + instanceEndpointInstance.setProtocol(protocolInstance); + } + + Element vipElement = XmlUtility.getElementByTagNameNS(instanceEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Vip"); + if (vipElement != null) { + InetAddress vipInstance; + vipInstance = InetAddress.getByName(vipElement.getTextContent()); + instanceEndpointInstance.setVirtualIPAddress(vipInstance); + } + } + } + + Element guestAgentStatusElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "GuestAgentStatus"); + if (guestAgentStatusElement != null) { + GuestAgentStatus guestAgentStatusInstance = new GuestAgentStatus(); + roleInstanceInstance.setGuestAgentStatus(guestAgentStatusInstance); + + Element protocolVersionElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "ProtocolVersion"); + if (protocolVersionElement != null) { + String protocolVersionInstance; + protocolVersionInstance = protocolVersionElement.getTextContent(); + guestAgentStatusInstance.setProtocolVersion(protocolVersionInstance); + } + + Element timestampElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement != null && (timestampElement.getTextContent() == null || timestampElement.getTextContent().isEmpty() == true) == false) { + Calendar timestampInstance; + timestampInstance = DatatypeConverter.parseDateTime(timestampElement.getTextContent()); + guestAgentStatusInstance.setTimestamp(timestampInstance); + } + + Element guestAgentVersionElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "GuestAgentVersion"); + if (guestAgentVersionElement != null) { + String guestAgentVersionInstance; + guestAgentVersionInstance = guestAgentVersionElement.getTextContent(); + guestAgentStatusInstance.setGuestAgentVersion(guestAgentVersionInstance); + } + + Element statusElement2 = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement2 != null) { + String statusInstance2; + statusInstance2 = statusElement2.getTextContent(); + guestAgentStatusInstance.setStatus(statusInstance2); + } + + Element codeElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null && (codeElement.getTextContent() == null || codeElement.getTextContent().isEmpty() == true) == false) { + int codeInstance; + codeInstance = DatatypeConverter.parseInt(codeElement.getTextContent()); + guestAgentStatusInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + GuestAgentMessage messageInstance = new GuestAgentMessage(); + guestAgentStatusInstance.setMessage(messageInstance); + + Element messageResourceIdElement = XmlUtility.getElementByTagNameNS(messageElement, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement != null) { + String messageResourceIdInstance; + messageResourceIdInstance = messageResourceIdElement.getTextContent(); + messageInstance.setMessageResourceId(messageResourceIdInstance); + } + + Element paramListSequenceElement = XmlUtility.getElementByTagNameNS(messageElement, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement != null) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Param").size(); i4 = i4 + 1) { + org.w3c.dom.Element paramListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Param").get(i4)); + messageInstance.getParamList().add(paramListElement.getTextContent()); + } + } + } + + Element formattedMessageElement = XmlUtility.getElementByTagNameNS(guestAgentStatusElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement != null) { + GuestAgentFormattedMessage formattedMessageInstance = new GuestAgentFormattedMessage(); + guestAgentStatusInstance.setFormattedMessage(formattedMessageInstance); + + Element languageElement = XmlUtility.getElementByTagNameNS(formattedMessageElement, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement != null) { + String languageInstance; + languageInstance = languageElement.getTextContent(); + formattedMessageInstance.setLanguage(languageInstance); + } + + Element messageElement2 = XmlUtility.getElementByTagNameNS(formattedMessageElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement2 != null) { + String messageInstance2; + messageInstance2 = messageElement2.getTextContent(); + formattedMessageInstance.setMessage(messageInstance2); + } + } + } + + Element resourceExtensionStatusListSequenceElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatusList"); + if (resourceExtensionStatusListSequenceElement != null) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatus").size(); i5 = i5 + 1) { + org.w3c.dom.Element resourceExtensionStatusListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionStatus").get(i5)); + ResourceExtensionStatus resourceExtensionStatusInstance = new ResourceExtensionStatus(); + roleInstanceInstance.getResourceExtensionStatusList().add(resourceExtensionStatusInstance); + + Element handlerNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "HandlerName"); + if (handlerNameElement != null) { + String handlerNameInstance; + handlerNameInstance = handlerNameElement.getTextContent(); + resourceExtensionStatusInstance.setHandlerName(handlerNameInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + resourceExtensionStatusInstance.setVersion(versionInstance); + } + + Element statusElement3 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement3 != null) { + String statusInstance3; + statusInstance3 = statusElement3.getTextContent(); + resourceExtensionStatusInstance.setStatus(statusInstance3); + } + + Element codeElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement2 != null && (codeElement2.getTextContent() == null || codeElement2.getTextContent().isEmpty() == true) == false) { + int codeInstance2; + codeInstance2 = DatatypeConverter.parseInt(codeElement2.getTextContent()); + resourceExtensionStatusInstance.setCode(codeInstance2); + } + + Element messageElement3 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement3 != null) { + GuestAgentMessage messageInstance3 = new GuestAgentMessage(); + resourceExtensionStatusInstance.setMessage(messageInstance3); + + Element messageResourceIdElement2 = XmlUtility.getElementByTagNameNS(messageElement3, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement2 != null) { + String messageResourceIdInstance2; + messageResourceIdInstance2 = messageResourceIdElement2.getTextContent(); + messageInstance3.setMessageResourceId(messageResourceIdInstance2); + } + + Element paramListSequenceElement2 = XmlUtility.getElementByTagNameNS(messageElement3, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement2 != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Param").size(); i6 = i6 + 1) { + org.w3c.dom.Element paramListElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Param").get(i6)); + messageInstance3.getParamList().add(paramListElement2.getTextContent()); + } + } + } + + Element formattedMessageElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement2 != null) { + GuestAgentFormattedMessage formattedMessageInstance2 = new GuestAgentFormattedMessage(); + resourceExtensionStatusInstance.setFormattedMessage(formattedMessageInstance2); + + Element languageElement2 = XmlUtility.getElementByTagNameNS(formattedMessageElement2, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement2 != null) { + String languageInstance2; + languageInstance2 = languageElement2.getTextContent(); + formattedMessageInstance2.setLanguage(languageInstance2); + } + + Element messageElement4 = XmlUtility.getElementByTagNameNS(formattedMessageElement2, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement4 != null) { + String messageInstance4; + messageInstance4 = messageElement4.getTextContent(); + formattedMessageInstance2.setMessage(messageInstance4); + } + } + + Element extensionSettingStatusElement = XmlUtility.getElementByTagNameNS(resourceExtensionStatusListElement, "http://schemas.microsoft.com/windowsazure", "ExtensionSettingStatus"); + if (extensionSettingStatusElement != null) { + ResourceExtensionConfigurationStatus extensionSettingStatusInstance = new ResourceExtensionConfigurationStatus(); + resourceExtensionStatusInstance.setExtensionSettingStatus(extensionSettingStatusInstance); + + Element timestampElement2 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement2 != null && (timestampElement2.getTextContent() == null || timestampElement2.getTextContent().isEmpty() == true) == false) { + Calendar timestampInstance2; + timestampInstance2 = DatatypeConverter.parseDateTime(timestampElement2.getTextContent()); + extensionSettingStatusInstance.setTimestamp(timestampInstance2); + } + + Element configurationAppliedTimeElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationAppliedTime"); + if (configurationAppliedTimeElement != null && (configurationAppliedTimeElement.getTextContent() == null || configurationAppliedTimeElement.getTextContent().isEmpty() == true) == false) { + Calendar configurationAppliedTimeInstance; + configurationAppliedTimeInstance = DatatypeConverter.parseDateTime(configurationAppliedTimeElement.getTextContent()); + extensionSettingStatusInstance.setConfigurationAppliedTime(configurationAppliedTimeInstance); + } + + Element nameElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement3 != null) { + String nameInstance3; + nameInstance3 = nameElement3.getTextContent(); + extensionSettingStatusInstance.setName(nameInstance3); + } + + Element operationElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + String operationInstance; + operationInstance = operationElement.getTextContent(); + extensionSettingStatusInstance.setOperation(operationInstance); + } + + Element statusElement4 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement4 != null) { + String statusInstance4; + statusInstance4 = statusElement4.getTextContent(); + extensionSettingStatusInstance.setStatus(statusInstance4); + } + + Element codeElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement3 != null && (codeElement3.getTextContent() == null || codeElement3.getTextContent().isEmpty() == true) == false) { + int codeInstance3; + codeInstance3 = DatatypeConverter.parseInt(codeElement3.getTextContent()); + extensionSettingStatusInstance.setCode(codeInstance3); + } + + Element messageElement5 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement5 != null) { + GuestAgentMessage messageInstance5 = new GuestAgentMessage(); + extensionSettingStatusInstance.setMessage(messageInstance5); + + Element messageResourceIdElement3 = XmlUtility.getElementByTagNameNS(messageElement5, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement3 != null) { + String messageResourceIdInstance3; + messageResourceIdInstance3 = messageResourceIdElement3.getTextContent(); + messageInstance5.setMessageResourceId(messageResourceIdInstance3); + } + + Element paramListSequenceElement3 = XmlUtility.getElementByTagNameNS(messageElement5, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement3 != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement3, "http://schemas.microsoft.com/windowsazure", "Param").size(); i7 = i7 + 1) { + org.w3c.dom.Element paramListElement3 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement3, "http://schemas.microsoft.com/windowsazure", "Param").get(i7)); + messageInstance5.getParamList().add(paramListElement3.getTextContent()); + } + } + } + + Element formattedMessageElement3 = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement3 != null) { + GuestAgentFormattedMessage formattedMessageInstance3 = new GuestAgentFormattedMessage(); + extensionSettingStatusInstance.setFormattedMessage(formattedMessageInstance3); + + Element languageElement3 = XmlUtility.getElementByTagNameNS(formattedMessageElement3, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement3 != null) { + String languageInstance3; + languageInstance3 = languageElement3.getTextContent(); + formattedMessageInstance3.setLanguage(languageInstance3); + } + + Element messageElement6 = XmlUtility.getElementByTagNameNS(formattedMessageElement3, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement6 != null) { + String messageInstance6; + messageInstance6 = messageElement6.getTextContent(); + formattedMessageInstance3.setMessage(messageInstance6); + } + } + + Element subStatusListSequenceElement = XmlUtility.getElementByTagNameNS(extensionSettingStatusElement, "http://schemas.microsoft.com/windowsazure", "SubStatusList"); + if (subStatusListSequenceElement != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubStatus").size(); i8 = i8 + 1) { + org.w3c.dom.Element subStatusListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subStatusListSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubStatus").get(i8)); + ResourceExtensionSubStatus subStatusInstance = new ResourceExtensionSubStatus(); + extensionSettingStatusInstance.getSubStatusList().add(subStatusInstance); + + Element nameElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement4 != null) { + String nameInstance4; + nameInstance4 = nameElement4.getTextContent(); + subStatusInstance.setName(nameInstance4); + } + + Element statusElement5 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement5 != null) { + String statusInstance5; + statusInstance5 = statusElement5.getTextContent(); + subStatusInstance.setStatus(statusInstance5); + } + + Element codeElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement4 != null && (codeElement4.getTextContent() == null || codeElement4.getTextContent().isEmpty() == true) == false) { + int codeInstance4; + codeInstance4 = DatatypeConverter.parseInt(codeElement4.getTextContent()); + subStatusInstance.setCode(codeInstance4); + } + + Element messageElement7 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement7 != null) { + GuestAgentMessage messageInstance7 = new GuestAgentMessage(); + subStatusInstance.setMessage(messageInstance7); + + Element messageResourceIdElement4 = XmlUtility.getElementByTagNameNS(messageElement7, "http://schemas.microsoft.com/windowsazure", "MessageResourceId"); + if (messageResourceIdElement4 != null) { + String messageResourceIdInstance4; + messageResourceIdInstance4 = messageResourceIdElement4.getTextContent(); + messageInstance7.setMessageResourceId(messageResourceIdInstance4); + } + + Element paramListSequenceElement4 = XmlUtility.getElementByTagNameNS(messageElement7, "http://schemas.microsoft.com/windowsazure", "ParamList"); + if (paramListSequenceElement4 != null) { + for (int i9 = 0; i9 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement4, "http://schemas.microsoft.com/windowsazure", "Param").size(); i9 = i9 + 1) { + org.w3c.dom.Element paramListElement4 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(paramListSequenceElement4, "http://schemas.microsoft.com/windowsazure", "Param").get(i9)); + messageInstance7.getParamList().add(paramListElement4.getTextContent()); + } + } + } + + Element formattedMessageElement4 = XmlUtility.getElementByTagNameNS(subStatusListElement, "http://schemas.microsoft.com/windowsazure", "FormattedMessage"); + if (formattedMessageElement4 != null) { + GuestAgentFormattedMessage formattedMessageInstance4 = new GuestAgentFormattedMessage(); + subStatusInstance.setFormattedMessage(formattedMessageInstance4); + + Element languageElement4 = XmlUtility.getElementByTagNameNS(formattedMessageElement4, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement4 != null) { + String languageInstance4; + languageInstance4 = languageElement4.getTextContent(); + formattedMessageInstance4.setLanguage(languageInstance4); + } + + Element messageElement8 = XmlUtility.getElementByTagNameNS(formattedMessageElement4, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement8 != null) { + String messageInstance8; + messageInstance8 = messageElement8.getTextContent(); + formattedMessageInstance4.setMessage(messageInstance8); + } + } + } + } + } + } + } + + Element powerStateElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "PowerState"); + if (powerStateElement != null) { + RoleInstancePowerState powerStateInstance; + powerStateInstance = RoleInstancePowerState.valueOf(powerStateElement.getTextContent()); + roleInstanceInstance.setPowerState(powerStateInstance); + } + + Element hostNameElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "HostName"); + if (hostNameElement != null) { + String hostNameInstance; + hostNameInstance = hostNameElement.getTextContent(); + roleInstanceInstance.setHostName(hostNameInstance); + } + + Element remoteAccessCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(roleInstanceListElement, "http://schemas.microsoft.com/windowsazure", "RemoteAccessCertificateThumbprint"); + if (remoteAccessCertificateThumbprintElement != null) { + String remoteAccessCertificateThumbprintInstance; + remoteAccessCertificateThumbprintInstance = remoteAccessCertificateThumbprintElement.getTextContent(); + roleInstanceInstance.setRemoteAccessCertificateThumbprint(remoteAccessCertificateThumbprintInstance); + } + } + } + + Element upgradeStatusElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "UpgradeStatus"); + if (upgradeStatusElement != null) { + UpgradeStatus upgradeStatusInstance = new UpgradeStatus(); + deploymentInstance.setUpgradeStatus(upgradeStatusInstance); + + Element upgradeTypeElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "UpgradeType"); + if (upgradeTypeElement != null) { + DeploymentUpgradeType upgradeTypeInstance; + upgradeTypeInstance = DeploymentUpgradeType.valueOf(upgradeTypeElement.getTextContent()); + upgradeStatusInstance.setUpgradeType(upgradeTypeInstance); + } + + Element currentUpgradeDomainStateElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "CurrentUpgradeDomainState"); + if (currentUpgradeDomainStateElement != null) { + UpgradeDomainState currentUpgradeDomainStateInstance; + currentUpgradeDomainStateInstance = UpgradeDomainState.valueOf(currentUpgradeDomainStateElement.getTextContent()); + upgradeStatusInstance.setCurrentUpgradeDomainState(currentUpgradeDomainStateInstance); + } + + Element currentUpgradeDomainElement = XmlUtility.getElementByTagNameNS(upgradeStatusElement, "http://schemas.microsoft.com/windowsazure", "CurrentUpgradeDomain"); + if (currentUpgradeDomainElement != null) { + int currentUpgradeDomainInstance; + currentUpgradeDomainInstance = DatatypeConverter.parseInt(currentUpgradeDomainElement.getTextContent()); + upgradeStatusInstance.setCurrentUpgradeDomain(currentUpgradeDomainInstance); + } + } + + Element upgradeDomainCountElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "UpgradeDomainCount"); + if (upgradeDomainCountElement != null) { + int upgradeDomainCountInstance; + upgradeDomainCountInstance = DatatypeConverter.parseInt(upgradeDomainCountElement.getTextContent()); + deploymentInstance.setUpgradeDomainCount(upgradeDomainCountInstance); + } + + Element roleListSequenceElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "RoleList"); + if (roleListSequenceElement != null) { + for (int i10 = 0; i10 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").size(); i10 = i10 + 1) { + org.w3c.dom.Element roleListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleListSequenceElement, "http://schemas.microsoft.com/windowsazure", "Role").get(i10)); + Role roleInstance = new Role(); + deploymentInstance.getRoles().add(roleInstance); + + Element roleNameElement2 = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement2 != null) { + String roleNameInstance2; + roleNameInstance2 = roleNameElement2.getTextContent(); + roleInstance.setRoleName(roleNameInstance2); + } + + Element osVersionElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "OsVersion"); + if (osVersionElement != null) { + String osVersionInstance; + osVersionInstance = osVersionElement.getTextContent(); + roleInstance.setOSVersion(osVersionInstance); + } + + Element roleTypeElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleType"); + if (roleTypeElement != null) { + String roleTypeInstance; + roleTypeInstance = roleTypeElement.getTextContent(); + roleInstance.setRoleType(roleTypeInstance); + } + + Element configurationSetsSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSets"); + if (configurationSetsSequenceElement != null) { + for (int i11 = 0; i11 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").size(); i11 = i11 + 1) { + org.w3c.dom.Element configurationSetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").get(i11)); + ConfigurationSet configurationSetInstance = new ConfigurationSet(); + roleInstance.getConfigurationSets().add(configurationSetInstance); + + Element configurationSetTypeElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + if (configurationSetTypeElement != null) { + String configurationSetTypeInstance; + configurationSetTypeInstance = configurationSetTypeElement.getTextContent(); + configurationSetInstance.setConfigurationSetType(configurationSetTypeInstance); + } + + Element inputEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + if (inputEndpointsSequenceElement != null) { + for (int i12 = 0; i12 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").size(); i12 = i12 + 1) { + org.w3c.dom.Element inputEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").get(i12)); + InputEndpoint inputEndpointInstance = new InputEndpoint(); + configurationSetInstance.getInputEndpoints().add(inputEndpointInstance); + + Element loadBalancedEndpointSetNameElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + if (loadBalancedEndpointSetNameElement != null) { + String loadBalancedEndpointSetNameInstance; + loadBalancedEndpointSetNameInstance = loadBalancedEndpointSetNameElement.getTextContent(); + inputEndpointInstance.setLoadBalancedEndpointSetName(loadBalancedEndpointSetNameInstance); + } + + Element localPortElement2 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LocalPort"); + if (localPortElement2 != null && (localPortElement2.getTextContent() == null || localPortElement2.getTextContent().isEmpty() == true) == false) { + int localPortInstance2; + localPortInstance2 = DatatypeConverter.parseInt(localPortElement2.getTextContent()); + inputEndpointInstance.setLocalPort(localPortInstance2); + } + + Element nameElement5 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement5 != null) { + String nameInstance5; + nameInstance5 = nameElement5.getTextContent(); + inputEndpointInstance.setName(nameInstance5); + } + + Element portElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement != null && (portElement.getTextContent() == null || portElement.getTextContent().isEmpty() == true) == false) { + int portInstance; + portInstance = DatatypeConverter.parseInt(portElement.getTextContent()); + inputEndpointInstance.setPort(portInstance); + } + + Element loadBalancerProbeElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + if (loadBalancerProbeElement != null) { + LoadBalancerProbe loadBalancerProbeInstance = new LoadBalancerProbe(); + inputEndpointInstance.setLoadBalancerProbe(loadBalancerProbeInstance); + + Element pathElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement != null) { + String pathInstance; + pathInstance = pathElement.getTextContent(); + loadBalancerProbeInstance.setPath(pathInstance); + } + + Element portElement2 = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement2 != null) { + int portInstance2; + portInstance2 = DatatypeConverter.parseInt(portElement2.getTextContent()); + loadBalancerProbeInstance.setPort(portInstance2); + } + + Element protocolElement2 = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement2 != null) { + LoadBalancerProbeTransportProtocol protocolInstance2; + protocolInstance2 = com.microsoft.windowsazure.management.compute.ComputeManagementClientImpl.parseLoadBalancerProbeTransportProtocol(protocolElement2.getTextContent()); + loadBalancerProbeInstance.setProtocol(protocolInstance2); + } + + Element intervalInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + if (intervalInSecondsElement != null && (intervalInSecondsElement.getTextContent() == null || intervalInSecondsElement.getTextContent().isEmpty() == true) == false) { + int intervalInSecondsInstance; + intervalInSecondsInstance = DatatypeConverter.parseInt(intervalInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setIntervalInSeconds(intervalInSecondsInstance); + } + + Element timeoutInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + if (timeoutInSecondsElement != null && (timeoutInSecondsElement.getTextContent() == null || timeoutInSecondsElement.getTextContent().isEmpty() == true) == false) { + int timeoutInSecondsInstance; + timeoutInSecondsInstance = DatatypeConverter.parseInt(timeoutInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setTimeoutInSeconds(timeoutInSecondsInstance); + } + } + + Element protocolElement3 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement3 != null) { + String protocolInstance3; + protocolInstance3 = protocolElement3.getTextContent(); + inputEndpointInstance.setProtocol(protocolInstance3); + } + + Element vipElement2 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Vip"); + if (vipElement2 != null) { + InetAddress vipInstance2; + vipInstance2 = InetAddress.getByName(vipElement2.getTextContent()); + inputEndpointInstance.setVirtualIPAddress(vipInstance2); + } + + Element enableDirectServerReturnElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + if (enableDirectServerReturnElement != null && (enableDirectServerReturnElement.getTextContent() == null || enableDirectServerReturnElement.getTextContent().isEmpty() == true) == false) { + boolean enableDirectServerReturnInstance; + enableDirectServerReturnInstance = DatatypeConverter.parseBoolean(enableDirectServerReturnElement.getTextContent().toLowerCase()); + inputEndpointInstance.setEnableDirectServerReturn(enableDirectServerReturnInstance); + } + + Element endpointAclElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + if (endpointAclElement != null) { + EndpointAcl endpointAclInstance = new EndpointAcl(); + inputEndpointInstance.setEndpointAcl(endpointAclInstance); + + Element rulesSequenceElement = XmlUtility.getElementByTagNameNS(endpointAclElement, "http://schemas.microsoft.com/windowsazure", "Rules"); + if (rulesSequenceElement != null) { + for (int i13 = 0; i13 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").size(); i13 = i13 + 1) { + org.w3c.dom.Element rulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").get(i13)); + AccessControlListRule ruleInstance = new AccessControlListRule(); + endpointAclInstance.getRules().add(ruleInstance); + + Element orderElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Order"); + if (orderElement != null && (orderElement.getTextContent() == null || orderElement.getTextContent().isEmpty() == true) == false) { + int orderInstance; + orderInstance = DatatypeConverter.parseInt(orderElement.getTextContent()); + ruleInstance.setOrder(orderInstance); + } + + Element actionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Action"); + if (actionElement != null) { + String actionInstance; + actionInstance = actionElement.getTextContent(); + ruleInstance.setAction(actionInstance); + } + + Element remoteSubnetElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + if (remoteSubnetElement != null) { + String remoteSubnetInstance; + remoteSubnetInstance = remoteSubnetElement.getTextContent(); + ruleInstance.setRemoteSubnet(remoteSubnetInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + ruleInstance.setDescription(descriptionInstance); + } + } + } + } + } + } + + Element subnetNamesSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SubnetNames"); + if (subnetNamesSequenceElement != null) { + for (int i14 = 0; i14 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").size(); i14 = i14 + 1) { + org.w3c.dom.Element subnetNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").get(i14)); + configurationSetInstance.getSubnetNames().add(subnetNamesElement.getTextContent()); + } + } + + Element staticVirtualNetworkIPAddressElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + if (staticVirtualNetworkIPAddressElement != null) { + String staticVirtualNetworkIPAddressInstance; + staticVirtualNetworkIPAddressInstance = staticVirtualNetworkIPAddressElement.getTextContent(); + configurationSetInstance.setStaticVirtualNetworkIPAddress(staticVirtualNetworkIPAddressInstance); + } + + Element computerNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ComputerName"); + if (computerNameElement != null) { + String computerNameInstance; + computerNameInstance = computerNameElement.getTextContent(); + configurationSetInstance.setComputerName(computerNameInstance); + } + + Element adminPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminPassword"); + if (adminPasswordElement != null) { + String adminPasswordInstance; + adminPasswordInstance = adminPasswordElement.getTextContent(); + configurationSetInstance.setAdminPassword(adminPasswordInstance); + } + + Element resetPasswordOnFirstLogonElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + if (resetPasswordOnFirstLogonElement != null && (resetPasswordOnFirstLogonElement.getTextContent() == null || resetPasswordOnFirstLogonElement.getTextContent().isEmpty() == true) == false) { + boolean resetPasswordOnFirstLogonInstance; + resetPasswordOnFirstLogonInstance = DatatypeConverter.parseBoolean(resetPasswordOnFirstLogonElement.getTextContent().toLowerCase()); + configurationSetInstance.setResetPasswordOnFirstLogon(resetPasswordOnFirstLogonInstance); + } + + Element enableAutomaticUpdatesElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + if (enableAutomaticUpdatesElement != null && (enableAutomaticUpdatesElement.getTextContent() == null || enableAutomaticUpdatesElement.getTextContent().isEmpty() == true) == false) { + boolean enableAutomaticUpdatesInstance; + enableAutomaticUpdatesInstance = DatatypeConverter.parseBoolean(enableAutomaticUpdatesElement.getTextContent().toLowerCase()); + configurationSetInstance.setEnableAutomaticUpdates(enableAutomaticUpdatesInstance); + } + + Element timeZoneElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "TimeZone"); + if (timeZoneElement != null) { + String timeZoneInstance; + timeZoneInstance = timeZoneElement.getTextContent(); + configurationSetInstance.setTimeZone(timeZoneInstance); + } + + Element domainJoinElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DomainJoin"); + if (domainJoinElement != null) { + DomainJoinSettings domainJoinInstance = new DomainJoinSettings(); + configurationSetInstance.setDomainJoin(domainJoinInstance); + + Element credentialsElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Credentials"); + if (credentialsElement != null) { + DomainJoinCredentials credentialsInstance = new DomainJoinCredentials(); + domainJoinInstance.setCredentials(credentialsInstance); + + Element domainElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Domain"); + if (domainElement != null) { + String domainInstance; + domainInstance = domainElement.getTextContent(); + credentialsInstance.setDomain(domainInstance); + } + + Element usernameElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Username"); + if (usernameElement != null) { + String usernameInstance; + usernameInstance = usernameElement.getTextContent(); + credentialsInstance.setUserName(usernameInstance); + } + + Element passwordElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement != null) { + String passwordInstance; + passwordInstance = passwordElement.getTextContent(); + credentialsInstance.setPassword(passwordInstance); + } + } + + Element joinDomainElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "JoinDomain"); + if (joinDomainElement != null) { + String joinDomainInstance; + joinDomainInstance = joinDomainElement.getTextContent(); + domainJoinInstance.setDomainToJoin(joinDomainInstance); + } + + Element machineObjectOUElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + if (machineObjectOUElement != null) { + String machineObjectOUInstance; + machineObjectOUInstance = machineObjectOUElement.getTextContent(); + domainJoinInstance.setLdapMachineObjectOU(machineObjectOUInstance); + } + + Element provisioningElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Provisioning"); + if (provisioningElement != null) { + DomainJoinProvisioning provisioningInstance = new DomainJoinProvisioning(); + domainJoinInstance.setProvisioning(provisioningInstance); + + Element accountDataElement = XmlUtility.getElementByTagNameNS(provisioningElement, "http://schemas.microsoft.com/windowsazure", "AccountData"); + if (accountDataElement != null) { + String accountDataInstance; + accountDataInstance = accountDataElement.getTextContent(); + provisioningInstance.setAccountData(accountDataInstance); + } + } + } + + Element storedCertificateSettingsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + if (storedCertificateSettingsSequenceElement != null) { + for (int i15 = 0; i15 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").size(); i15 = i15 + 1) { + org.w3c.dom.Element storedCertificateSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").get(i15)); + StoredCertificateSettings certificateSettingInstance = new StoredCertificateSettings(); + configurationSetInstance.getStoredCertificateSettings().add(certificateSettingInstance); + + Element storeLocationElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreLocation"); + if (storeLocationElement != null) { + } + + Element storeNameElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreName"); + if (storeNameElement != null) { + String storeNameInstance; + storeNameInstance = storeNameElement.getTextContent(); + certificateSettingInstance.setStoreName(storeNameInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + certificateSettingInstance.setThumbprint(thumbprintInstance); + } + } + } + + Element winRMElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "WinRM"); + if (winRMElement != null) { + WindowsRemoteManagementSettings winRMInstance = new WindowsRemoteManagementSettings(); + configurationSetInstance.setWindowsRemoteManagement(winRMInstance); + + Element listenersSequenceElement = XmlUtility.getElementByTagNameNS(winRMElement, "http://schemas.microsoft.com/windowsazure", "Listeners"); + if (listenersSequenceElement != null) { + for (int i16 = 0; i16 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").size(); i16 = i16 + 1) { + org.w3c.dom.Element listenersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").get(i16)); + WindowsRemoteManagementListener listenerInstance = new WindowsRemoteManagementListener(); + winRMInstance.getListeners().add(listenerInstance); + + Element protocolElement4 = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement4 != null) { + VirtualMachineWindowsRemoteManagementListenerType protocolInstance4; + protocolInstance4 = VirtualMachineWindowsRemoteManagementListenerType.valueOf(protocolElement4.getTextContent()); + listenerInstance.setListenerType(protocolInstance4); + } + + Element certificateThumbprintElement = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + if (certificateThumbprintElement != null) { + String certificateThumbprintInstance; + certificateThumbprintInstance = certificateThumbprintElement.getTextContent(); + listenerInstance.setCertificateThumbprint(certificateThumbprintInstance); + } + } + } + } + + Element adminUsernameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminUsername"); + if (adminUsernameElement != null) { + String adminUsernameInstance; + adminUsernameInstance = adminUsernameElement.getTextContent(); + configurationSetInstance.setAdminUserName(adminUsernameInstance); + } + + Element hostNameElement2 = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "HostName"); + if (hostNameElement2 != null) { + String hostNameInstance2; + hostNameInstance2 = hostNameElement2.getTextContent(); + configurationSetInstance.setHostName(hostNameInstance2); + } + + Element userNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserName"); + if (userNameElement != null) { + String userNameInstance; + userNameInstance = userNameElement.getTextContent(); + configurationSetInstance.setUserName(userNameInstance); + } + + Element userPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserPassword"); + if (userPasswordElement != null) { + String userPasswordInstance; + userPasswordInstance = userPasswordElement.getTextContent(); + configurationSetInstance.setUserPassword(userPasswordInstance); + } + + Element disableSshPasswordAuthenticationElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + if (disableSshPasswordAuthenticationElement != null && (disableSshPasswordAuthenticationElement.getTextContent() == null || disableSshPasswordAuthenticationElement.getTextContent().isEmpty() == true) == false) { + boolean disableSshPasswordAuthenticationInstance; + disableSshPasswordAuthenticationInstance = DatatypeConverter.parseBoolean(disableSshPasswordAuthenticationElement.getTextContent().toLowerCase()); + configurationSetInstance.setDisableSshPasswordAuthentication(disableSshPasswordAuthenticationInstance); + } + + Element sSHElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SSH"); + if (sSHElement != null) { + SshSettings sSHInstance = new SshSettings(); + configurationSetInstance.setSshSettings(sSHInstance); + + Element publicKeysSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "PublicKeys"); + if (publicKeysSequenceElement != null) { + for (int i17 = 0; i17 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").size(); i17 = i17 + 1) { + org.w3c.dom.Element publicKeysElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").get(i17)); + SshSettingPublicKey publicKeyInstance = new SshSettingPublicKey(); + sSHInstance.getPublicKeys().add(publicKeyInstance); + + Element fingerprintElement = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement != null) { + String fingerprintInstance; + fingerprintInstance = fingerprintElement.getTextContent(); + publicKeyInstance.setFingerprint(fingerprintInstance); + } + + Element pathElement2 = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement2 != null) { + String pathInstance2; + pathInstance2 = pathElement2.getTextContent(); + publicKeyInstance.setPath(pathInstance2); + } + } + } + + Element keyPairsSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "KeyPairs"); + if (keyPairsSequenceElement != null) { + for (int i18 = 0; i18 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").size(); i18 = i18 + 1) { + org.w3c.dom.Element keyPairsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").get(i18)); + SshSettingKeyPair keyPairInstance = new SshSettingKeyPair(); + sSHInstance.getKeyPairs().add(keyPairInstance); + + Element fingerprintElement2 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement2 != null) { + String fingerprintInstance2; + fingerprintInstance2 = fingerprintElement2.getTextContent(); + keyPairInstance.setFingerprint(fingerprintInstance2); + } + + Element pathElement3 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement3 != null) { + String pathInstance3; + pathInstance3 = pathElement3.getTextContent(); + keyPairInstance.setPath(pathInstance3); + } + } + } + } + + Element customDataElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "CustomData"); + if (customDataElement != null) { + String customDataInstance; + customDataInstance = customDataElement.getTextContent(); + configurationSetInstance.setCustomData(customDataInstance); + } + } + } + + Element resourceExtensionReferencesSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences"); + if (resourceExtensionReferencesSequenceElement != null) { + for (int i19 = 0; i19 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionReferencesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference").size(); i19 = i19 + 1) { + org.w3c.dom.Element resourceExtensionReferencesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionReferencesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference").get(i19)); + ResourceExtensionReference resourceExtensionReferenceInstance = new ResourceExtensionReference(); + roleInstance.getResourceExtensionReferences().add(resourceExtensionReferenceInstance); + + Element referenceNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "ReferenceName"); + if (referenceNameElement != null) { + String referenceNameInstance; + referenceNameInstance = referenceNameElement.getTextContent(); + resourceExtensionReferenceInstance.setReferenceName(referenceNameInstance); + } + + Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Publisher"); + if (publisherElement != null) { + String publisherInstance; + publisherInstance = publisherElement.getTextContent(); + resourceExtensionReferenceInstance.setPublisher(publisherInstance); + } + + Element nameElement6 = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement6 != null) { + String nameInstance6; + nameInstance6 = nameElement6.getTextContent(); + resourceExtensionReferenceInstance.setName(nameInstance6); + } + + Element versionElement2 = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement2 != null) { + String versionInstance2; + versionInstance2 = versionElement2.getTextContent(); + resourceExtensionReferenceInstance.setVersion(versionInstance2); + } + + Element resourceExtensionParameterValuesSequenceElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValues"); + if (resourceExtensionParameterValuesSequenceElement != null) { + for (int i20 = 0; i20 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionParameterValuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue").size(); i20 = i20 + 1) { + org.w3c.dom.Element resourceExtensionParameterValuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionParameterValuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue").get(i20)); + ResourceExtensionParameterValue resourceExtensionParameterValueInstance = new ResourceExtensionParameterValue(); + resourceExtensionReferenceInstance.getResourceExtensionParameterValues().add(resourceExtensionParameterValueInstance); + + Element keyElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Key"); + if (keyElement != null) { + String keyInstance; + keyInstance = keyElement.getTextContent(); + resourceExtensionParameterValueInstance.setKey(keyInstance); + } + + Element valueElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Value"); + if (valueElement != null) { + String valueInstance; + valueInstance = valueElement.getTextContent() != null ? new String(Base64.decode(valueElement.getTextContent())) : null; + resourceExtensionParameterValueInstance.setValue(valueInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(resourceExtensionParameterValuesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + resourceExtensionParameterValueInstance.setType(typeInstance); + } + } + } + + Element stateElement = XmlUtility.getElementByTagNameNS(resourceExtensionReferencesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + resourceExtensionReferenceInstance.setState(stateInstance); + } + } + } + + Element vMImageNameElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "VMImageName"); + if (vMImageNameElement != null) { + String vMImageNameInstance; + vMImageNameInstance = vMImageNameElement.getTextContent(); + roleInstance.setVMImageName(vMImageNameInstance); + } + + Element availabilitySetNameElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "AvailabilitySetName"); + if (availabilitySetNameElement != null) { + String availabilitySetNameInstance; + availabilitySetNameInstance = availabilitySetNameElement.getTextContent(); + roleInstance.setAvailabilitySetName(availabilitySetNameInstance); + } + + Element dataVirtualHardDisksSequenceElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks"); + if (dataVirtualHardDisksSequenceElement != null) { + for (int i21 = 0; i21 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").size(); i21 = i21 + 1) { + org.w3c.dom.Element dataVirtualHardDisksElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").get(i21)); + DataVirtualHardDisk dataVirtualHardDiskInstance = new DataVirtualHardDisk(); + roleInstance.getDataVirtualHardDisks().add(dataVirtualHardDiskInstance); + + Element hostCachingElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement != null && (hostCachingElement.getTextContent() == null || hostCachingElement.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance; + hostCachingInstance = VirtualHardDiskHostCaching.valueOf(hostCachingElement.getTextContent()); + dataVirtualHardDiskInstance.setHostCaching(hostCachingInstance); + } + + Element diskLabelElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement != null) { + String diskLabelInstance; + diskLabelInstance = diskLabelElement.getTextContent(); + dataVirtualHardDiskInstance.setLabel(diskLabelInstance); + } + + Element diskNameElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement != null) { + String diskNameInstance; + diskNameInstance = diskNameElement.getTextContent(); + dataVirtualHardDiskInstance.setName(diskNameInstance); + } + + Element lunElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "Lun"); + if (lunElement != null && (lunElement.getTextContent() == null || lunElement.getTextContent().isEmpty() == true) == false) { + int lunInstance; + lunInstance = DatatypeConverter.parseInt(lunElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalUnitNumber(lunInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null && (logicalDiskSizeInGBElement.getTextContent() == null || logicalDiskSizeInGBElement.getTextContent().isEmpty() == true) == false) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setMediaLink(mediaLinkInstance); + } + + Element sourceMediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + if (sourceMediaLinkElement != null) { + URI sourceMediaLinkInstance; + sourceMediaLinkInstance = new URI(sourceMediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setSourceMediaLink(sourceMediaLinkInstance); + } + } + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance2; + labelInstance2 = labelElement2.getTextContent(); + roleInstance.setLabel(labelInstance2); + } + + Element oSVirtualHardDiskElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk"); + if (oSVirtualHardDiskElement != null) { + OSVirtualHardDisk oSVirtualHardDiskInstance = new OSVirtualHardDisk(); + roleInstance.setOSVirtualHardDisk(oSVirtualHardDiskInstance); + + Element hostCachingElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement2 != null && (hostCachingElement2.getTextContent() == null || hostCachingElement2.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance2; + hostCachingInstance2 = VirtualHardDiskHostCaching.valueOf(hostCachingElement2.getTextContent()); + oSVirtualHardDiskInstance.setHostCaching(hostCachingInstance2); + } + + Element diskLabelElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement2 != null) { + String diskLabelInstance2; + diskLabelInstance2 = diskLabelElement2.getTextContent(); + oSVirtualHardDiskInstance.setLabel(diskLabelInstance2); + } + + Element diskNameElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement2 != null) { + String diskNameInstance2; + diskNameInstance2 = diskNameElement2.getTextContent(); + oSVirtualHardDiskInstance.setName(diskNameInstance2); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance2; + mediaLinkInstance2 = new URI(mediaLinkElement2.getTextContent()); + oSVirtualHardDiskInstance.setMediaLink(mediaLinkInstance2); + } + + Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); + if (sourceImageNameElement != null) { + String sourceImageNameInstance; + sourceImageNameInstance = sourceImageNameElement.getTextContent(); + oSVirtualHardDiskInstance.setSourceImageName(sourceImageNameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + oSVirtualHardDiskInstance.setOperatingSystem(osInstance); + } + } + + Element roleSizeElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "RoleSize"); + if (roleSizeElement != null) { + String roleSizeInstance; + roleSizeInstance = roleSizeElement.getTextContent(); + roleInstance.setRoleSize(roleSizeInstance); + } + + Element provisionGuestAgentElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent"); + if (provisionGuestAgentElement != null && (provisionGuestAgentElement.getTextContent() == null || provisionGuestAgentElement.getTextContent().isEmpty() == true) == false) { + boolean provisionGuestAgentInstance; + provisionGuestAgentInstance = DatatypeConverter.parseBoolean(provisionGuestAgentElement.getTextContent().toLowerCase()); + roleInstance.setProvisionGuestAgent(provisionGuestAgentInstance); + } + + Element defaultWinRmCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(roleListElement, "http://schemas.microsoft.com/windowsazure", "DefaultWinRmCertificateThumbprint"); + if (defaultWinRmCertificateThumbprintElement != null) { + String defaultWinRmCertificateThumbprintInstance; + defaultWinRmCertificateThumbprintInstance = defaultWinRmCertificateThumbprintElement.getTextContent(); + roleInstance.setDefaultWinRmCertificateThumbprint(defaultWinRmCertificateThumbprintInstance); + } + } + } + + Element sdkVersionElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "SdkVersion"); + if (sdkVersionElement != null) { + String sdkVersionInstance; + sdkVersionInstance = sdkVersionElement.getTextContent(); + deploymentInstance.setSdkVersion(sdkVersionInstance); + } + + Element lockedElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "Locked"); + if (lockedElement != null) { + boolean lockedInstance; + lockedInstance = DatatypeConverter.parseBoolean(lockedElement.getTextContent().toLowerCase()); + deploymentInstance.setLocked(lockedInstance); + } + + Element rollbackAllowedElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "RollbackAllowed"); + if (rollbackAllowedElement != null) { + boolean rollbackAllowedInstance; + rollbackAllowedInstance = DatatypeConverter.parseBoolean(rollbackAllowedElement.getTextContent().toLowerCase()); + deploymentInstance.setRollbackAllowed(rollbackAllowedInstance); + } + + Element createdTimeElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); + if (createdTimeElement != null) { + Calendar createdTimeInstance; + createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); + deploymentInstance.setCreatedTime(createdTimeInstance); + } + + Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "LastModifiedTime"); + if (lastModifiedTimeElement != null) { + String lastModifiedTimeInstance; + lastModifiedTimeInstance = lastModifiedTimeElement.getTextContent(); + deploymentInstance.setLastModifiedTime(lastModifiedTimeInstance); + } + + Element virtualNetworkNameElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "VirtualNetworkName"); + if (virtualNetworkNameElement != null) { + String virtualNetworkNameInstance; + virtualNetworkNameInstance = virtualNetworkNameElement.getTextContent(); + deploymentInstance.setVirtualNetworkName(virtualNetworkNameInstance); + } + + Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement != null) { + for (int i22 = 0; i22 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i22 = i22 + 1) { + org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i22)); + String extendedPropertiesKey = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + deploymentInstance.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); + } + } + + Element persistentVMDowntimeElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "PersistentVMDowntime"); + if (persistentVMDowntimeElement != null) { + PersistentVMDowntime persistentVMDowntimeInstance = new PersistentVMDowntime(); + deploymentInstance.setPersistentVMDowntime(persistentVMDowntimeInstance); + + Element startTimeElement = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); + if (startTimeElement != null) { + Calendar startTimeInstance; + startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); + persistentVMDowntimeInstance.setStartTime(startTimeInstance); + } + + Element endTimeElement = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "EndTime"); + if (endTimeElement != null) { + Calendar endTimeInstance; + endTimeInstance = DatatypeConverter.parseDateTime(endTimeElement.getTextContent()); + persistentVMDowntimeInstance.setEndTime(endTimeInstance); + } + + Element statusElement6 = XmlUtility.getElementByTagNameNS(persistentVMDowntimeElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement6 != null) { + String statusInstance6; + statusInstance6 = statusElement6.getTextContent(); + persistentVMDowntimeInstance.setStatus(statusInstance6); + } + } + + Element virtualIPsSequenceElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "VirtualIPs"); + if (virtualIPsSequenceElement != null) { + for (int i23 = 0; i23 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP").size(); i23 = i23 + 1) { + org.w3c.dom.Element virtualIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP").get(i23)); + VirtualIPAddress virtualIPInstance = new VirtualIPAddress(); + deploymentInstance.getVirtualIPAddresses().add(virtualIPInstance); + + Element addressElement = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement != null) { + InetAddress addressInstance; + addressInstance = InetAddress.getByName(addressElement.getTextContent()); + virtualIPInstance.setAddress(addressInstance); + } + + Element nameElement7 = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement7 != null) { + String nameInstance7; + nameInstance7 = nameElement7.getTextContent(); + virtualIPInstance.setName(nameInstance7); + } + + Element isDnsProgrammedElement = XmlUtility.getElementByTagNameNS(virtualIPsElement, "http://schemas.microsoft.com/windowsazure", "IsDnsProgrammed"); + if (isDnsProgrammedElement != null && (isDnsProgrammedElement.getTextContent() == null || isDnsProgrammedElement.getTextContent().isEmpty() == true) == false) { + boolean isDnsProgrammedInstance; + isDnsProgrammedInstance = DatatypeConverter.parseBoolean(isDnsProgrammedElement.getTextContent().toLowerCase()); + virtualIPInstance.setIsDnsProgrammed(isDnsProgrammedInstance); + } + } + } + + Element dnsElement = XmlUtility.getElementByTagNameNS(deploymentsElement, "http://schemas.microsoft.com/windowsazure", "Dns"); + if (dnsElement != null) { + DnsSettings dnsInstance = new DnsSettings(); + deploymentInstance.setDnsSettings(dnsInstance); + + Element dnsServersSequenceElement = XmlUtility.getElementByTagNameNS(dnsElement, "http://schemas.microsoft.com/windowsazure", "DnsServers"); + if (dnsServersSequenceElement != null) { + for (int i24 = 0; i24 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").size(); i24 = i24 + 1) { + org.w3c.dom.Element dnsServersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").get(i24)); + DnsServer dnsServerInstance = new DnsServer(); + dnsInstance.getDnsServers().add(dnsServerInstance); + + Element nameElement8 = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement8 != null) { + String nameInstance8; + nameInstance8 = nameElement8.getTextContent(); + dnsServerInstance.setName(nameInstance8); + } + + Element addressElement2 = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement2 != null) { + InetAddress addressInstance2; + addressInstance2 = InetAddress.getByName(addressElement2.getTextContent()); + dnsServerInstance.setAddress(addressInstance2); + } + } + } + } + } + } + + Element urlElement2 = XmlUtility.getElementByTagNameNS(hostedServiceElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement2 != null) { + URI urlInstance2; + urlInstance2 = new URI(urlElement2.getTextContent()); + result.setUri(urlInstance2); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(hostedServiceElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + result.setServiceName(serviceNameInstance); + } + + Element hostedServicePropertiesElement = XmlUtility.getElementByTagNameNS(hostedServiceElement, "http://schemas.microsoft.com/windowsazure", "HostedServiceProperties"); + if (hostedServicePropertiesElement != null) { + HostedServiceProperties hostedServicePropertiesInstance = new HostedServiceProperties(); + result.setProperties(hostedServicePropertiesInstance); + + Element descriptionElement2 = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement2 != null) { + String descriptionInstance2; + descriptionInstance2 = descriptionElement2.getTextContent(); + hostedServicePropertiesInstance.setDescription(descriptionInstance2); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + hostedServicePropertiesInstance.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + hostedServicePropertiesInstance.setLocation(locationInstance); + } + + Element labelElement3 = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement3 != null) { + String labelInstance3; + labelInstance3 = labelElement3.getTextContent() != null ? new String(Base64.decode(labelElement3.getTextContent())) : null; + hostedServicePropertiesInstance.setLabel(labelInstance3); + } + + Element statusElement7 = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement7 != null) { + HostedServiceStatus statusInstance7; + statusInstance7 = HostedServiceStatus.valueOf(statusElement7.getTextContent()); + hostedServicePropertiesInstance.setStatus(statusInstance7); + } + + Element dateCreatedElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "DateCreated"); + if (dateCreatedElement != null) { + Calendar dateCreatedInstance; + dateCreatedInstance = DatatypeConverter.parseDateTime(dateCreatedElement.getTextContent()); + hostedServicePropertiesInstance.setDateCreated(dateCreatedInstance); + } + + Element dateLastModifiedElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "DateLastModified"); + if (dateLastModifiedElement != null) { + Calendar dateLastModifiedInstance; + dateLastModifiedInstance = DatatypeConverter.parseDateTime(dateLastModifiedElement.getTextContent()); + hostedServicePropertiesInstance.setDateLastModified(dateLastModifiedInstance); + } + + Element extendedPropertiesSequenceElement2 = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement2 != null) { + for (int i25 = 0; i25 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i25 = i25 + 1) { + org.w3c.dom.Element extendedPropertiesElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i25)); + String extendedPropertiesKey2 = XmlUtility.getElementByTagNameNS(extendedPropertiesElement2, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue2 = XmlUtility.getElementByTagNameNS(extendedPropertiesElement2, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + hostedServicePropertiesInstance.getExtendedProperties().put(extendedPropertiesKey2, extendedPropertiesValue2); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Extension operation retrieves information about a specified + * extension that was added to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169557.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @return The Get Extension operation response. + */ + @Override + public Future getExtensionAsync(final String serviceName, final String extensionId) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceGetExtensionResponse call() throws Exception { + return getExtension(serviceName, extensionId); + } + }); + } + + /** + * The Get Extension operation retrieves information about a specified + * extension that was added to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169557.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param extensionId Required. The identifier that was assigned to the + * extension when it was added to the cloud service + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Extension operation response. + */ + @Override + public HostedServiceGetExtensionResponse getExtension(String serviceName, String extensionId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (extensionId == null) { + throw new NullPointerException("extensionId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("extensionId", extensionId); + CloudTracing.enter(invocationId, this, "getExtensionAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/extensions/" + extensionId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceGetExtensionResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceGetExtensionResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element extensionElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Extension"); + if (extensionElement != null) { + Element providerNameSpaceElement = XmlUtility.getElementByTagNameNS(extensionElement, "http://schemas.microsoft.com/windowsazure", "ProviderNameSpace"); + if (providerNameSpaceElement != null) { + String providerNameSpaceInstance; + providerNameSpaceInstance = providerNameSpaceElement.getTextContent(); + result.setProviderNamespace(providerNameSpaceInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(extensionElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + result.setType(typeInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(extensionElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setId(idInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(extensionElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + result.setVersion(versionInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(extensionElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + result.setThumbprint(thumbprintInstance); + } + + Element thumbprintAlgorithmElement = XmlUtility.getElementByTagNameNS(extensionElement, "http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm"); + if (thumbprintAlgorithmElement != null) { + String thumbprintAlgorithmInstance; + thumbprintAlgorithmInstance = thumbprintAlgorithmElement.getTextContent(); + result.setThumbprintAlgorithm(thumbprintAlgorithmInstance); + } + + Element publicConfigurationElement = XmlUtility.getElementByTagNameNS(extensionElement, "http://schemas.microsoft.com/windowsazure", "PublicConfiguration"); + if (publicConfigurationElement != null) { + String publicConfigurationInstance; + publicConfigurationInstance = publicConfigurationElement.getTextContent() != null ? new String(Base64.decode(publicConfigurationElement.getTextContent())) : null; + result.setPublicConfiguration(publicConfigurationInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Hosted Services operation lists the cloud services available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx for + * more information) + * + * @return The List Hosted Service operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Hosted Services operation lists the cloud services available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Hosted Service operation response. + */ + @Override + public HostedServiceListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element hostedServicesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "HostedServices"); + if (hostedServicesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostedServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "HostedService").size(); i1 = i1 + 1) { + org.w3c.dom.Element hostedServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostedServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "HostedService").get(i1)); + HostedServiceListResponse.HostedService hostedServiceInstance = new HostedServiceListResponse.HostedService(); + result.getHostedServices().add(hostedServiceInstance); + + Element urlElement = XmlUtility.getElementByTagNameNS(hostedServicesElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + hostedServiceInstance.setUri(urlInstance); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(hostedServicesElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + hostedServiceInstance.setServiceName(serviceNameInstance); + } + + Element hostedServicePropertiesElement = XmlUtility.getElementByTagNameNS(hostedServicesElement, "http://schemas.microsoft.com/windowsazure", "HostedServiceProperties"); + if (hostedServicePropertiesElement != null) { + HostedServiceProperties hostedServicePropertiesInstance = new HostedServiceProperties(); + hostedServiceInstance.setProperties(hostedServicePropertiesInstance); + + Element descriptionElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + hostedServicePropertiesInstance.setDescription(descriptionInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + hostedServicePropertiesInstance.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + hostedServicePropertiesInstance.setLocation(locationInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + hostedServicePropertiesInstance.setLabel(labelInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + HostedServiceStatus statusInstance; + statusInstance = HostedServiceStatus.valueOf(statusElement.getTextContent()); + hostedServicePropertiesInstance.setStatus(statusInstance); + } + + Element dateCreatedElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "DateCreated"); + if (dateCreatedElement != null) { + Calendar dateCreatedInstance; + dateCreatedInstance = DatatypeConverter.parseDateTime(dateCreatedElement.getTextContent()); + hostedServicePropertiesInstance.setDateCreated(dateCreatedInstance); + } + + Element dateLastModifiedElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "DateLastModified"); + if (dateLastModifiedElement != null) { + Calendar dateLastModifiedInstance; + dateLastModifiedInstance = DatatypeConverter.parseDateTime(dateLastModifiedElement.getTextContent()); + hostedServicePropertiesInstance.setDateLastModified(dateLastModifiedInstance); + } + + Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(hostedServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i2 = i2 + 1) { + org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i2)); + String extendedPropertiesKey = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + hostedServicePropertiesInstance.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Available Extensions operation lists the extensions that are + * available to add to your cloud service. In Windows Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx for + * more information) + * + * @return The List Available Extensions operation response. + */ + @Override + public Future listAvailableExtensionsAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceListAvailableExtensionsResponse call() throws Exception { + return listAvailableExtensions(); + } + }); + } + + /** + * The List Available Extensions operation lists the extensions that are + * available to add to your cloud service. In Windows Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Available Extensions operation response. + */ + @Override + public HostedServiceListAvailableExtensionsResponse listAvailableExtensions() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAvailableExtensionsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/extensions"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceListAvailableExtensionsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceListAvailableExtensionsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element extensionImagesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ExtensionImages"); + if (extensionImagesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionImagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtensionImage").size(); i1 = i1 + 1) { + org.w3c.dom.Element extensionImagesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionImagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtensionImage").get(i1)); + HostedServiceListAvailableExtensionsResponse.ExtensionImage extensionImageInstance = new HostedServiceListAvailableExtensionsResponse.ExtensionImage(); + result.getExtensionImages().add(extensionImageInstance); + + Element providerNameSpaceElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "ProviderNameSpace"); + if (providerNameSpaceElement != null) { + String providerNameSpaceInstance; + providerNameSpaceInstance = providerNameSpaceElement.getTextContent(); + extensionImageInstance.setProviderNamespace(providerNameSpaceInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + extensionImageInstance.setType(typeInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + extensionImageInstance.setLabel(labelInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + extensionImageInstance.setVersion(versionInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + extensionImageInstance.setDescription(descriptionInstance); + } + + Element thumbprintAlgorithmElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm"); + if (thumbprintAlgorithmElement != null) { + String thumbprintAlgorithmInstance; + thumbprintAlgorithmInstance = thumbprintAlgorithmElement.getTextContent(); + extensionImageInstance.setThumbprintAlgorithm(thumbprintAlgorithmInstance); + } + + Element hostingResourcesElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "HostingResources"); + if (hostingResourcesElement != null) { + String hostingResourcesInstance; + hostingResourcesInstance = hostingResourcesElement.getTextContent(); + extensionImageInstance.setHostingResources(hostingResourcesInstance); + } + + Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "PublicConfigurationSchema"); + if (publicConfigurationSchemaElement != null) { + String publicConfigurationSchemaInstance; + publicConfigurationSchemaInstance = publicConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(publicConfigurationSchemaElement.getTextContent())) : null; + extensionImageInstance.setPublicConfigurationSchema(publicConfigurationSchemaInstance); + } + + Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "PrivateConfigurationSchema"); + if (privateConfigurationSchemaElement != null) { + String privateConfigurationSchemaInstance; + privateConfigurationSchemaInstance = privateConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(privateConfigurationSchemaElement.getTextContent())) : null; + extensionImageInstance.setPrivateConfigurationSchema(privateConfigurationSchemaInstance); + } + + Element blockRoleUponFailureElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "BlockRoleUponFailure"); + if (blockRoleUponFailureElement != null && (blockRoleUponFailureElement.getTextContent() == null || blockRoleUponFailureElement.getTextContent().isEmpty() == true) == false) { + boolean blockRoleUponFailureInstance; + blockRoleUponFailureInstance = DatatypeConverter.parseBoolean(blockRoleUponFailureElement.getTextContent().toLowerCase()); + extensionImageInstance.setBlockRoleUponFailure(blockRoleUponFailureInstance); + } + + Element sampleConfigElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "SampleConfig"); + if (sampleConfigElement != null) { + String sampleConfigInstance; + sampleConfigInstance = sampleConfigElement.getTextContent() != null ? new String(Base64.decode(sampleConfigElement.getTextContent())) : null; + extensionImageInstance.setSampleConfig(sampleConfigInstance); + } + + Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "ReplicationCompleted"); + if (replicationCompletedElement != null && (replicationCompletedElement.getTextContent() == null || replicationCompletedElement.getTextContent().isEmpty() == true) == false) { + boolean replicationCompletedInstance; + replicationCompletedInstance = DatatypeConverter.parseBoolean(replicationCompletedElement.getTextContent().toLowerCase()); + extensionImageInstance.setReplicationCompleted(replicationCompletedInstance); + } + + Element eulaElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement != null) { + URI eulaInstance; + eulaInstance = new URI(eulaElement.getTextContent()); + extensionImageInstance.setEula(eulaInstance); + } + + Element privacyUriElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement.getTextContent()); + extensionImageInstance.setPrivacyUri(privacyUriInstance); + } + + Element homepageUriElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "HomepageUri"); + if (homepageUriElement != null) { + URI homepageUriInstance; + homepageUriInstance = new URI(homepageUriElement.getTextContent()); + extensionImageInstance.setHomepageUri(homepageUriInstance); + } + + Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "IsJsonExtension"); + if (isJsonExtensionElement != null && (isJsonExtensionElement.getTextContent() == null || isJsonExtensionElement.getTextContent().isEmpty() == true) == false) { + boolean isJsonExtensionInstance; + isJsonExtensionInstance = DatatypeConverter.parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase()); + extensionImageInstance.setIsJsonExtension(isJsonExtensionInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Extensions operation lists all of the extensions that were added + * to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169561.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @return The List Extensions operation response. + */ + @Override + public Future listExtensionsAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceListExtensionsResponse call() throws Exception { + return listExtensions(serviceName); + } + }); + } + + /** + * The List Extensions operation lists all of the extensions that were added + * to a cloud service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn169561.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Extensions operation response. + */ + @Override + public HostedServiceListExtensionsResponse listExtensions(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "listExtensionsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/extensions"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceListExtensionsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceListExtensionsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element extensionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Extensions"); + if (extensionsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").size(); i1 = i1 + 1) { + org.w3c.dom.Element extensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Extension").get(i1)); + HostedServiceListExtensionsResponse.Extension extensionInstance = new HostedServiceListExtensionsResponse.Extension(); + result.getExtensions().add(extensionInstance); + + Element providerNameSpaceElement = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "ProviderNameSpace"); + if (providerNameSpaceElement != null) { + String providerNameSpaceInstance; + providerNameSpaceInstance = providerNameSpaceElement.getTextContent(); + extensionInstance.setProviderNamespace(providerNameSpaceInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + extensionInstance.setType(typeInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + extensionInstance.setId(idInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + extensionInstance.setVersion(versionInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + extensionInstance.setThumbprint(thumbprintInstance); + } + + Element thumbprintAlgorithmElement = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm"); + if (thumbprintAlgorithmElement != null) { + String thumbprintAlgorithmInstance; + thumbprintAlgorithmInstance = thumbprintAlgorithmElement.getTextContent(); + extensionInstance.setThumbprintAlgorithm(thumbprintAlgorithmInstance); + } + + Element publicConfigurationElement = XmlUtility.getElementByTagNameNS(extensionsElement, "http://schemas.microsoft.com/windowsazure", "PublicConfiguration"); + if (publicConfigurationElement != null) { + String publicConfigurationInstance; + publicConfigurationInstance = publicConfigurationElement.getTextContent() != null ? new String(Base64.decode(publicConfigurationElement.getTextContent())) : null; + extensionInstance.setPublicConfiguration(publicConfigurationInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Extension Versions operation lists the versions of an extension + * that are available to add to a cloud service. In Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495437.aspx for + * more information) + * + * @param providerNamespace Required. The provider namespace. + * @param extensionType Required. The extension type name. + * @return The List Available Extensions operation response. + */ + @Override + public Future listExtensionVersionsAsync(final String providerNamespace, final String extensionType) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public HostedServiceListAvailableExtensionsResponse call() throws Exception { + return listExtensionVersions(providerNamespace, extensionType); + } + }); + } + + /** + * The List Extension Versions operation lists the versions of an extension + * that are available to add to a cloud service. In Azure, a process can + * run as an extension of a cloud service. For example, Remote Desktop + * Access or the Azure Diagnostics Agent can run as extensions to the cloud + * service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495437.aspx for + * more information) + * + * @param providerNamespace Required. The provider namespace. + * @param extensionType Required. The extension type name. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Available Extensions operation response. + */ + @Override + public HostedServiceListAvailableExtensionsResponse listExtensionVersions(String providerNamespace, String extensionType) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (providerNamespace == null) { + throw new NullPointerException("providerNamespace"); + } + if (extensionType == null) { + throw new NullPointerException("extensionType"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("providerNamespace", providerNamespace); + tracingParameters.put("extensionType", extensionType); + CloudTracing.enter(invocationId, this, "listExtensionVersionsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/extensions/" + providerNamespace.trim() + "/" + extensionType.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + HostedServiceListAvailableExtensionsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new HostedServiceListAvailableExtensionsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element extensionImagesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ExtensionImages"); + if (extensionImagesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionImagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtensionImage").size(); i1 = i1 + 1) { + org.w3c.dom.Element extensionImagesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extensionImagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtensionImage").get(i1)); + HostedServiceListAvailableExtensionsResponse.ExtensionImage extensionImageInstance = new HostedServiceListAvailableExtensionsResponse.ExtensionImage(); + result.getExtensionImages().add(extensionImageInstance); + + Element providerNameSpaceElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "ProviderNameSpace"); + if (providerNameSpaceElement != null) { + String providerNameSpaceInstance; + providerNameSpaceInstance = providerNameSpaceElement.getTextContent(); + extensionImageInstance.setProviderNamespace(providerNameSpaceInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + extensionImageInstance.setType(typeInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + extensionImageInstance.setLabel(labelInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + extensionImageInstance.setVersion(versionInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + extensionImageInstance.setDescription(descriptionInstance); + } + + Element thumbprintAlgorithmElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm"); + if (thumbprintAlgorithmElement != null) { + String thumbprintAlgorithmInstance; + thumbprintAlgorithmInstance = thumbprintAlgorithmElement.getTextContent(); + extensionImageInstance.setThumbprintAlgorithm(thumbprintAlgorithmInstance); + } + + Element hostingResourcesElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "HostingResources"); + if (hostingResourcesElement != null) { + String hostingResourcesInstance; + hostingResourcesInstance = hostingResourcesElement.getTextContent(); + extensionImageInstance.setHostingResources(hostingResourcesInstance); + } + + Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "PublicConfigurationSchema"); + if (publicConfigurationSchemaElement != null) { + String publicConfigurationSchemaInstance; + publicConfigurationSchemaInstance = publicConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(publicConfigurationSchemaElement.getTextContent())) : null; + extensionImageInstance.setPublicConfigurationSchema(publicConfigurationSchemaInstance); + } + + Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "PrivateConfigurationSchema"); + if (privateConfigurationSchemaElement != null) { + String privateConfigurationSchemaInstance; + privateConfigurationSchemaInstance = privateConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(privateConfigurationSchemaElement.getTextContent())) : null; + extensionImageInstance.setPrivateConfigurationSchema(privateConfigurationSchemaInstance); + } + + Element blockRoleUponFailureElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "BlockRoleUponFailure"); + if (blockRoleUponFailureElement != null && (blockRoleUponFailureElement.getTextContent() == null || blockRoleUponFailureElement.getTextContent().isEmpty() == true) == false) { + boolean blockRoleUponFailureInstance; + blockRoleUponFailureInstance = DatatypeConverter.parseBoolean(blockRoleUponFailureElement.getTextContent().toLowerCase()); + extensionImageInstance.setBlockRoleUponFailure(blockRoleUponFailureInstance); + } + + Element sampleConfigElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "SampleConfig"); + if (sampleConfigElement != null) { + String sampleConfigInstance; + sampleConfigInstance = sampleConfigElement.getTextContent() != null ? new String(Base64.decode(sampleConfigElement.getTextContent())) : null; + extensionImageInstance.setSampleConfig(sampleConfigInstance); + } + + Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "ReplicationCompleted"); + if (replicationCompletedElement != null && (replicationCompletedElement.getTextContent() == null || replicationCompletedElement.getTextContent().isEmpty() == true) == false) { + boolean replicationCompletedInstance; + replicationCompletedInstance = DatatypeConverter.parseBoolean(replicationCompletedElement.getTextContent().toLowerCase()); + extensionImageInstance.setReplicationCompleted(replicationCompletedInstance); + } + + Element eulaElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement != null) { + URI eulaInstance; + eulaInstance = new URI(eulaElement.getTextContent()); + extensionImageInstance.setEula(eulaInstance); + } + + Element privacyUriElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement.getTextContent()); + extensionImageInstance.setPrivacyUri(privacyUriInstance); + } + + Element homepageUriElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "HomepageUri"); + if (homepageUriElement != null) { + URI homepageUriInstance; + homepageUriInstance = new URI(homepageUriElement.getTextContent()); + extensionImageInstance.setHomepageUri(homepageUriInstance); + } + + Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(extensionImagesElement, "http://schemas.microsoft.com/windowsazure", "IsJsonExtension"); + if (isJsonExtensionElement != null && (isJsonExtensionElement.getTextContent() == null || isJsonExtensionElement.getTextContent().isEmpty() == true) == false) { + boolean isJsonExtensionInstance; + isJsonExtensionInstance = DatatypeConverter.parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase()); + extensionImageInstance.setIsJsonExtension(isJsonExtensionInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Update Hosted Service operation can update the label or description + * of a cloud service in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Update Hosted + * Service operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future updateAsync(final String serviceName, final HostedServiceUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return update(serviceName, parameters); + } + }); + } + + /** + * The Update Hosted Service operation can update the label or description + * of a cloud service in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx for + * more information) + * + * @param serviceName Required. The name of the cloud service. + * @param parameters Required. Parameters supplied to the Update Hosted + * Service operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse update(String serviceName, HostedServiceUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, InterruptedException, ExecutionException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { + throw new IllegalArgumentException("parameters.Description"); + } + int labelCount = (parameters.getDescription() != null ? 1 : 0) + (parameters.getLabel() != null ? 1 : 0); + if (labelCount < 1) { + throw new IllegalArgumentException("Expected at least one of parameters.Description, parameters.Label to be provided."); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element updateHostedServiceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateHostedService"); + requestDoc.appendChild(updateHostedServiceElement); + + if (parameters.getLabel() != null) { + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + updateHostedServiceElement.appendChild(labelElement); + } + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + updateHostedServiceElement.appendChild(descriptionElement); + } + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + updateHostedServiceElement.appendChild(extendedPropertiesDictionaryElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/OperatingSystemOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/OperatingSystemOperations.java new file mode 100644 index 0000000000000..698e13993ca73 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/OperatingSystemOperations.java @@ -0,0 +1,119 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.OperatingSystemListFamiliesResponse; +import com.microsoft.windowsazure.management.compute.models.OperatingSystemListResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* Operations for determining the version of the Azure Guest Operating System on +* which your service is running. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ff684169.aspx for more +* information) +*/ +public interface OperatingSystemOperations { + /** + * The List Operating Systems operation lists the versions of the guest + * operating system that are currently available in Windows Azure. The + * 2010-10-28 version of List Operating Systems also indicates what family + * an operating system version belongs to. Currently Azure supports two + * operating system families: the Azure guest operating system that is + * substantially compatible with Windows Server 2008 SP2, and the Azure + * guest operating system that is substantially compatible with Windows + * Server 2008 R2. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Operating Systems operation response. + */ + OperatingSystemListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Operating Systems operation lists the versions of the guest + * operating system that are currently available in Windows Azure. The + * 2010-10-28 version of List Operating Systems also indicates what family + * an operating system version belongs to. Currently Azure supports two + * operating system families: the Azure guest operating system that is + * substantially compatible with Windows Server 2008 SP2, and the Azure + * guest operating system that is substantially compatible with Windows + * Server 2008 R2. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx for + * more information) + * + * @return The List Operating Systems operation response. + */ + Future listAsync(); + + /** + * The List OS Families operation lists the guest operating system families + * available in Azure, and also lists the operating system versions + * available for each family. Currently Azure supports two operating system + * families: the Azure guest operating system that is substantially + * compatible with Windows Server 2008 SP2, and the Azure guest operating + * system that is substantially compatible with Windows Server 2008 R2. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx + * for more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Operating System Families operation response. + */ + OperatingSystemListFamiliesResponse listFamilies() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List OS Families operation lists the guest operating system families + * available in Azure, and also lists the operating system versions + * available for each family. Currently Azure supports two operating system + * families: the Azure guest operating system that is substantially + * compatible with Windows Server 2008 SP2, and the Azure guest operating + * system that is substantially compatible with Windows Server 2008 R2. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx + * for more information) + * + * @return The List Operating System Families operation response. + */ + Future listFamiliesAsync(); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/OperatingSystemOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/OperatingSystemOperationsImpl.java new file mode 100644 index 0000000000000..999a2b6f51d9c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/OperatingSystemOperationsImpl.java @@ -0,0 +1,430 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.OperatingSystemListFamiliesResponse; +import com.microsoft.windowsazure.management.compute.models.OperatingSystemListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Operations for determining the version of the Azure Guest Operating System on +* which your service is running. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ff684169.aspx for more +* information) +*/ +public class OperatingSystemOperationsImpl implements ServiceOperations, OperatingSystemOperations { + /** + * Initializes a new instance of the OperatingSystemOperationsImpl class. + * + * @param client Reference to the service client. + */ + OperatingSystemOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The List Operating Systems operation lists the versions of the guest + * operating system that are currently available in Windows Azure. The + * 2010-10-28 version of List Operating Systems also indicates what family + * an operating system version belongs to. Currently Azure supports two + * operating system families: the Azure guest operating system that is + * substantially compatible with Windows Server 2008 SP2, and the Azure + * guest operating system that is substantially compatible with Windows + * Server 2008 R2. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx for + * more information) + * + * @return The List Operating Systems operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperatingSystemListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Operating Systems operation lists the versions of the guest + * operating system that are currently available in Windows Azure. The + * 2010-10-28 version of List Operating Systems also indicates what family + * an operating system version belongs to. Currently Azure supports two + * operating system families: the Azure guest operating system that is + * substantially compatible with Windows Server 2008 SP2, and the Azure + * guest operating system that is substantially compatible with Windows + * Server 2008 R2. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Operating Systems operation response. + */ + @Override + public OperatingSystemListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/operatingsystems"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperatingSystemListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new OperatingSystemListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operatingSystemsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "OperatingSystems"); + if (operatingSystemsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operatingSystemsSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperatingSystem").size(); i1 = i1 + 1) { + org.w3c.dom.Element operatingSystemsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operatingSystemsSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperatingSystem").get(i1)); + OperatingSystemListResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListResponse.OperatingSystem(); + result.getOperatingSystems().add(operatingSystemInstance); + + Element versionElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + operatingSystemInstance.setVersion(versionInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + operatingSystemInstance.setLabel(labelInstance); + } + + Element isDefaultElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "IsDefault"); + if (isDefaultElement != null) { + boolean isDefaultInstance; + isDefaultInstance = DatatypeConverter.parseBoolean(isDefaultElement.getTextContent().toLowerCase()); + operatingSystemInstance.setIsDefault(isDefaultInstance); + } + + Element isActiveElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "IsActive"); + if (isActiveElement != null) { + boolean isActiveInstance; + isActiveInstance = DatatypeConverter.parseBoolean(isActiveElement.getTextContent().toLowerCase()); + operatingSystemInstance.setIsActive(isActiveInstance); + } + + Element familyElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "Family"); + if (familyElement != null) { + int familyInstance; + familyInstance = DatatypeConverter.parseInt(familyElement.getTextContent()); + operatingSystemInstance.setFamily(familyInstance); + } + + Element familyLabelElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "FamilyLabel"); + if (familyLabelElement != null) { + String familyLabelInstance; + familyLabelInstance = familyLabelElement.getTextContent() != null ? new String(Base64.decode(familyLabelElement.getTextContent())) : null; + operatingSystemInstance.setFamilyLabel(familyLabelInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List OS Families operation lists the guest operating system families + * available in Azure, and also lists the operating system versions + * available for each family. Currently Azure supports two operating system + * families: the Azure guest operating system that is substantially + * compatible with Windows Server 2008 SP2, and the Azure guest operating + * system that is substantially compatible with Windows Server 2008 R2. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx + * for more information) + * + * @return The List Operating System Families operation response. + */ + @Override + public Future listFamiliesAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperatingSystemListFamiliesResponse call() throws Exception { + return listFamilies(); + } + }); + } + + /** + * The List OS Families operation lists the guest operating system families + * available in Azure, and also lists the operating system versions + * available for each family. Currently Azure supports two operating system + * families: the Azure guest operating system that is substantially + * compatible with Windows Server 2008 SP2, and the Azure guest operating + * system that is substantially compatible with Windows Server 2008 R2. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx + * for more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Operating System Families operation response. + */ + @Override + public OperatingSystemListFamiliesResponse listFamilies() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listFamiliesAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/operatingsystemfamilies"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperatingSystemListFamiliesResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new OperatingSystemListFamiliesResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operatingSystemFamiliesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamilies"); + if (operatingSystemFamiliesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operatingSystemFamiliesSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily").size(); i1 = i1 + 1) { + org.w3c.dom.Element operatingSystemFamiliesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operatingSystemFamiliesSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily").get(i1)); + OperatingSystemListFamiliesResponse.OperatingSystemFamily operatingSystemFamilyInstance = new OperatingSystemListFamiliesResponse.OperatingSystemFamily(); + result.getOperatingSystemFamilies().add(operatingSystemFamilyInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + int nameInstance; + nameInstance = DatatypeConverter.parseInt(nameElement.getTextContent()); + operatingSystemFamilyInstance.setName(nameInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + operatingSystemFamilyInstance.setLabel(labelInstance); + } + + Element operatingSystemsSequenceElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement, "http://schemas.microsoft.com/windowsazure", "OperatingSystems"); + if (operatingSystemsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operatingSystemsSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperatingSystem").size(); i2 = i2 + 1) { + org.w3c.dom.Element operatingSystemsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operatingSystemsSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperatingSystem").get(i2)); + OperatingSystemListFamiliesResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListFamiliesResponse.OperatingSystem(); + operatingSystemFamilyInstance.getOperatingSystems().add(operatingSystemInstance); + + Element versionElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + operatingSystemInstance.setVersion(versionInstance); + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance2; + labelInstance2 = labelElement2.getTextContent() != null ? new String(Base64.decode(labelElement2.getTextContent())) : null; + operatingSystemInstance.setLabel(labelInstance2); + } + + Element isDefaultElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "IsDefault"); + if (isDefaultElement != null) { + boolean isDefaultInstance; + isDefaultInstance = DatatypeConverter.parseBoolean(isDefaultElement.getTextContent().toLowerCase()); + operatingSystemInstance.setIsDefault(isDefaultInstance); + } + + Element isActiveElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement, "http://schemas.microsoft.com/windowsazure", "IsActive"); + if (isActiveElement != null) { + boolean isActiveInstance; + isActiveInstance = DatatypeConverter.parseBoolean(isActiveElement.getTextContent().toLowerCase()); + operatingSystemInstance.setIsActive(isActiveInstance); + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ServiceCertificateOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ServiceCertificateOperations.java new file mode 100644 index 0000000000000..2dbe7dfb6386c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ServiceCertificateOperations.java @@ -0,0 +1,312 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateCreateParameters; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateDeleteParameters; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateGetParameters; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateGetResponse; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateListResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* Operations for managing service certificates for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for more +* information) +*/ +public interface ServiceCertificateOperations { + /** + * The Begin Creating Service Certificate operation adds a certificate to a + * hosted service. This operation is an asynchronous operation. To + * determine whether the management service has finished processing the + * request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Service Certificate operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginCreating(String serviceName, ServiceCertificateCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Creating Service Certificate operation adds a certificate to a + * hosted service. This operation is an asynchronous operation. To + * determine whether the management service has finished processing the + * request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Service Certificate operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginCreatingAsync(String serviceName, ServiceCertificateCreateParameters parameters); + + /** + * The Begin Deleting Service Certificate operation deletes a service + * certificate from the certificate store of a hosted service. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Begin Deleting + * Service Certificate operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeleting(ServiceCertificateDeleteParameters parameters) throws IOException, ServiceException; + + /** + * The Begin Deleting Service Certificate operation deletes a service + * certificate from the certificate store of a hosted service. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Begin Deleting + * Service Certificate operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingAsync(ServiceCertificateDeleteParameters parameters); + + /** + * The Create Service Certificate operation adds a certificate to a hosted + * service. This operation is an asynchronous operation. To determine + * whether the management service has finished processing the request, call + * Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Create Service + * Certificate operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse create(String serviceName, ServiceCertificateCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException; + + /** + * The Create Service Certificate operation adds a certificate to a hosted + * service. This operation is an asynchronous operation. To determine + * whether the management service has finished processing the request, call + * Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Create Service + * Certificate operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future createAsync(String serviceName, ServiceCertificateCreateParameters parameters); + + /** + * The Delete Service Certificate operation deletes a service certificate + * from the certificate store of a hosted service. This operation is an + * asynchronous operation. To determine whether the management service has + * finished processing the request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Delete Service + * Certificate operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse delete(ServiceCertificateDeleteParameters parameters) throws IOException, ServiceException, InterruptedException, ExecutionException; + + /** + * The Delete Service Certificate operation deletes a service certificate + * from the certificate store of a hosted service. This operation is an + * asynchronous operation. To determine whether the management service has + * finished processing the request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Delete Service + * Certificate operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteAsync(ServiceCertificateDeleteParameters parameters); + + /** + * The Get Service Certificate operation returns the public data for the + * specified X.509 certificate associated with a hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Get Service + * Certificate operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Service Certificate operation response. + */ + ServiceCertificateGetResponse get(ServiceCertificateGetParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Service Certificate operation returns the public data for the + * specified X.509 certificate associated with a hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Get Service + * Certificate operation. + * @return The Get Service Certificate operation response. + */ + Future getAsync(ServiceCertificateGetParameters parameters); + + /** + * The List Service Certificates operation lists all of the service + * certificates associated with the specified hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your hosted service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Service Certificates operation response. + */ + ServiceCertificateListResponse list(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Service Certificates operation lists all of the service + * certificates associated with the specified hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your hosted service. + * @return The List Service Certificates operation response. + */ + Future listAsync(String serviceName); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ServiceCertificateOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ServiceCertificateOperationsImpl.java new file mode 100644 index 0000000000000..c4fc7d354fb38 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/ServiceCertificateOperationsImpl.java @@ -0,0 +1,922 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateCreateParameters; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateDeleteParameters; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateGetParameters; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateGetResponse; +import com.microsoft.windowsazure.management.compute.models.ServiceCertificateListResponse; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Operations for managing service certificates for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for more +* information) +*/ +public class ServiceCertificateOperationsImpl implements ServiceOperations, ServiceCertificateOperations { + /** + * Initializes a new instance of the ServiceCertificateOperationsImpl class. + * + * @param client Reference to the service client. + */ + ServiceCertificateOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The Begin Creating Service Certificate operation adds a certificate to a + * hosted service. This operation is an asynchronous operation. To + * determine whether the management service has finished processing the + * request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Service Certificate operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCreatingAsync(final String serviceName, final ServiceCertificateCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginCreating(serviceName, parameters); + } + }); + } + + /** + * The Begin Creating Service Certificate operation adds a certificate to a + * hosted service. This operation is an asynchronous operation. To + * determine whether the management service has finished processing the + * request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Service Certificate operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginCreating(String serviceName, ServiceCertificateCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getData() == null) { + throw new NullPointerException("parameters.Data"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/certificates"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element certificateFileElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateFile"); + requestDoc.appendChild(certificateFileElement); + + Element dataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Data"); + dataElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData()))); + certificateFileElement.appendChild(dataElement); + + Element certificateFormatElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateFormat"); + certificateFormatElement.appendChild(requestDoc.createTextNode(ComputeManagementClientImpl.certificateFormatToString(parameters.getCertificateFormat()))); + certificateFileElement.appendChild(certificateFormatElement); + + if (parameters.getPassword() != null) { + Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(parameters.getPassword())); + certificateFileElement.appendChild(passwordElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Deleting Service Certificate operation deletes a service + * certificate from the certificate store of a hosted service. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Begin Deleting + * Service Certificate operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingAsync(final ServiceCertificateDeleteParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeleting(parameters); + } + }); + } + + /** + * The Begin Deleting Service Certificate operation deletes a service + * certificate from the certificate store of a hosted service. This + * operation is an asynchronous operation. To determine whether the + * management service has finished processing the request, call Get + * Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Begin Deleting + * Service Certificate operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeleting(ServiceCertificateDeleteParameters parameters) throws IOException, ServiceException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getServiceName() == null) { + throw new NullPointerException("parameters.ServiceName"); + } + // TODO: Validate parameters.ServiceName is a valid DNS name. + if (parameters.getThumbprint() == null) { + throw new NullPointerException("parameters.Thumbprint"); + } + if (parameters.getThumbprintAlgorithm() == null) { + throw new NullPointerException("parameters.ThumbprintAlgorithm"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + parameters.getServiceName().trim() + "/certificates/" + parameters.getThumbprintAlgorithm().trim() + "-" + parameters.getThumbprint().trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Create Service Certificate operation adds a certificate to a hosted + * service. This operation is an asynchronous operation. To determine + * whether the management service has finished processing the request, call + * Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Create Service + * Certificate operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future createAsync(final String serviceName, final ServiceCertificateCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return create(serviceName, parameters); + } + }); + } + + /** + * The Create Service Certificate operation adds a certificate to a hosted + * service. This operation is an asynchronous operation. To determine + * whether the management service has finished processing the request, call + * Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your service. + * @param parameters Required. Parameters supplied to the Create Service + * Certificate operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse create(String serviceName, ServiceCertificateCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getServiceCertificatesOperations().beginCreatingAsync(serviceName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Service Certificate operation deletes a service certificate + * from the certificate store of a hosted service. This operation is an + * asynchronous operation. To determine whether the management service has + * finished processing the request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Delete Service + * Certificate operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteAsync(final ServiceCertificateDeleteParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return delete(parameters); + } + }); + } + + /** + * The Delete Service Certificate operation deletes a service certificate + * from the certificate store of a hosted service. This operation is an + * asynchronous operation. To determine whether the management service has + * finished processing the request, call Get Operation Status. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Delete Service + * Certificate operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse delete(ServiceCertificateDeleteParameters parameters) throws IOException, ServiceException, InterruptedException, ExecutionException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getServiceCertificatesOperations().beginDeletingAsync(parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Get Service Certificate operation returns the public data for the + * specified X.509 certificate associated with a hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Get Service + * Certificate operation. + * @return The Get Service Certificate operation response. + */ + @Override + public Future getAsync(final ServiceCertificateGetParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServiceCertificateGetResponse call() throws Exception { + return get(parameters); + } + }); + } + + /** + * The Get Service Certificate operation returns the public data for the + * specified X.509 certificate associated with a hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Get Service + * Certificate operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Service Certificate operation response. + */ + @Override + public ServiceCertificateGetResponse get(ServiceCertificateGetParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getServiceName() == null) { + throw new NullPointerException("parameters.ServiceName"); + } + // TODO: Validate parameters.ServiceName is a valid DNS name. + if (parameters.getThumbprint() == null) { + throw new NullPointerException("parameters.Thumbprint"); + } + if (parameters.getThumbprintAlgorithm() == null) { + throw new NullPointerException("parameters.ThumbprintAlgorithm"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + parameters.getServiceName().trim() + "/certificates/" + parameters.getThumbprintAlgorithm().trim() + "-" + parameters.getThumbprint().trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServiceCertificateGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServiceCertificateGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element certificateElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Certificate"); + if (certificateElement != null) { + Element dataElement = XmlUtility.getElementByTagNameNS(certificateElement, "http://schemas.microsoft.com/windowsazure", "Data"); + if (dataElement != null) { + byte[] dataInstance; + dataInstance = dataElement.getTextContent() != null ? Base64.decode(dataElement.getTextContent()) : null; + result.setData(dataInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Service Certificates operation lists all of the service + * certificates associated with the specified hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your hosted service. + * @return The List Service Certificates operation response. + */ + @Override + public Future listAsync(final String serviceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServiceCertificateListResponse call() throws Exception { + return list(serviceName); + } + }); + } + + /** + * The List Service Certificates operation lists all of the service + * certificates associated with the specified hosted service. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @param serviceName Required. The DNS prefix name of your hosted service. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Service Certificates operation response. + */ + @Override + public ServiceCertificateListResponse list(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + // TODO: Validate serviceName is a valid DNS name. + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/certificates"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServiceCertificateListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServiceCertificateListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element certificatesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Certificates"); + if (certificatesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(certificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").size(); i1 = i1 + 1) { + org.w3c.dom.Element certificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(certificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").get(i1)); + ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate(); + result.getCertificates().add(certificateInstance); + + Element certificateUrlElement = XmlUtility.getElementByTagNameNS(certificatesElement, "http://schemas.microsoft.com/windowsazure", "CertificateUrl"); + if (certificateUrlElement != null) { + URI certificateUrlInstance; + certificateUrlInstance = new URI(certificateUrlElement.getTextContent()); + certificateInstance.setCertificateUri(certificateUrlInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(certificatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + certificateInstance.setThumbprint(thumbprintInstance); + } + + Element thumbprintAlgorithmElement = XmlUtility.getElementByTagNameNS(certificatesElement, "http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm"); + if (thumbprintAlgorithmElement != null) { + String thumbprintAlgorithmInstance; + thumbprintAlgorithmInstance = thumbprintAlgorithmElement.getTextContent(); + certificateInstance.setThumbprintAlgorithm(thumbprintAlgorithmInstance); + } + + Element dataElement = XmlUtility.getElementByTagNameNS(certificatesElement, "http://schemas.microsoft.com/windowsazure", "Data"); + if (dataElement != null) { + byte[] dataInstance; + dataInstance = dataElement.getTextContent() != null ? Base64.decode(dataElement.getTextContent()) : null; + certificateInstance.setData(dataInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineDiskOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineDiskOperations.java new file mode 100644 index 0000000000000..2d4a51388af4f --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineDiskOperations.java @@ -0,0 +1,472 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDataDiskCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDataDiskGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDataDiskUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskCreateResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskListResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskUpdateResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the disks in your +* subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx for more +* information) +*/ +public interface VirtualMachineDiskOperations { + /** + * The Begin Deleting Data Disk operation removes the specified data disk + * from a virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeletingDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, boolean deleteFromStorage) throws IOException, ServiceException; + + /** + * The Begin Deleting Data Disk operation removes the specified data disk + * from a virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingDataDiskAsync(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, boolean deleteFromStorage); + + /** + * The Create Data Disk operation adds a data disk to a virtual machine. + * There are three ways to create the data disk using the Add Data Disk + * operation. Option 1 - Attach an empty data disk to the role by + * specifying the disk label and location of the disk image. Do not include + * the DiskName and SourceMediaLink elements in the request body. Include + * the MediaLink element and reference a blob that is in the same + * geographical region as the role. You can also omit the MediaLink + * element. In this usage, Azure will create the data disk in the storage + * account configured as default for the role. Option 2 - Attach an + * existing data disk that is in the image repository. Do not include the + * DiskName and SourceMediaLink elements in the request body. Specify the + * data disk to use by including the DiskName element. Note: If included + * the in the response body, the MediaLink and LogicalDiskSizeInGB elements + * are ignored. Option 3 - Specify the location of a blob in your storage + * account that contain a disk image to use. Include the SourceMediaLink + * element. Note: If the MediaLink element isincluded, it is ignored. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Data Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse createDataDisk(String serviceName, String deploymentName, String roleName, VirtualMachineDataDiskCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Create Data Disk operation adds a data disk to a virtual machine. + * There are three ways to create the data disk using the Add Data Disk + * operation. Option 1 - Attach an empty data disk to the role by + * specifying the disk label and location of the disk image. Do not include + * the DiskName and SourceMediaLink elements in the request body. Include + * the MediaLink element and reference a blob that is in the same + * geographical region as the role. You can also omit the MediaLink + * element. In this usage, Azure will create the data disk in the storage + * account configured as default for the role. Option 2 - Attach an + * existing data disk that is in the image repository. Do not include the + * DiskName and SourceMediaLink elements in the request body. Specify the + * data disk to use by including the DiskName element. Note: If included + * the in the response body, the MediaLink and LogicalDiskSizeInGB elements + * are ignored. Option 3 - Specify the location of a blob in your storage + * account that contain a disk image to use. Include the SourceMediaLink + * element. Note: If the MediaLink element isincluded, it is ignored. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Data Disk operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future createDataDiskAsync(String serviceName, String deploymentName, String roleName, VirtualMachineDataDiskCreateParameters parameters); + + /** + * The Create Disk operation adds a disk to the user image repository. The + * disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine disk associated with your subscription. + */ + VirtualMachineDiskCreateResponse createDisk(VirtualMachineDiskCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException; + + /** + * The Create Disk operation adds a disk to the user image repository. The + * disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Disk operation. + * @return A virtual machine disk associated with your subscription. + */ + Future createDiskAsync(VirtualMachineDiskCreateParameters parameters); + + /** + * The Delete Data Disk operation removes the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse deleteDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, boolean deleteFromStorage) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Delete Data Disk operation removes the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteDataDiskAsync(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, boolean deleteFromStorage); + + /** + * The Delete Disk operation deletes the specified data or operating system + * disk from your image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157200.aspx for + * more information) + * + * @param name Required. The name of the disk to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse deleteDisk(String name, boolean deleteFromStorage) throws IOException, ServiceException; + + /** + * The Delete Disk operation deletes the specified data or operating system + * disk from your image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157200.aspx for + * more information) + * + * @param name Required. The name of the disk to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteDiskAsync(String name, boolean deleteFromStorage); + + /** + * The Get Data Disk operation retrieves the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157180.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Data Disk operation response. + */ + VirtualMachineDataDiskGetResponse getDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Data Disk operation retrieves the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157180.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @return The Get Data Disk operation response. + */ + Future getDataDiskAsync(String serviceName, String deploymentName, String roleName, int logicalUnitNumber); + + /** + * The Get Disk operation retrieves a disk from the user image repository. + * The disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine disk associated with your subscription. + */ + VirtualMachineDiskGetResponse getDisk(String name) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Disk operation retrieves a disk from the user image repository. + * The disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk. + * @return A virtual machine disk associated with your subscription. + */ + Future getDiskAsync(String name); + + /** + * The List Disks operation retrieves a list of the disks in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157176.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Disks operation response. + */ + VirtualMachineDiskListResponse listDisks() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Disks operation retrieves a list of the disks in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157176.aspx for + * more information) + * + * @return The List Disks operation response. + */ + Future listDisksAsync(); + + /** + * The Update Data Disk operation updates the specified data disk attached + * to the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157190.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Data Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse updateDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, VirtualMachineDataDiskUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Update Data Disk operation updates the specified data disk attached + * to the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157190.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Data Disk operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future updateDataDiskAsync(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, VirtualMachineDataDiskUpdateParameters parameters); + + /** + * The Add Disk operation adds a disk to the user image repository. The disk + * can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk being updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine disk associated with your subscription. + */ + VirtualMachineDiskUpdateResponse updateDisk(String name, VirtualMachineDiskUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException; + + /** + * The Add Disk operation adds a disk to the user image repository. The disk + * can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk being updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Disk operation. + * @return A virtual machine disk associated with your subscription. + */ + Future updateDiskAsync(String name, VirtualMachineDiskUpdateParameters parameters); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineDiskOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineDiskOperationsImpl.java new file mode 100644 index 0000000000000..12a6264d505c1 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineDiskOperationsImpl.java @@ -0,0 +1,2000 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualHardDiskHostCaching; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDataDiskCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDataDiskGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDataDiskUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskCreateResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskListResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineDiskUpdateResponse; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the disks in your +* subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx for more +* information) +*/ +public class VirtualMachineDiskOperationsImpl implements ServiceOperations, VirtualMachineDiskOperations { + /** + * Initializes a new instance of the VirtualMachineDiskOperationsImpl class. + * + * @param client Reference to the service client. + */ + VirtualMachineDiskOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The Begin Deleting Data Disk operation removes the specified data disk + * from a virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingDataDiskAsync(final String serviceName, final String deploymentName, final String roleName, final int logicalUnitNumber, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeletingDataDisk(serviceName, deploymentName, roleName, logicalUnitNumber, deleteFromStorage); + } + }); + } + + /** + * The Begin Deleting Data Disk operation removes the specified data disk + * from a virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeletingDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, boolean deleteFromStorage) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (roleName == null) { + throw new NullPointerException("roleName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleName", roleName); + tracingParameters.put("logicalUnitNumber", logicalUnitNumber); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "beginDeletingDataDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles/" + roleName.trim() + "/DataDisks/" + logicalUnitNumber + "?"; + if (deleteFromStorage == true) { + url = url + "comp=" + "media"; + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Create Data Disk operation adds a data disk to a virtual machine. + * There are three ways to create the data disk using the Add Data Disk + * operation. Option 1 - Attach an empty data disk to the role by + * specifying the disk label and location of the disk image. Do not include + * the DiskName and SourceMediaLink elements in the request body. Include + * the MediaLink element and reference a blob that is in the same + * geographical region as the role. You can also omit the MediaLink + * element. In this usage, Azure will create the data disk in the storage + * account configured as default for the role. Option 2 - Attach an + * existing data disk that is in the image repository. Do not include the + * DiskName and SourceMediaLink elements in the request body. Specify the + * data disk to use by including the DiskName element. Note: If included + * the in the response body, the MediaLink and LogicalDiskSizeInGB elements + * are ignored. Option 3 - Specify the location of a blob in your storage + * account that contain a disk image to use. Include the SourceMediaLink + * element. Note: If the MediaLink element isincluded, it is ignored. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Data Disk operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future createDataDiskAsync(final String serviceName, final String deploymentName, final String roleName, final VirtualMachineDataDiskCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return createDataDisk(serviceName, deploymentName, roleName, parameters); + } + }); + } + + /** + * The Create Data Disk operation adds a data disk to a virtual machine. + * There are three ways to create the data disk using the Add Data Disk + * operation. Option 1 - Attach an empty data disk to the role by + * specifying the disk label and location of the disk image. Do not include + * the DiskName and SourceMediaLink elements in the request body. Include + * the MediaLink element and reference a blob that is in the same + * geographical region as the role. You can also omit the MediaLink + * element. In this usage, Azure will create the data disk in the storage + * account configured as default for the role. Option 2 - Attach an + * existing data disk that is in the image repository. Do not include the + * DiskName and SourceMediaLink elements in the request body. Specify the + * data disk to use by including the DiskName element. Note: If included + * the in the response body, the MediaLink and LogicalDiskSizeInGB elements + * are ignored. Option 3 - Specify the location of a blob in your storage + * account that contain a disk image to use. Include the SourceMediaLink + * element. Note: If the MediaLink element isincluded, it is ignored. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Data Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse createDataDisk(String serviceName, String deploymentName, String roleName, VirtualMachineDataDiskCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (roleName == null) { + throw new NullPointerException("roleName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getMediaLinkUri() == null) { + throw new NullPointerException("parameters.MediaLinkUri"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleName", roleName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createDataDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles/" + roleName.trim() + "/DataDisks"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element dataVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk"); + requestDoc.appendChild(dataVirtualHardDiskElement); + + Element hostCachingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement.appendChild(requestDoc.createTextNode(parameters.getHostCaching().toString())); + dataVirtualHardDiskElement.appendChild(hostCachingElement); + + if (parameters.getLabel() != null) { + Element diskLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); + dataVirtualHardDiskElement.appendChild(diskLabelElement); + } + + if (parameters.getName() != null) { + Element diskNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + dataVirtualHardDiskElement.appendChild(diskNameElement); + } + + if (parameters.getLogicalUnitNumber() != null) { + Element lunElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Lun"); + lunElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getLogicalUnitNumber()))); + dataVirtualHardDiskElement.appendChild(lunElement); + } + + Element logicalDiskSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getLogicalDiskSizeInGB()))); + dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement); + + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString())); + dataVirtualHardDiskElement.appendChild(mediaLinkElement); + + if (parameters.getSourceMediaLinkUri() != null) { + Element sourceMediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + sourceMediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getSourceMediaLinkUri().toString())); + dataVirtualHardDiskElement.appendChild(sourceMediaLinkElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Create Disk operation adds a disk to the user image repository. The + * disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Disk operation. + * @return A virtual machine disk associated with your subscription. + */ + @Override + public Future createDiskAsync(final VirtualMachineDiskCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineDiskCreateResponse call() throws Exception { + return createDisk(parameters); + } + }); + } + + /** + * The Create Disk operation adds a disk to the user image repository. The + * disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine disk associated with your subscription. + */ + @Override + public VirtualMachineDiskCreateResponse createDisk(VirtualMachineDiskCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getMediaLinkUri() == null) { + throw new NullPointerException("parameters.MediaLinkUri"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/disks"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element diskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Disk"); + requestDoc.appendChild(diskElement); + + if (parameters.getOperatingSystemType() != null) { + Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS"); + osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType())); + diskElement.appendChild(osElement); + } + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); + diskElement.appendChild(labelElement); + + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString())); + diskElement.appendChild(mediaLinkElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + diskElement.appendChild(nameElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineDiskCreateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineDiskCreateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element diskElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Disk"); + if (diskElement2 != null) { + Element osElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement2 != null) { + String osInstance; + osInstance = osElement2.getTextContent(); + result.setOperatingSystem(osInstance); + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance; + labelInstance = labelElement2.getTextContent(); + result.setLabel(labelInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + result.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + result.setLocation(locationInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + result.setLogicalSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement2.getTextContent()); + result.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + result.setName(nameInstance); + } + + Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); + if (sourceImageNameElement != null) { + String sourceImageNameInstance; + sourceImageNameInstance = sourceImageNameElement.getTextContent(); + result.setSourceImageName(sourceImageNameInstance); + } + + Element attachedToElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "AttachedTo"); + if (attachedToElement != null) { + VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails attachedToInstance = new VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails(); + result.setUsageDetails(attachedToInstance); + + Element hostedServiceNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "HostedServiceName"); + if (hostedServiceNameElement != null) { + String hostedServiceNameInstance; + hostedServiceNameInstance = hostedServiceNameElement.getTextContent(); + attachedToInstance.setHostedServiceName(hostedServiceNameInstance); + } + + Element deploymentNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "DeploymentName"); + if (deploymentNameElement != null) { + String deploymentNameInstance; + deploymentNameInstance = deploymentNameElement.getTextContent(); + attachedToInstance.setDeploymentName(deploymentNameInstance); + } + + Element roleNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + attachedToInstance.setRoleName(roleNameInstance); + } + } + + Element isPremiumElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement != null && (isPremiumElement.getTextContent() == null || isPremiumElement.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement.getTextContent().toLowerCase()); + result.setIsPremium(isPremiumInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Data Disk operation removes the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteDataDiskAsync(final String serviceName, final String deploymentName, final String roleName, final int logicalUnitNumber, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return deleteDataDisk(serviceName, deploymentName, roleName, logicalUnitNumber, deleteFromStorage); + } + }); + } + + /** + * The Delete Data Disk operation removes the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157179.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to delete the data disk + * from. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse deleteDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, boolean deleteFromStorage) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleName", roleName); + tracingParameters.put("logicalUnitNumber", logicalUnitNumber); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "deleteDataDiskAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachineDisksOperations().beginDeletingDataDiskAsync(serviceName, deploymentName, roleName, logicalUnitNumber, deleteFromStorage).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Disk operation deletes the specified data or operating system + * disk from your image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157200.aspx for + * more information) + * + * @param name Required. The name of the disk to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteDiskAsync(final String name, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return deleteDisk(name, deleteFromStorage); + } + }); + } + + /** + * The Delete Disk operation deletes the specified data or operating system + * disk from your image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157200.aspx for + * more information) + * + * @param name Required. The name of the disk to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * disk should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse deleteDisk(String name, boolean deleteFromStorage) throws IOException, ServiceException { + // Validate + if (name == null) { + throw new NullPointerException("name"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("name", name); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "deleteDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/disks/" + name.trim() + "?"; + if (deleteFromStorage == true) { + url = url + "comp=" + "media"; + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Data Disk operation retrieves the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157180.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @return The Get Data Disk operation response. + */ + @Override + public Future getDataDiskAsync(final String serviceName, final String deploymentName, final String roleName, final int logicalUnitNumber) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineDataDiskGetResponse call() throws Exception { + return getDataDisk(serviceName, deploymentName, roleName, logicalUnitNumber); + } + }); + } + + /** + * The Get Data Disk operation retrieves the specified data disk from a + * virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157180.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Data Disk operation response. + */ + @Override + public VirtualMachineDataDiskGetResponse getDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (roleName == null) { + throw new NullPointerException("roleName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleName", roleName); + tracingParameters.put("logicalUnitNumber", logicalUnitNumber); + CloudTracing.enter(invocationId, this, "getDataDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles/" + roleName.trim() + "/DataDisks/" + logicalUnitNumber; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineDataDiskGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineDataDiskGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element dataVirtualHardDiskElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk"); + if (dataVirtualHardDiskElement != null) { + Element hostCachingElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement != null) { + VirtualHardDiskHostCaching hostCachingInstance; + hostCachingInstance = VirtualHardDiskHostCaching.valueOf(hostCachingElement.getTextContent()); + result.setHostCaching(hostCachingInstance); + } + + Element diskLabelElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement != null) { + String diskLabelInstance; + diskLabelInstance = diskLabelElement.getTextContent(); + result.setLabel(diskLabelInstance); + } + + Element diskNameElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement != null) { + String diskNameInstance; + diskNameInstance = diskNameElement.getTextContent(); + result.setName(diskNameInstance); + } + + Element lunElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "Lun"); + if (lunElement != null && (lunElement.getTextContent() == null || lunElement.getTextContent().isEmpty() == true) == false) { + int lunInstance; + lunInstance = DatatypeConverter.parseInt(lunElement.getTextContent()); + result.setLogicalUnitNumber(lunInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + result.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + result.setMediaLinkUri(mediaLinkInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Disk operation retrieves a disk from the user image repository. + * The disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk. + * @return A virtual machine disk associated with your subscription. + */ + @Override + public Future getDiskAsync(final String name) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineDiskGetResponse call() throws Exception { + return getDisk(name); + } + }); + } + + /** + * The Get Disk operation retrieves a disk from the user image repository. + * The disk can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine disk associated with your subscription. + */ + @Override + public VirtualMachineDiskGetResponse getDisk(String name) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (name == null) { + throw new NullPointerException("name"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("name", name); + CloudTracing.enter(invocationId, this, "getDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/disks/" + name.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineDiskGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineDiskGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element diskElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Disk"); + if (diskElement != null) { + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + result.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + result.setLocation(locationInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + result.setLabel(labelInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + result.setLogicalSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + result.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + result.setOperatingSystemType(osInstance); + } + + Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); + if (sourceImageNameElement != null) { + String sourceImageNameInstance; + sourceImageNameInstance = sourceImageNameElement.getTextContent(); + result.setSourceImageName(sourceImageNameInstance); + } + + Element attachedToElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "AttachedTo"); + if (attachedToElement != null) { + VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails attachedToInstance = new VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails(); + result.setUsageDetails(attachedToInstance); + + Element hostedServiceNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "HostedServiceName"); + if (hostedServiceNameElement != null) { + String hostedServiceNameInstance; + hostedServiceNameInstance = hostedServiceNameElement.getTextContent(); + attachedToInstance.setHostedServiceName(hostedServiceNameInstance); + } + + Element deploymentNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "DeploymentName"); + if (deploymentNameElement != null) { + String deploymentNameInstance; + deploymentNameInstance = deploymentNameElement.getTextContent(); + attachedToInstance.setDeploymentName(deploymentNameInstance); + } + + Element roleNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + attachedToInstance.setRoleName(roleNameInstance); + } + } + + Element isCorruptedElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "IsCorrupted"); + if (isCorruptedElement != null && (isCorruptedElement.getTextContent() == null || isCorruptedElement.getTextContent().isEmpty() == true) == false) { + boolean isCorruptedInstance; + isCorruptedInstance = DatatypeConverter.parseBoolean(isCorruptedElement.getTextContent().toLowerCase()); + result.setIsCorrupted(isCorruptedInstance); + } + + Element isPremiumElement = XmlUtility.getElementByTagNameNS(diskElement, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement != null && (isPremiumElement.getTextContent() == null || isPremiumElement.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement.getTextContent().toLowerCase()); + result.setIsPremium(isPremiumInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Disks operation retrieves a list of the disks in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157176.aspx for + * more information) + * + * @return The List Disks operation response. + */ + @Override + public Future listDisksAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineDiskListResponse call() throws Exception { + return listDisks(); + } + }); + } + + /** + * The List Disks operation retrieves a list of the disks in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157176.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Disks operation response. + */ + @Override + public VirtualMachineDiskListResponse listDisks() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listDisksAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/disks"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineDiskListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineDiskListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element disksSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Disks"); + if (disksSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(disksSequenceElement, "http://schemas.microsoft.com/windowsazure", "Disk").size(); i1 = i1 + 1) { + org.w3c.dom.Element disksElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(disksSequenceElement, "http://schemas.microsoft.com/windowsazure", "Disk").get(i1)); + VirtualMachineDiskListResponse.VirtualMachineDisk diskInstance = new VirtualMachineDiskListResponse.VirtualMachineDisk(); + result.getDisks().add(diskInstance); + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + diskInstance.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + diskInstance.setLocation(locationInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + diskInstance.setLabel(labelInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + diskInstance.setLogicalSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + diskInstance.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + diskInstance.setName(nameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + diskInstance.setOperatingSystemType(osInstance); + } + + Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); + if (sourceImageNameElement != null) { + String sourceImageNameInstance; + sourceImageNameInstance = sourceImageNameElement.getTextContent(); + diskInstance.setSourceImageName(sourceImageNameInstance); + } + + Element attachedToElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "AttachedTo"); + if (attachedToElement != null) { + VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails attachedToInstance = new VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails(); + diskInstance.setUsageDetails(attachedToInstance); + + Element hostedServiceNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "HostedServiceName"); + if (hostedServiceNameElement != null) { + String hostedServiceNameInstance; + hostedServiceNameInstance = hostedServiceNameElement.getTextContent(); + attachedToInstance.setHostedServiceName(hostedServiceNameInstance); + } + + Element deploymentNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "DeploymentName"); + if (deploymentNameElement != null) { + String deploymentNameInstance; + deploymentNameInstance = deploymentNameElement.getTextContent(); + attachedToInstance.setDeploymentName(deploymentNameInstance); + } + + Element roleNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + attachedToInstance.setRoleName(roleNameInstance); + } + } + + Element isCorruptedElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "IsCorrupted"); + if (isCorruptedElement != null && (isCorruptedElement.getTextContent() == null || isCorruptedElement.getTextContent().isEmpty() == true) == false) { + boolean isCorruptedInstance; + isCorruptedInstance = DatatypeConverter.parseBoolean(isCorruptedElement.getTextContent().toLowerCase()); + diskInstance.setIsCorrupted(isCorruptedInstance); + } + + Element isPremiumElement = XmlUtility.getElementByTagNameNS(disksElement, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement != null && (isPremiumElement.getTextContent() == null || isPremiumElement.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement.getTextContent().toLowerCase()); + diskInstance.setIsPremium(isPremiumInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Update Data Disk operation updates the specified data disk attached + * to the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157190.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Data Disk operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future updateDataDiskAsync(final String serviceName, final String deploymentName, final String roleName, final int logicalUnitNumber, final VirtualMachineDataDiskUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return updateDataDisk(serviceName, deploymentName, roleName, logicalUnitNumber, parameters); + } + }); + } + + /** + * The Update Data Disk operation updates the specified data disk attached + * to the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157190.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of the deployment. + * @param roleName Required. The name of the role to add the data disk to. + * @param logicalUnitNumber Required. The logical unit number of the disk. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Data Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse updateDataDisk(String serviceName, String deploymentName, String roleName, int logicalUnitNumber, VirtualMachineDataDiskUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (roleName == null) { + throw new NullPointerException("roleName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getMediaLinkUri() == null) { + throw new NullPointerException("parameters.MediaLinkUri"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("roleName", roleName); + tracingParameters.put("logicalUnitNumber", logicalUnitNumber); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateDataDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles/" + roleName.trim() + "/DataDisks/" + logicalUnitNumber; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element dataVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk"); + requestDoc.appendChild(dataVirtualHardDiskElement); + + Element hostCachingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement.appendChild(requestDoc.createTextNode(parameters.getHostCaching().toString())); + dataVirtualHardDiskElement.appendChild(hostCachingElement); + + if (parameters.getLabel() != null) { + Element diskLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); + dataVirtualHardDiskElement.appendChild(diskLabelElement); + } + + if (parameters.getName() != null) { + Element diskNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + dataVirtualHardDiskElement.appendChild(diskNameElement); + } + + if (parameters.getLogicalUnitNumber() != null) { + Element lunElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Lun"); + lunElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getLogicalUnitNumber()))); + dataVirtualHardDiskElement.appendChild(lunElement); + } + + Element logicalDiskSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getLogicalDiskSizeInGB()))); + dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement); + + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString())); + dataVirtualHardDiskElement.appendChild(mediaLinkElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Add Disk operation adds a disk to the user image repository. The disk + * can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk being updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Disk operation. + * @return A virtual machine disk associated with your subscription. + */ + @Override + public Future updateDiskAsync(final String name, final VirtualMachineDiskUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineDiskUpdateResponse call() throws Exception { + return updateDisk(name, parameters); + } + }); + } + + /** + * The Add Disk operation adds a disk to the user image repository. The disk + * can be an operating system disk or a data disk. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for + * more information) + * + * @param name Required. The name of the disk being updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Disk operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine disk associated with your subscription. + */ + @Override + public VirtualMachineDiskUpdateResponse updateDisk(String name, VirtualMachineDiskUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // Validate + if (name == null) { + throw new NullPointerException("name"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("name", name); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateDiskAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/disks/" + name.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element diskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Disk"); + requestDoc.appendChild(diskElement); + + if (parameters.isHasOperatingSystem() != null) { + Element hasOperatingSystemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HasOperatingSystem"); + hasOperatingSystemElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isHasOperatingSystem()).toLowerCase())); + diskElement.appendChild(hasOperatingSystemElement); + } + + if (parameters.getOperatingSystemType() != null) { + Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS"); + osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType())); + diskElement.appendChild(osElement); + } + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); + diskElement.appendChild(labelElement); + + if (parameters.getMediaLinkUri() != null) { + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString())); + diskElement.appendChild(mediaLinkElement); + } + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + diskElement.appendChild(nameElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineDiskUpdateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineDiskUpdateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element diskElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Disk"); + if (diskElement2 != null) { + Element osElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement2 != null) { + String osInstance; + osInstance = osElement2.getTextContent(); + result.setOperatingSystem(osInstance); + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance; + labelInstance = labelElement2.getTextContent(); + result.setLabel(labelInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + result.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + result.setLocation(locationInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + result.setLogicalSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement2.getTextContent()); + result.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + result.setName(nameInstance); + } + + Element isPremiumElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement != null && (isPremiumElement.getTextContent() == null || isPremiumElement.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement.getTextContent().toLowerCase()); + result.setIsPremium(isPremiumInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperations.java new file mode 100644 index 0000000000000..6de04a70eb3fb --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperations.java @@ -0,0 +1,116 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineExtensionListResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* machine extensions in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for more +* information) +*/ +public interface VirtualMachineExtensionOperations { + /** + * The List Resource Extensions operation lists the resource extensions that + * are available to add to a Virtual Machine. In Azure, a process can run + * as a resource extension of a Virtual Machine. For example, Remote + * Desktop Access or the Azure Diagnostics Agent can run as resource + * extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Resource Extensions operation response. + */ + VirtualMachineExtensionListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Resource Extensions operation lists the resource extensions that + * are available to add to a Virtual Machine. In Azure, a process can run + * as a resource extension of a Virtual Machine. For example, Remote + * Desktop Access or the Azure Diagnostics Agent can run as resource + * extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx for + * more information) + * + * @return The List Resource Extensions operation response. + */ + Future listAsync(); + + /** + * The List Resource Extension Versions operation lists the versions of a + * resource extension that are available to add to a Virtual Machine. In + * Azure, a process can run as a resource extension of a Virtual Machine. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as resource extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495440.aspx for + * more information) + * + * @param publisherName Required. The name of the publisher. + * @param extensionName Required. The name of the extension. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Resource Extensions operation response. + */ + VirtualMachineExtensionListResponse listVersions(String publisherName, String extensionName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Resource Extension Versions operation lists the versions of a + * resource extension that are available to add to a Virtual Machine. In + * Azure, a process can run as a resource extension of a Virtual Machine. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as resource extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495440.aspx for + * more information) + * + * @param publisherName Required. The name of the publisher. + * @param extensionName Required. The name of the extension. + * @return The List Resource Extensions operation response. + */ + Future listVersionsAsync(String publisherName, String extensionName); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperationsImpl.java new file mode 100644 index 0000000000000..232490c69fe99 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperationsImpl.java @@ -0,0 +1,526 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineExtensionListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* machine extensions in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for more +* information) +*/ +public class VirtualMachineExtensionOperationsImpl implements ServiceOperations, VirtualMachineExtensionOperations { + /** + * Initializes a new instance of the VirtualMachineExtensionOperationsImpl + * class. + * + * @param client Reference to the service client. + */ + VirtualMachineExtensionOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The List Resource Extensions operation lists the resource extensions that + * are available to add to a Virtual Machine. In Azure, a process can run + * as a resource extension of a Virtual Machine. For example, Remote + * Desktop Access or the Azure Diagnostics Agent can run as resource + * extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx for + * more information) + * + * @return The List Resource Extensions operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineExtensionListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Resource Extensions operation lists the resource extensions that + * are available to add to a Virtual Machine. In Azure, a process can run + * as a resource extension of a Virtual Machine. For example, Remote + * Desktop Access or the Azure Diagnostics Agent can run as resource + * extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Resource Extensions operation response. + */ + @Override + public VirtualMachineExtensionListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/resourceextensions"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineExtensionListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineExtensionListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element resourceExtensionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ResourceExtensions"); + if (resourceExtensionsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtension").size(); i1 = i1 + 1) { + org.w3c.dom.Element resourceExtensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtension").get(i1)); + VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension(); + result.getResourceExtensions().add(resourceExtensionInstance); + + Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Publisher"); + if (publisherElement != null) { + String publisherInstance; + publisherInstance = publisherElement.getTextContent(); + resourceExtensionInstance.setPublisher(publisherInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + resourceExtensionInstance.setName(nameInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + resourceExtensionInstance.setVersion(versionInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + resourceExtensionInstance.setLabel(labelInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + resourceExtensionInstance.setDescription(descriptionInstance); + } + + Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "PublicConfigurationSchema"); + if (publicConfigurationSchemaElement != null) { + String publicConfigurationSchemaInstance; + publicConfigurationSchemaInstance = publicConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(publicConfigurationSchemaElement.getTextContent())) : null; + resourceExtensionInstance.setPublicConfigurationSchema(publicConfigurationSchemaInstance); + } + + Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "PrivateConfigurationSchema"); + if (privateConfigurationSchemaElement != null) { + String privateConfigurationSchemaInstance; + privateConfigurationSchemaInstance = privateConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(privateConfigurationSchemaElement.getTextContent())) : null; + resourceExtensionInstance.setPrivateConfigurationSchema(privateConfigurationSchemaInstance); + } + + Element sampleConfigElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "SampleConfig"); + if (sampleConfigElement != null) { + String sampleConfigInstance; + sampleConfigInstance = sampleConfigElement.getTextContent() != null ? new String(Base64.decode(sampleConfigElement.getTextContent())) : null; + resourceExtensionInstance.setSampleConfig(sampleConfigInstance); + } + + Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "ReplicationCompleted"); + if (replicationCompletedElement != null && (replicationCompletedElement.getTextContent() == null || replicationCompletedElement.getTextContent().isEmpty() == true) == false) { + boolean replicationCompletedInstance; + replicationCompletedInstance = DatatypeConverter.parseBoolean(replicationCompletedElement.getTextContent().toLowerCase()); + resourceExtensionInstance.setReplicationCompleted(replicationCompletedInstance); + } + + Element eulaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement != null) { + URI eulaInstance; + eulaInstance = new URI(eulaElement.getTextContent()); + resourceExtensionInstance.setEula(eulaInstance); + } + + Element privacyUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement.getTextContent()); + resourceExtensionInstance.setPrivacyUri(privacyUriInstance); + } + + Element homepageUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "HomepageUri"); + if (homepageUriElement != null) { + URI homepageUriInstance; + homepageUriInstance = new URI(homepageUriElement.getTextContent()); + resourceExtensionInstance.setHomepageUri(homepageUriInstance); + } + + Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "IsJsonExtension"); + if (isJsonExtensionElement != null && (isJsonExtensionElement.getTextContent() == null || isJsonExtensionElement.getTextContent().isEmpty() == true) == false) { + boolean isJsonExtensionInstance; + isJsonExtensionInstance = DatatypeConverter.parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase()); + resourceExtensionInstance.setIsJsonExtension(isJsonExtensionInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Resource Extension Versions operation lists the versions of a + * resource extension that are available to add to a Virtual Machine. In + * Azure, a process can run as a resource extension of a Virtual Machine. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as resource extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495440.aspx for + * more information) + * + * @param publisherName Required. The name of the publisher. + * @param extensionName Required. The name of the extension. + * @return The List Resource Extensions operation response. + */ + @Override + public Future listVersionsAsync(final String publisherName, final String extensionName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineExtensionListResponse call() throws Exception { + return listVersions(publisherName, extensionName); + } + }); + } + + /** + * The List Resource Extension Versions operation lists the versions of a + * resource extension that are available to add to a Virtual Machine. In + * Azure, a process can run as a resource extension of a Virtual Machine. + * For example, Remote Desktop Access or the Azure Diagnostics Agent can + * run as resource extensions to the Virtual Machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn495440.aspx for + * more information) + * + * @param publisherName Required. The name of the publisher. + * @param extensionName Required. The name of the extension. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Resource Extensions operation response. + */ + @Override + public VirtualMachineExtensionListResponse listVersions(String publisherName, String extensionName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (publisherName == null) { + throw new NullPointerException("publisherName"); + } + if (extensionName == null) { + throw new NullPointerException("extensionName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("publisherName", publisherName); + tracingParameters.put("extensionName", extensionName); + CloudTracing.enter(invocationId, this, "listVersionsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/resourceextensions/" + publisherName.trim() + "/" + extensionName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineExtensionListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineExtensionListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element resourceExtensionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ResourceExtensions"); + if (resourceExtensionsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtension").size(); i1 = i1 + 1) { + org.w3c.dom.Element resourceExtensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(resourceExtensionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ResourceExtension").get(i1)); + VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension(); + result.getResourceExtensions().add(resourceExtensionInstance); + + Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Publisher"); + if (publisherElement != null) { + String publisherInstance; + publisherInstance = publisherElement.getTextContent(); + resourceExtensionInstance.setPublisher(publisherInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + resourceExtensionInstance.setName(nameInstance); + } + + Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Version"); + if (versionElement != null) { + String versionInstance; + versionInstance = versionElement.getTextContent(); + resourceExtensionInstance.setVersion(versionInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + resourceExtensionInstance.setLabel(labelInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + resourceExtensionInstance.setDescription(descriptionInstance); + } + + Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "PublicConfigurationSchema"); + if (publicConfigurationSchemaElement != null) { + String publicConfigurationSchemaInstance; + publicConfigurationSchemaInstance = publicConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(publicConfigurationSchemaElement.getTextContent())) : null; + resourceExtensionInstance.setPublicConfigurationSchema(publicConfigurationSchemaInstance); + } + + Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "PrivateConfigurationSchema"); + if (privateConfigurationSchemaElement != null) { + String privateConfigurationSchemaInstance; + privateConfigurationSchemaInstance = privateConfigurationSchemaElement.getTextContent() != null ? new String(Base64.decode(privateConfigurationSchemaElement.getTextContent())) : null; + resourceExtensionInstance.setPrivateConfigurationSchema(privateConfigurationSchemaInstance); + } + + Element sampleConfigElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "SampleConfig"); + if (sampleConfigElement != null) { + String sampleConfigInstance; + sampleConfigInstance = sampleConfigElement.getTextContent() != null ? new String(Base64.decode(sampleConfigElement.getTextContent())) : null; + resourceExtensionInstance.setSampleConfig(sampleConfigInstance); + } + + Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "ReplicationCompleted"); + if (replicationCompletedElement != null && (replicationCompletedElement.getTextContent() == null || replicationCompletedElement.getTextContent().isEmpty() == true) == false) { + boolean replicationCompletedInstance; + replicationCompletedInstance = DatatypeConverter.parseBoolean(replicationCompletedElement.getTextContent().toLowerCase()); + resourceExtensionInstance.setReplicationCompleted(replicationCompletedInstance); + } + + Element eulaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement != null) { + URI eulaInstance; + eulaInstance = new URI(eulaElement.getTextContent()); + resourceExtensionInstance.setEula(eulaInstance); + } + + Element privacyUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement.getTextContent()); + resourceExtensionInstance.setPrivacyUri(privacyUriInstance); + } + + Element homepageUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "HomepageUri"); + if (homepageUriElement != null) { + URI homepageUriInstance; + homepageUriInstance = new URI(homepageUriElement.getTextContent()); + resourceExtensionInstance.setHomepageUri(homepageUriInstance); + } + + Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure", "IsJsonExtension"); + if (isJsonExtensionElement != null && (isJsonExtensionElement.getTextContent() == null || isJsonExtensionElement.getTextContent().isEmpty() == true) == false) { + boolean isJsonExtensionInstance; + isJsonExtensionInstance = DatatypeConverter.parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase()); + resourceExtensionInstance.setIsJsonExtension(isJsonExtensionInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOSImageOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOSImageOperations.java new file mode 100644 index 0000000000000..c2d9da7d62f1c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOSImageOperations.java @@ -0,0 +1,251 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageListResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the OS images in +* your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx for more +* information) +*/ +public interface VirtualMachineOSImageOperations { + /** + * The Create OS Image operation adds an operating system image that is + * stored in a storage account and is available from the image repository. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Image operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException; + + /** + * The Create OS Image operation adds an operating system image that is + * stored in a storage account and is available from the image repository. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Image operation. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + Future createAsync(VirtualMachineOSImageCreateParameters parameters); + + /** + * The Delete OS Image operation deletes the specified OS image from your + * image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx for + * more information) + * + * @param imageName Required. The name of the image to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String imageName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException; + + /** + * The Delete OS Image operation deletes the specified OS image from your + * image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx for + * more information) + * + * @param imageName Required. The name of the image to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String imageName, boolean deleteFromStorage); + + /** + * The Get OS Image operation retrieves the details for an operating system + * image from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @param imageName Required. The name of the OS image to retrieve. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine image associated with your subscription. + */ + VirtualMachineOSImageGetResponse get(String imageName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get OS Image operation retrieves the details for an operating system + * image from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @param imageName Required. The name of the OS image to retrieve. + * @return A virtual machine image associated with your subscription. + */ + Future getAsync(String imageName); + + /** + * The List OS Images operation retrieves a list of the operating system + * images from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List OS Images operation response. + */ + VirtualMachineOSImageListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List OS Images operation retrieves a list of the operating system + * images from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @return The List OS Images operation response. + */ + Future listAsync(); + + /** + * The Update OS Image operation updates an OS image that in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for + * more information) + * + * @param imageName Required. The name of the virtual machine image to be + * updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Image operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + VirtualMachineOSImageUpdateResponse update(String imageName, VirtualMachineOSImageUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, InterruptedException, ExecutionException, URISyntaxException; + + /** + * The Update OS Image operation updates an OS image that in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for + * more information) + * + * @param imageName Required. The name of the virtual machine image to be + * updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Image operation. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + Future updateAsync(String imageName, VirtualMachineOSImageUpdateParameters parameters); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOSImageOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOSImageOperationsImpl.java new file mode 100644 index 0000000000000..bc5e069d0eb6d --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOSImageOperationsImpl.java @@ -0,0 +1,1485 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageListResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.TimeZone; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the OS images in +* your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx for more +* information) +*/ +public class VirtualMachineOSImageOperationsImpl implements ServiceOperations, VirtualMachineOSImageOperations { + /** + * Initializes a new instance of the VirtualMachineOSImageOperationsImpl + * class. + * + * @param client Reference to the service client. + */ + VirtualMachineOSImageOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The Create OS Image operation adds an operating system image that is + * stored in a storage account and is available from the image repository. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Image operation. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + @Override + public Future createAsync(final VirtualMachineOSImageCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineOSImageCreateResponse call() throws Exception { + return create(parameters); + } + }); + } + + /** + * The Create OS Image operation adds an operating system image that is + * stored in a storage account and is available from the image repository. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx + * for more information) + * + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Image operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + @Override + public VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getMediaLinkUri() == null) { + throw new NullPointerException("parameters.MediaLinkUri"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + if (parameters.getOperatingSystemType() == null) { + throw new NullPointerException("parameters.OperatingSystemType"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/images"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element oSImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSImage"); + requestDoc.appendChild(oSImageElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); + oSImageElement.appendChild(labelElement); + + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString())); + oSImageElement.appendChild(mediaLinkElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + oSImageElement.appendChild(nameElement); + + Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS"); + osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType())); + oSImageElement.appendChild(osElement); + + if (parameters.getEula() != null) { + Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula"); + eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula())); + oSImageElement.appendChild(eulaElement); + } + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + oSImageElement.appendChild(descriptionElement); + } + + if (parameters.getImageFamily() != null) { + Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ImageFamily"); + imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily())); + oSImageElement.appendChild(imageFamilyElement); + } + + if (parameters.getPublishedDate() != null) { + Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublishedDate"); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + publishedDateElement.appendChild(requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime()))); + oSImageElement.appendChild(publishedDateElement); + } + + Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IsPremium"); + isPremiumElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase())); + oSImageElement.appendChild(isPremiumElement); + + Element showInGuiElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ShowInGui"); + showInGuiElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isShowInGui()).toLowerCase())); + oSImageElement.appendChild(showInGuiElement); + + if (parameters.getPrivacyUri() != null) { + Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString())); + oSImageElement.appendChild(privacyUriElement); + } + + if (parameters.getIconUri() != null) { + Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IconUri"); + iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri().toString())); + oSImageElement.appendChild(iconUriElement); + } + + if (parameters.getRecommendedVMSize() != null) { + Element recommendedVMSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize"); + recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize())); + oSImageElement.appendChild(recommendedVMSizeElement); + } + + if (parameters.getSmallIconUri() != null) { + Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SmallIconUri"); + smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri().toString())); + oSImageElement.appendChild(smallIconUriElement); + } + + if (parameters.getLanguage() != null) { + Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Language"); + languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage())); + oSImageElement.appendChild(languageElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineOSImageCreateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineOSImageCreateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element oSImageElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "OSImage"); + if (oSImageElement2 != null) { + Element locationElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + result.setLocation(locationInstance); + } + + Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Category"); + if (categoryElement != null) { + String categoryInstance; + categoryInstance = categoryElement.getTextContent(); + result.setCategory(categoryInstance); + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance; + labelInstance = labelElement2.getTextContent(); + result.setLabel(labelInstance); + } + + Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB"); + if (logicalSizeInGBElement != null) { + double logicalSizeInGBInstance; + logicalSizeInGBInstance = DatatypeConverter.parseDouble(logicalSizeInGBElement.getTextContent()); + result.setLogicalSizeInGB(logicalSizeInGBInstance); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement2.getTextContent()); + result.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + result.setName(nameInstance); + } + + Element osElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement2 != null) { + String osInstance; + osInstance = osElement2.getTextContent(); + result.setOperatingSystemType(osInstance); + } + + Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement2 != null) { + String eulaInstance; + eulaInstance = eulaElement2.getTextContent(); + result.setEula(eulaInstance); + } + + Element descriptionElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement2 != null) { + String descriptionInstance; + descriptionInstance = descriptionElement2.getTextContent(); + result.setDescription(descriptionInstance); + } + + Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "ImageFamily"); + if (imageFamilyElement2 != null) { + String imageFamilyInstance; + imageFamilyInstance = imageFamilyElement2.getTextContent(); + result.setImageFamily(imageFamilyInstance); + } + + Element publishedDateElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "PublishedDate"); + if (publishedDateElement2 != null && (publishedDateElement2.getTextContent() == null || publishedDateElement2.getTextContent().isEmpty() == true) == false) { + Calendar publishedDateInstance; + publishedDateInstance = DatatypeConverter.parseDateTime(publishedDateElement2.getTextContent()); + result.setPublishedDate(publishedDateInstance); + } + + Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "PublisherName"); + if (publisherNameElement != null) { + String publisherNameInstance; + publisherNameInstance = publisherNameElement.getTextContent(); + result.setPublisherName(publisherNameInstance); + } + + Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement2 != null && (isPremiumElement2.getTextContent() == null || isPremiumElement2.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement2.getTextContent().toLowerCase()); + result.setIsPremium(isPremiumInstance); + } + + Element showInGuiElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "ShowInGui"); + if (showInGuiElement2 != null && (showInGuiElement2.getTextContent() == null || showInGuiElement2.getTextContent().isEmpty() == true) == false) { + boolean showInGuiInstance; + showInGuiInstance = DatatypeConverter.parseBoolean(showInGuiElement2.getTextContent().toLowerCase()); + result.setShowInGui(showInGuiInstance); + } + + Element privacyUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement2 != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement2.getTextContent()); + result.setPrivacyUri(privacyUriInstance); + } + + Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "IconUri"); + if (iconUriElement2 != null) { + URI iconUriInstance; + iconUriInstance = new URI(iconUriElement2.getTextContent()); + result.setIconUri(iconUriInstance); + } + + Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize"); + if (recommendedVMSizeElement2 != null) { + String recommendedVMSizeInstance; + recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent(); + result.setRecommendedVMSize(recommendedVMSizeInstance); + } + + Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "SmallIconUri"); + if (smallIconUriElement2 != null) { + URI smallIconUriInstance; + smallIconUriInstance = new URI(smallIconUriElement2.getTextContent()); + result.setSmallIconUri(smallIconUriInstance); + } + + Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement2 != null) { + String languageInstance; + languageInstance = languageElement2.getTextContent(); + result.setLanguage(languageInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete OS Image operation deletes the specified OS image from your + * image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx for + * more information) + * + * @param imageName Required. The name of the image to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String imageName, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(imageName, deleteFromStorage); + } + }); + } + + /** + * The Delete OS Image operation deletes the specified OS image from your + * image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx for + * more information) + * + * @param imageName Required. The name of the image to delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String imageName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException { + // Validate + if (imageName == null) { + throw new NullPointerException("imageName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("imageName", imageName); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/images/" + imageName.trim() + "?"; + if (deleteFromStorage == true) { + url = url + "comp=" + "media"; + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get OS Image operation retrieves the details for an operating system + * image from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @param imageName Required. The name of the OS image to retrieve. + * @return A virtual machine image associated with your subscription. + */ + @Override + public Future getAsync(final String imageName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineOSImageGetResponse call() throws Exception { + return get(imageName); + } + }); + } + + /** + * The Get OS Image operation retrieves the details for an operating system + * image from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @param imageName Required. The name of the OS image to retrieve. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return A virtual machine image associated with your subscription. + */ + @Override + public VirtualMachineOSImageGetResponse get(String imageName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (imageName == null) { + throw new NullPointerException("imageName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("imageName", imageName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/images/" + imageName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineOSImageGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineOSImageGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element oSImageElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "OSImage"); + if (oSImageElement != null) { + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + result.setAffinityGroup(affinityGroupInstance); + } + + Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Category"); + if (categoryElement != null) { + String categoryInstance; + categoryInstance = categoryElement.getTextContent(); + result.setCategory(categoryInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + result.setLabel(labelInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + result.setLocation(locationInstance); + } + + Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB"); + if (logicalSizeInGBElement != null) { + double logicalSizeInGBInstance; + logicalSizeInGBInstance = DatatypeConverter.parseDouble(logicalSizeInGBElement.getTextContent()); + result.setLogicalSizeInGB(logicalSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + result.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + result.setOperatingSystemType(osInstance); + } + + Element eulaElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement != null) { + String eulaInstance; + eulaInstance = eulaElement.getTextContent(); + result.setEula(eulaInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + result.setDescription(descriptionInstance); + } + + Element imageFamilyElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "ImageFamily"); + if (imageFamilyElement != null) { + String imageFamilyInstance; + imageFamilyInstance = imageFamilyElement.getTextContent(); + result.setImageFamily(imageFamilyInstance); + } + + Element showInGuiElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "ShowInGui"); + if (showInGuiElement != null && (showInGuiElement.getTextContent() == null || showInGuiElement.getTextContent().isEmpty() == true) == false) { + boolean showInGuiInstance; + showInGuiInstance = DatatypeConverter.parseBoolean(showInGuiElement.getTextContent().toLowerCase()); + result.setShowInGui(showInGuiInstance); + } + + Element publishedDateElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "PublishedDate"); + if (publishedDateElement != null) { + Calendar publishedDateInstance; + publishedDateInstance = DatatypeConverter.parseDateTime(publishedDateElement.getTextContent()); + result.setPublishedDate(publishedDateInstance); + } + + Element isPremiumElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement != null && (isPremiumElement.getTextContent() == null || isPremiumElement.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement.getTextContent().toLowerCase()); + result.setIsPremium(isPremiumInstance); + } + + Element iconUriElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "IconUri"); + if (iconUriElement != null) { + URI iconUriInstance; + iconUriInstance = new URI(iconUriElement.getTextContent()); + result.setIconUri(iconUriInstance); + } + + Element privacyUriElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement.getTextContent()); + result.setPrivacyUri(privacyUriInstance); + } + + Element recommendedVMSizeElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize"); + if (recommendedVMSizeElement != null) { + String recommendedVMSizeInstance; + recommendedVMSizeInstance = recommendedVMSizeElement.getTextContent(); + result.setRecommendedVMSize(recommendedVMSizeInstance); + } + + Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "PublisherName"); + if (publisherNameElement != null) { + String publisherNameInstance; + publisherNameInstance = publisherNameElement.getTextContent(); + result.setPublisherName(publisherNameInstance); + } + + Element smallIconUriElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "SmallIconUri"); + if (smallIconUriElement != null) { + URI smallIconUriInstance; + smallIconUriInstance = new URI(smallIconUriElement.getTextContent()); + result.setSmallIconUri(smallIconUriInstance); + } + + Element languageElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement != null) { + String languageInstance; + languageInstance = languageElement.getTextContent(); + result.setLanguage(languageInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List OS Images operation retrieves a list of the operating system + * images from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @return The List OS Images operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineOSImageListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List OS Images operation retrieves a list of the operating system + * images from the image repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List OS Images operation response. + */ + @Override + public VirtualMachineOSImageListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/images"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineOSImageListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineOSImageListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element imagesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Images"); + if (imagesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(imagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "OSImage").size(); i1 = i1 + 1) { + org.w3c.dom.Element imagesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(imagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "OSImage").get(i1)); + VirtualMachineOSImageListResponse.VirtualMachineOSImage oSImageInstance = new VirtualMachineOSImageListResponse.VirtualMachineOSImage(); + result.getImages().add(oSImageInstance); + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + oSImageInstance.setAffinityGroup(affinityGroupInstance); + } + + Element categoryElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "Category"); + if (categoryElement != null) { + String categoryInstance; + categoryInstance = categoryElement.getTextContent(); + oSImageInstance.setCategory(categoryInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + oSImageInstance.setLabel(labelInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + oSImageInstance.setLocation(locationInstance); + } + + Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB"); + if (logicalSizeInGBElement != null) { + double logicalSizeInGBInstance; + logicalSizeInGBInstance = DatatypeConverter.parseDouble(logicalSizeInGBElement.getTextContent()); + oSImageInstance.setLogicalSizeInGB(logicalSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + oSImageInstance.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + oSImageInstance.setName(nameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + oSImageInstance.setOperatingSystemType(osInstance); + } + + Element eulaElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement != null) { + String eulaInstance; + eulaInstance = eulaElement.getTextContent(); + oSImageInstance.setEula(eulaInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + oSImageInstance.setDescription(descriptionInstance); + } + + Element imageFamilyElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "ImageFamily"); + if (imageFamilyElement != null) { + String imageFamilyInstance; + imageFamilyInstance = imageFamilyElement.getTextContent(); + oSImageInstance.setImageFamily(imageFamilyInstance); + } + + Element publishedDateElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "PublishedDate"); + if (publishedDateElement != null) { + Calendar publishedDateInstance; + publishedDateInstance = DatatypeConverter.parseDateTime(publishedDateElement.getTextContent()); + oSImageInstance.setPublishedDate(publishedDateInstance); + } + + Element isPremiumElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement != null && (isPremiumElement.getTextContent() == null || isPremiumElement.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement.getTextContent().toLowerCase()); + oSImageInstance.setIsPremium(isPremiumInstance); + } + + Element privacyUriElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement.getTextContent()); + oSImageInstance.setPrivacyUri(privacyUriInstance); + } + + Element recommendedVMSizeElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize"); + if (recommendedVMSizeElement != null) { + String recommendedVMSizeInstance; + recommendedVMSizeInstance = recommendedVMSizeElement.getTextContent(); + oSImageInstance.setRecommendedVMSize(recommendedVMSizeInstance); + } + + Element publisherNameElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "PublisherName"); + if (publisherNameElement != null) { + String publisherNameInstance; + publisherNameInstance = publisherNameElement.getTextContent(); + oSImageInstance.setPublisherName(publisherNameInstance); + } + + Element pricingDetailLinkElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "PricingDetailLink"); + if (pricingDetailLinkElement != null) { + URI pricingDetailLinkInstance; + pricingDetailLinkInstance = new URI(pricingDetailLinkElement.getTextContent()); + oSImageInstance.setPricingDetailUri(pricingDetailLinkInstance); + } + + Element smallIconUriElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "SmallIconUri"); + if (smallIconUriElement != null) { + URI smallIconUriInstance; + smallIconUriInstance = new URI(smallIconUriElement.getTextContent()); + oSImageInstance.setSmallIconUri(smallIconUriInstance); + } + + Element languageElement = XmlUtility.getElementByTagNameNS(imagesElement, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement != null) { + String languageInstance; + languageInstance = languageElement.getTextContent(); + oSImageInstance.setLanguage(languageInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Update OS Image operation updates an OS image that in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for + * more information) + * + * @param imageName Required. The name of the virtual machine image to be + * updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Image operation. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + @Override + public Future updateAsync(final String imageName, final VirtualMachineOSImageUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineOSImageUpdateResponse call() throws Exception { + return update(imageName, parameters); + } + }); + } + + /** + * The Update OS Image operation updates an OS image that in your image + * repository. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for + * more information) + * + * @param imageName Required. The name of the virtual machine image to be + * updated. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine Image operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return Parameters returned from the Create Virtual Machine Image + * operation. + */ + @Override + public VirtualMachineOSImageUpdateResponse update(String imageName, VirtualMachineOSImageUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, InterruptedException, ExecutionException, URISyntaxException { + // Validate + if (imageName == null) { + throw new NullPointerException("imageName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("imageName", imageName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/images/" + imageName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element oSImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSImage"); + requestDoc.appendChild(oSImageElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); + oSImageElement.appendChild(labelElement); + + if (parameters.getEula() != null) { + Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula"); + eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula())); + oSImageElement.appendChild(eulaElement); + } + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + oSImageElement.appendChild(descriptionElement); + } + + if (parameters.getImageFamily() != null) { + Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ImageFamily"); + imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily())); + oSImageElement.appendChild(imageFamilyElement); + } + + if (parameters.getPublishedDate() != null) { + Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublishedDate"); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + publishedDateElement.appendChild(requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime()))); + oSImageElement.appendChild(publishedDateElement); + } + + Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IsPremium"); + isPremiumElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase())); + oSImageElement.appendChild(isPremiumElement); + + if (parameters.getPrivacyUri() != null) { + Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString())); + oSImageElement.appendChild(privacyUriElement); + } + + if (parameters.getIconUri() != null) { + Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IconUri"); + iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri().toString())); + oSImageElement.appendChild(iconUriElement); + } + + if (parameters.getRecommendedVMSize() != null) { + Element recommendedVMSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize"); + recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize())); + oSImageElement.appendChild(recommendedVMSizeElement); + } + + if (parameters.getSmallIconUri() != null) { + Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SmallIconUri"); + smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri().toString())); + oSImageElement.appendChild(smallIconUriElement); + } + + if (parameters.getLanguage() != null) { + Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Language"); + languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage())); + oSImageElement.appendChild(languageElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineOSImageUpdateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineOSImageUpdateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element oSImageElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "OSImage"); + if (oSImageElement2 != null) { + Element locationElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + result.setLocation(locationInstance); + } + + Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Category"); + if (categoryElement != null) { + String categoryInstance; + categoryInstance = categoryElement.getTextContent(); + result.setCategory(categoryInstance); + } + + Element labelElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement2 != null) { + String labelInstance; + labelInstance = labelElement2.getTextContent(); + result.setLabel(labelInstance); + } + + Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB"); + if (logicalSizeInGBElement != null) { + double logicalSizeInGBInstance; + logicalSizeInGBInstance = DatatypeConverter.parseDouble(logicalSizeInGBElement.getTextContent()); + result.setLogicalSizeInGB(logicalSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + result.setMediaLinkUri(mediaLinkInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + result.setOperatingSystemType(osInstance); + } + + Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Eula"); + if (eulaElement2 != null) { + String eulaInstance; + eulaInstance = eulaElement2.getTextContent(); + result.setEula(eulaInstance); + } + + Element descriptionElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement2 != null) { + String descriptionInstance; + descriptionInstance = descriptionElement2.getTextContent(); + result.setDescription(descriptionInstance); + } + + Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "ImageFamily"); + if (imageFamilyElement2 != null) { + String imageFamilyInstance; + imageFamilyInstance = imageFamilyElement2.getTextContent(); + result.setImageFamily(imageFamilyInstance); + } + + Element publishedDateElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "PublishedDate"); + if (publishedDateElement2 != null && (publishedDateElement2.getTextContent() == null || publishedDateElement2.getTextContent().isEmpty() == true) == false) { + Calendar publishedDateInstance; + publishedDateInstance = DatatypeConverter.parseDateTime(publishedDateElement2.getTextContent()); + result.setPublishedDate(publishedDateInstance); + } + + Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "PublisherName"); + if (publisherNameElement != null) { + String publisherNameInstance; + publisherNameInstance = publisherNameElement.getTextContent(); + result.setPublisherName(publisherNameInstance); + } + + Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "IsPremium"); + if (isPremiumElement2 != null && (isPremiumElement2.getTextContent() == null || isPremiumElement2.getTextContent().isEmpty() == true) == false) { + boolean isPremiumInstance; + isPremiumInstance = DatatypeConverter.parseBoolean(isPremiumElement2.getTextContent().toLowerCase()); + result.setIsPremium(isPremiumInstance); + } + + Element showInGuiElement = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "ShowInGui"); + if (showInGuiElement != null && (showInGuiElement.getTextContent() == null || showInGuiElement.getTextContent().isEmpty() == true) == false) { + boolean showInGuiInstance; + showInGuiInstance = DatatypeConverter.parseBoolean(showInGuiElement.getTextContent().toLowerCase()); + result.setShowInGui(showInGuiInstance); + } + + Element privacyUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); + if (privacyUriElement2 != null) { + URI privacyUriInstance; + privacyUriInstance = new URI(privacyUriElement2.getTextContent()); + result.setPrivacyUri(privacyUriInstance); + } + + Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "IconUri"); + if (iconUriElement2 != null) { + URI iconUriInstance; + iconUriInstance = new URI(iconUriElement2.getTextContent()); + result.setIconUri(iconUriInstance); + } + + Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize"); + if (recommendedVMSizeElement2 != null) { + String recommendedVMSizeInstance; + recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent(); + result.setRecommendedVMSize(recommendedVMSizeInstance); + } + + Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "SmallIconUri"); + if (smallIconUriElement2 != null) { + URI smallIconUriInstance; + smallIconUriInstance = new URI(smallIconUriElement2.getTextContent()); + result.setSmallIconUri(smallIconUriInstance); + } + + Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2, "http://schemas.microsoft.com/windowsazure", "Language"); + if (languageElement2 != null) { + String languageInstance; + languageInstance = languageElement2.getTextContent(); + result.setLanguage(languageInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperations.java new file mode 100644 index 0000000000000..409dccb08fdc0 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperations.java @@ -0,0 +1,1343 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureOSImageParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureVMImageParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateDeploymentParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetRemoteDesktopFileResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownRolesParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineStartRolesParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateLoadBalancedSetParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateParameters; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* machines in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for more +* information) +*/ +public interface VirtualMachineOperations { + /** + * The Begin Capturing Role operation creates a copy of the operating system + * virtual hard disk (VHD) that is deployed in the virtual machine, saves + * the VHD copy in the same storage location as the operating system VHD, + * and registers the copy as an image in your image gallery. From the + * captured image, you can create additional customized virtual machines. + * For more information about images and disks, see Manage Disks and Images + * at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. + * For more information about capturing images, see How to Capture an Image + * of a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Begin Capturing + * Virtual Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginCapturingOSImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Capturing Role operation creates a copy of the operating system + * virtual hard disk (VHD) that is deployed in the virtual machine, saves + * the VHD copy in the same storage location as the operating system VHD, + * and registers the copy as an image in your image gallery. From the + * captured image, you can create additional customized virtual machines. + * For more information about images and disks, see Manage Disks and Images + * at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. + * For more information about capturing images, see How to Capture an Image + * of a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Begin Capturing + * Virtual Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginCapturingOSImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters); + + /** + * Begin capturing role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginCapturingVMImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Begin capturing role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginCapturingVMImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters); + + /** + * The Begin Creating Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginCreating(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Creating Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginCreatingAsync(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters); + + /** + * The Begin Creating Virtual Machine Deployment operation provisions a + * virtual machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine Deployment operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginCreatingDeployment(String serviceName, VirtualMachineCreateDeploymentParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Creating Virtual Machine Deployment operation provisions a + * virtual machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine Deployment operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginCreatingDeploymentAsync(String serviceName, VirtualMachineCreateDeploymentParameters parameters); + + /** + * The Begin Deleting Role operation deletes the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeleting(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage) throws IOException, ServiceException; + + /** + * The Begin Deleting Role operation deletes the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingAsync(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage); + + /** + * The Begin Restarting role operation restarts the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginRestarting(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException; + + /** + * The Begin Restarting role operation restarts the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginRestartingAsync(String serviceName, String deploymentName, String virtualMachineName); + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown vm operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginShutdown(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown vm operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginShutdownAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters); + + /** + * The Begin Shutting Down Roles operation stops the specified set of + * virtual machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Shutting Down + * Roles operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginShuttingDownRoles(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Shutting Down Roles operation stops the specified set of + * virtual machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Shutting Down + * Roles operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginShuttingDownRolesAsync(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters); + + /** + * The Begin Starting Role operation starts the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginStarting(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException; + + /** + * The Begin Starting Role operation starts the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginStartingAsync(String serviceName, String deploymentName, String virtualMachineName); + + /** + * The Begin Starting Roles operation starts the specified set of virtual + * machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Starting + * Roles operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginStartingRoles(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Starting Roles operation starts the specified set of virtual + * machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Starting + * Roles operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginStartingRolesAsync(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters); + + /** + * The Begin Updating Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Begin Updating + * Virtual Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginUpdating(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Updating Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Begin Updating + * Virtual Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginUpdatingAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters); + + /** + * The Begin Updating Load Balanced Endpoint Set operation changes the + * specified load-balanced InputEndpoints on all the roles of an + * Infrastructure as a Service deployment. Non-load-balanced endpoints must + * be changed using UpdateRole. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Load Balanced Endpoint Set operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginUpdatingLoadBalancedEndpointSet(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Updating Load Balanced Endpoint Set operation changes the + * specified load-balanced InputEndpoints on all the roles of an + * Infrastructure as a Service deployment. Non-load-balanced endpoints must + * be changed using UpdateRole. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Load Balanced Endpoint Set operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginUpdatingLoadBalancedEndpointSetAsync(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters); + + /** + * The Capture Role operation creates a copy of the operating system virtual + * hard disk (VHD) that is deployed in the virtual machine, saves the VHD + * copy in the same storage location as the operating system VHD, and + * registers the copy as an image in your image gallery. From the captured + * image, you can create additional customized virtual machines. For more + * information about images and disks, see Manage Disks and Images at + * http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For + * more information about capturing images, see How to Capture an Image of + * a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse captureOSImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Capture Role operation creates a copy of the operating system virtual + * hard disk (VHD) that is deployed in the virtual machine, saves the VHD + * copy in the same storage location as the operating system VHD, and + * registers the copy as an image in your image gallery. From the captured + * image, you can create additional customized virtual machines. For more + * information about images and disks, see Manage Disks and Images at + * http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For + * more information about capturing images, see How to Capture an Image of + * a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future captureOSImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters); + + /** + * Capture role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse captureVMImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * Capture role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future captureVMImageAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters); + + /** + * The Create Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse create(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException; + + /** + * The Create Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future createAsync(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters); + + /** + * The Create Virtual Machine Deployment operation provisions a virtual + * machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Deployment operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse createDeployment(String serviceName, VirtualMachineCreateDeploymentParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Create Virtual Machine Deployment operation provisions a virtual + * machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Deployment operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future createDeploymentAsync(String serviceName, VirtualMachineCreateDeploymentParameters parameters); + + /** + * The Delete Role operation deletes the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse delete(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException; + + /** + * The Delete Role operation deletes the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteAsync(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage); + + /** + * The Get Role operation retrieves information about the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Virtual Machine operation response. + */ + VirtualMachineGetResponse get(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Role operation retrieves information about the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @return The Get Virtual Machine operation response. + */ + Future getAsync(String serviceName, String deploymentName, String virtualMachineName); + + /** + * The Download RDP file operation retrieves the Remote Desktop Protocol + * configuration file from the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The Download RDP file operation response. + */ + VirtualMachineGetRemoteDesktopFileResponse getRemoteDesktopFile(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException; + + /** + * The Download RDP file operation retrieves the Remote Desktop Protocol + * configuration file from the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @return The Download RDP file operation response. + */ + Future getRemoteDesktopFileAsync(String serviceName, String deploymentName, String virtualMachineName); + + /** + * The Restart role operation restarts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse restart(String serviceName, String deploymentName, String virtualMachineName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Restart role operation restarts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future restartAsync(String serviceName, String deploymentName, String virtualMachineName); + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown virtual + * machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse shutdown(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown virtual + * machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future shutdownAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters); + + /** + * The Shutdown Roles operation stops the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Shutdown Roles + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse shutdownRoles(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Shutdown Roles operation stops the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Shutdown Roles + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future shutdownRolesAsync(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters); + + /** + * The Start Role operation starts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse start(String serviceName, String deploymentName, String virtualMachineName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Start Role operation starts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future startAsync(String serviceName, String deploymentName, String virtualMachineName); + + /** + * The Start Roles operation starts the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Start Roles + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse startRoles(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Start Roles operation starts the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Start Roles + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future startRolesAsync(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters); + + /** + * The Update Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse update(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, InterruptedException, ExecutionException, URISyntaxException; + + /** + * The Update Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future updateAsync(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters); + + /** + * The Update Load Balanced Endpoint Set operation changes the specified + * load-balanced InputEndpoints on all the roles of an Infrastructure as a + * Service deployment. Non-load-balanced endpoints must be changed using + * UpdateRole. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Load + * Balanced Endpoint Set operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse updateLoadBalancedEndpointSet(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Update Load Balanced Endpoint Set operation changes the specified + * load-balanced InputEndpoints on all the roles of an Infrastructure as a + * Service deployment. Non-load-balanced endpoints must be changed using + * UpdateRole. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Load + * Balanced Endpoint Set operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future updateLoadBalancedEndpointSetAsync(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperationsImpl.java new file mode 100644 index 0000000000000..4d021d28dd529 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperationsImpl.java @@ -0,0 +1,6709 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.StreamUtils; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.AccessControlListRule; +import com.microsoft.windowsazure.management.compute.models.ConfigurationSet; +import com.microsoft.windowsazure.management.compute.models.DataVirtualHardDisk; +import com.microsoft.windowsazure.management.compute.models.DnsServer; +import com.microsoft.windowsazure.management.compute.models.DomainJoinCredentials; +import com.microsoft.windowsazure.management.compute.models.DomainJoinProvisioning; +import com.microsoft.windowsazure.management.compute.models.DomainJoinSettings; +import com.microsoft.windowsazure.management.compute.models.EndpointAcl; +import com.microsoft.windowsazure.management.compute.models.InputEndpoint; +import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbe; +import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbeTransportProtocol; +import com.microsoft.windowsazure.management.compute.models.OSVirtualHardDisk; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionParameterValue; +import com.microsoft.windowsazure.management.compute.models.ResourceExtensionReference; +import com.microsoft.windowsazure.management.compute.models.Role; +import com.microsoft.windowsazure.management.compute.models.SshSettingKeyPair; +import com.microsoft.windowsazure.management.compute.models.SshSettingPublicKey; +import com.microsoft.windowsazure.management.compute.models.SshSettings; +import com.microsoft.windowsazure.management.compute.models.StoredCertificateSettings; +import com.microsoft.windowsazure.management.compute.models.VirtualHardDiskHostCaching; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureOSImageParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureVMImageParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateDeploymentParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetRemoteDesktopFileResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetResponse; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineRoleType; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownRolesParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineStartRolesParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateLoadBalancedSetParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateParameters; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineWindowsRemoteManagementListenerType; +import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementListener; +import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementSettings; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* machines in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for more +* information) +*/ +public class VirtualMachineOperationsImpl implements ServiceOperations, VirtualMachineOperations { + /** + * Initializes a new instance of the VirtualMachineOperationsImpl class. + * + * @param client Reference to the service client. + */ + VirtualMachineOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The Begin Capturing Role operation creates a copy of the operating system + * virtual hard disk (VHD) that is deployed in the virtual machine, saves + * the VHD copy in the same storage location as the operating system VHD, + * and registers the copy as an image in your image gallery. From the + * captured image, you can create additional customized virtual machines. + * For more information about images and disks, see Manage Disks and Images + * at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. + * For more information about capturing images, see How to Capture an Image + * of a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Begin Capturing + * Virtual Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCapturingOSImageAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineCaptureOSImageParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginCapturingOSImage(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * The Begin Capturing Role operation creates a copy of the operating system + * virtual hard disk (VHD) that is deployed in the virtual machine, saves + * the VHD copy in the same storage location as the operating system VHD, + * and registers the copy as an image in your image gallery. From the + * captured image, you can create additional customized virtual machines. + * For more information about images and disks, see Manage Disks and Images + * at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. + * For more information about capturing images, see How to Capture an Image + * of a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Begin Capturing + * Virtual Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginCapturingOSImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getProvisioningConfiguration() != null) { + if (parameters.getProvisioningConfiguration().getDomainJoin() != null) { + if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials() != null) { + if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials().getPassword() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.DomainJoin.Credentials.Password"); + } + if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials().getUserName() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.DomainJoin.Credentials.UserName"); + } + } + } + if (parameters.getProvisioningConfiguration().getHostName() != null && parameters.getProvisioningConfiguration().getHostName().length() < 1) { + throw new IllegalArgumentException("parameters.ProvisioningConfiguration.HostName"); + } + if (parameters.getProvisioningConfiguration().getHostName() != null && parameters.getProvisioningConfiguration().getHostName().length() > 64) { + throw new IllegalArgumentException("parameters.ProvisioningConfiguration.HostName"); + } + if (parameters.getProvisioningConfiguration().getSshSettings() != null) { + if (parameters.getProvisioningConfiguration().getSshSettings().getKeyPairs() != null) { + for (SshSettingKeyPair keyPairsParameterItem : parameters.getProvisioningConfiguration().getSshSettings().getKeyPairs()) { + if (keyPairsParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.SshSettings.KeyPairs.Fingerprint"); + } + if (keyPairsParameterItem.getPath() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.SshSettings.KeyPairs.Path"); + } + } + } + if (parameters.getProvisioningConfiguration().getSshSettings().getPublicKeys() != null) { + for (SshSettingPublicKey publicKeysParameterItem : parameters.getProvisioningConfiguration().getSshSettings().getPublicKeys()) { + if (publicKeysParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.SshSettings.PublicKeys.Fingerprint"); + } + if (publicKeysParameterItem.getPath() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.SshSettings.PublicKeys.Path"); + } + } + } + } + if (parameters.getProvisioningConfiguration().getStoredCertificateSettings() != null) { + for (StoredCertificateSettings storedCertificateSettingsParameterItem : parameters.getProvisioningConfiguration().getStoredCertificateSettings()) { + if (storedCertificateSettingsParameterItem.getStoreName() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.StoredCertificateSettings.StoreName"); + } + if (storedCertificateSettingsParameterItem.getThumbprint() == null) { + throw new NullPointerException("parameters.ProvisioningConfiguration.StoredCertificateSettings.Thumbprint"); + } + } + } + if (parameters.getProvisioningConfiguration().getUserName() != null && parameters.getProvisioningConfiguration().getUserName().length() < 1) { + throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserName"); + } + if (parameters.getProvisioningConfiguration().getUserName() != null && parameters.getProvisioningConfiguration().getUserName().length() > 32) { + throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserName"); + } + if (parameters.getProvisioningConfiguration().getUserPassword() != null && parameters.getProvisioningConfiguration().getUserPassword().length() < 6 && (parameters.getProvisioningConfiguration().isDisableSshPasswordAuthentication() == false || parameters.getProvisioningConfiguration().getUserPassword().length() != 0)) { + throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserPassword"); + } + if (parameters.getProvisioningConfiguration().getUserPassword() != null && parameters.getProvisioningConfiguration().getUserPassword().length() > 72) { + throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserPassword"); + } + } + if (parameters.getTargetImageLabel() == null) { + throw new NullPointerException("parameters.TargetImageLabel"); + } + if (parameters.getTargetImageName() == null) { + throw new NullPointerException("parameters.TargetImageName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCapturingOSImageAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + virtualMachineName.trim() + "/Operations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element captureRoleOperationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CaptureRoleOperation"); + requestDoc.appendChild(captureRoleOperationElement); + + Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OperationType"); + operationTypeElement.appendChild(requestDoc.createTextNode("CaptureRoleOperation")); + captureRoleOperationElement.appendChild(operationTypeElement); + + Element postCaptureActionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PostCaptureAction"); + postCaptureActionElement.appendChild(requestDoc.createTextNode(parameters.getPostCaptureAction().toString())); + captureRoleOperationElement.appendChild(postCaptureActionElement); + + if (parameters.getProvisioningConfiguration() != null) { + Element provisioningConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisioningConfiguration"); + captureRoleOperationElement.appendChild(provisioningConfigurationElement); + + if (parameters.getProvisioningConfiguration().getConfigurationSetType() != null) { + Element configurationSetTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + configurationSetTypeElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getConfigurationSetType())); + provisioningConfigurationElement.appendChild(configurationSetTypeElement); + } + + if (parameters.getProvisioningConfiguration().getInputEndpoints() != null) { + Element inputEndpointsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + for (InputEndpoint inputEndpointsItem : parameters.getProvisioningConfiguration().getInputEndpoints()) { + Element inputEndpointElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint"); + inputEndpointsSequenceElement.appendChild(inputEndpointElement); + + if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) { + Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + loadBalancedEndpointSetNameElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancedEndpointSetName())); + inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement); + } + + if (inputEndpointsItem.getLocalPort() != null) { + Element localPortElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort"); + localPortElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLocalPort()))); + inputEndpointElement.appendChild(localPortElement); + } + + if (inputEndpointsItem.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getName())); + inputEndpointElement.appendChild(nameElement); + } + + if (inputEndpointsItem.getPort() != null) { + Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort()))); + inputEndpointElement.appendChild(portElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe() != null) { + Element loadBalancerProbeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + inputEndpointElement.appendChild(loadBalancerProbeElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) { + Element pathElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerProbe().getPath())); + loadBalancerProbeElement.appendChild(pathElement); + } + + Element portElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement2.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getPort()))); + loadBalancerProbeElement.appendChild(portElement2); + + Element protocolElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement.appendChild(requestDoc.createTextNode(ComputeManagementClientImpl.loadBalancerProbeTransportProtocolToString(inputEndpointsItem.getLoadBalancerProbe().getProtocol()))); + loadBalancerProbeElement.appendChild(protocolElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) { + Element intervalInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + intervalInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds()))); + loadBalancerProbeElement.appendChild(intervalInSecondsElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) { + Element timeoutInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + timeoutInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds()))); + loadBalancerProbeElement.appendChild(timeoutInSecondsElement); + } + } + + if (inputEndpointsItem.getProtocol() != null) { + Element protocolElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement2.appendChild(requestDoc.createTextNode(inputEndpointsItem.getProtocol())); + inputEndpointElement.appendChild(protocolElement2); + } + + if (inputEndpointsItem.getVirtualIPAddress() != null) { + Element vipElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Vip"); + vipElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getVirtualIPAddress().getHostAddress())); + inputEndpointElement.appendChild(vipElement); + } + + if (inputEndpointsItem.isEnableDirectServerReturn() != null) { + Element enableDirectServerReturnElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(Boolean.toString(inputEndpointsItem.isEnableDirectServerReturn()).toLowerCase())); + inputEndpointElement.appendChild(enableDirectServerReturnElement); + } + + if (inputEndpointsItem.getEndpointAcl() != null) { + Element endpointAclElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + inputEndpointElement.appendChild(endpointAclElement); + + if (inputEndpointsItem.getEndpointAcl().getRules() != null) { + Element rulesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rules"); + for (AccessControlListRule rulesItem : inputEndpointsItem.getEndpointAcl().getRules()) { + Element ruleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rule"); + rulesSequenceElement.appendChild(ruleElement); + + if (rulesItem.getOrder() != null) { + Element orderElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Order"); + orderElement.appendChild(requestDoc.createTextNode(Integer.toString(rulesItem.getOrder()))); + ruleElement.appendChild(orderElement); + } + + if (rulesItem.getAction() != null) { + Element actionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Action"); + actionElement.appendChild(requestDoc.createTextNode(rulesItem.getAction())); + ruleElement.appendChild(actionElement); + } + + if (rulesItem.getRemoteSubnet() != null) { + Element remoteSubnetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + remoteSubnetElement.appendChild(requestDoc.createTextNode(rulesItem.getRemoteSubnet())); + ruleElement.appendChild(remoteSubnetElement); + } + + if (rulesItem.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(rulesItem.getDescription())); + ruleElement.appendChild(descriptionElement); + } + } + endpointAclElement.appendChild(rulesSequenceElement); + } + } + } + provisioningConfigurationElement.appendChild(inputEndpointsSequenceElement); + } + + if (parameters.getProvisioningConfiguration().getSubnetNames() != null) { + Element subnetNamesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetNames"); + for (String subnetNamesItem : parameters.getProvisioningConfiguration().getSubnetNames()) { + Element subnetNamesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName"); + subnetNamesItemElement.appendChild(requestDoc.createTextNode(subnetNamesItem)); + subnetNamesSequenceElement.appendChild(subnetNamesItemElement); + } + provisioningConfigurationElement.appendChild(subnetNamesSequenceElement); + } + + if (parameters.getProvisioningConfiguration().getStaticVirtualNetworkIPAddress() != null) { + Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getStaticVirtualNetworkIPAddress())); + provisioningConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement); + } + + if (parameters.getProvisioningConfiguration().getComputerName() != null) { + Element computerNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ComputerName"); + computerNameElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getComputerName())); + provisioningConfigurationElement.appendChild(computerNameElement); + } + + if (parameters.getProvisioningConfiguration().getAdminPassword() != null) { + Element adminPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminPassword"); + adminPasswordElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getAdminPassword())); + provisioningConfigurationElement.appendChild(adminPasswordElement); + } + + if (parameters.getProvisioningConfiguration().isResetPasswordOnFirstLogon() != null) { + Element resetPasswordOnFirstLogonElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.getProvisioningConfiguration().isResetPasswordOnFirstLogon()).toLowerCase())); + provisioningConfigurationElement.appendChild(resetPasswordOnFirstLogonElement); + } + + if (parameters.getProvisioningConfiguration().isEnableAutomaticUpdates() != null) { + Element enableAutomaticUpdatesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.getProvisioningConfiguration().isEnableAutomaticUpdates()).toLowerCase())); + provisioningConfigurationElement.appendChild(enableAutomaticUpdatesElement); + } + + if (parameters.getProvisioningConfiguration().getTimeZone() != null) { + Element timeZoneElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeZone"); + timeZoneElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getTimeZone())); + provisioningConfigurationElement.appendChild(timeZoneElement); + } + + if (parameters.getProvisioningConfiguration().getDomainJoin() != null) { + Element domainJoinElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DomainJoin"); + provisioningConfigurationElement.appendChild(domainJoinElement); + + if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials() != null) { + Element credentialsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Credentials"); + domainJoinElement.appendChild(credentialsElement); + + if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials().getDomain() != null) { + Element domainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Domain"); + domainElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getDomainJoin().getCredentials().getDomain())); + credentialsElement.appendChild(domainElement); + } + + Element usernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Username"); + usernameElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getDomainJoin().getCredentials().getUserName())); + credentialsElement.appendChild(usernameElement); + + Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getDomainJoin().getCredentials().getPassword())); + credentialsElement.appendChild(passwordElement); + } + + if (parameters.getProvisioningConfiguration().getDomainJoin().getDomainToJoin() != null) { + Element joinDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "JoinDomain"); + joinDomainElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getDomainJoin().getDomainToJoin())); + domainJoinElement.appendChild(joinDomainElement); + } + + if (parameters.getProvisioningConfiguration().getDomainJoin().getLdapMachineObjectOU() != null) { + Element machineObjectOUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + machineObjectOUElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getDomainJoin().getLdapMachineObjectOU())); + domainJoinElement.appendChild(machineObjectOUElement); + } + + if (parameters.getProvisioningConfiguration().getDomainJoin().getProvisioning() != null) { + Element provisioningElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Provisioning"); + domainJoinElement.appendChild(provisioningElement); + + if (parameters.getProvisioningConfiguration().getDomainJoin().getProvisioning().getAccountData() != null) { + Element accountDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AccountData"); + accountDataElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getDomainJoin().getProvisioning().getAccountData())); + provisioningElement.appendChild(accountDataElement); + } + } + } + + if (parameters.getProvisioningConfiguration().getStoredCertificateSettings() != null) { + Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + for (StoredCertificateSettings storedCertificateSettingsItem : parameters.getProvisioningConfiguration().getStoredCertificateSettings()) { + Element certificateSettingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateSetting"); + storedCertificateSettingsSequenceElement.appendChild(certificateSettingElement); + + Element storeLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreLocation"); + storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine")); + certificateSettingElement.appendChild(storeLocationElement); + + Element storeNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreName"); + storeNameElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getStoreName())); + certificateSettingElement.appendChild(storeNameElement); + + Element thumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + thumbprintElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getThumbprint())); + certificateSettingElement.appendChild(thumbprintElement); + } + provisioningConfigurationElement.appendChild(storedCertificateSettingsSequenceElement); + } + + if (parameters.getProvisioningConfiguration().getWindowsRemoteManagement() != null) { + Element winRMElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WinRM"); + provisioningConfigurationElement.appendChild(winRMElement); + + if (parameters.getProvisioningConfiguration().getWindowsRemoteManagement().getListeners() != null) { + Element listenersSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listeners"); + for (WindowsRemoteManagementListener listenersItem : parameters.getProvisioningConfiguration().getWindowsRemoteManagement().getListeners()) { + Element listenerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listener"); + listenersSequenceElement.appendChild(listenerElement); + + if (listenersItem.getCertificateThumbprint() != null) { + Element certificateThumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + certificateThumbprintElement.appendChild(requestDoc.createTextNode(listenersItem.getCertificateThumbprint())); + listenerElement.appendChild(certificateThumbprintElement); + } + + Element protocolElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement3.appendChild(requestDoc.createTextNode(listenersItem.getListenerType().toString())); + listenerElement.appendChild(protocolElement3); + } + winRMElement.appendChild(listenersSequenceElement); + } + } + + if (parameters.getProvisioningConfiguration().getAdminUserName() != null) { + Element adminUsernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminUsername"); + adminUsernameElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getAdminUserName())); + provisioningConfigurationElement.appendChild(adminUsernameElement); + } + + if (parameters.getProvisioningConfiguration().getHostName() != null) { + Element hostNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostName"); + hostNameElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getHostName())); + provisioningConfigurationElement.appendChild(hostNameElement); + } + + if (parameters.getProvisioningConfiguration().getUserName() != null) { + Element userNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserName"); + userNameElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getUserName())); + provisioningConfigurationElement.appendChild(userNameElement); + } + + if (parameters.getProvisioningConfiguration().getUserPassword() != null) { + Element userPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserPassword"); + userPasswordElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getUserPassword())); + provisioningConfigurationElement.appendChild(userPasswordElement); + } + + if (parameters.getProvisioningConfiguration().isDisableSshPasswordAuthentication() != null) { + Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.getProvisioningConfiguration().isDisableSshPasswordAuthentication()).toLowerCase())); + provisioningConfigurationElement.appendChild(disableSshPasswordAuthenticationElement); + } + + if (parameters.getProvisioningConfiguration().getSshSettings() != null) { + Element sSHElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SSH"); + provisioningConfigurationElement.appendChild(sSHElement); + + if (parameters.getProvisioningConfiguration().getSshSettings().getPublicKeys() != null) { + Element publicKeysSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKeys"); + for (SshSettingPublicKey publicKeysItem : parameters.getProvisioningConfiguration().getSshSettings().getPublicKeys()) { + Element publicKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKey"); + publicKeysSequenceElement.appendChild(publicKeyElement); + + Element fingerprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement.appendChild(requestDoc.createTextNode(publicKeysItem.getFingerprint())); + publicKeyElement.appendChild(fingerprintElement); + + Element pathElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement2.appendChild(requestDoc.createTextNode(publicKeysItem.getPath())); + publicKeyElement.appendChild(pathElement2); + } + sSHElement.appendChild(publicKeysSequenceElement); + } + + if (parameters.getProvisioningConfiguration().getSshSettings().getKeyPairs() != null) { + Element keyPairsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPairs"); + for (SshSettingKeyPair keyPairsItem : parameters.getProvisioningConfiguration().getSshSettings().getKeyPairs()) { + Element keyPairElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPair"); + keyPairsSequenceElement.appendChild(keyPairElement); + + Element fingerprintElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement2.appendChild(requestDoc.createTextNode(keyPairsItem.getFingerprint())); + keyPairElement.appendChild(fingerprintElement2); + + Element pathElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement3.appendChild(requestDoc.createTextNode(keyPairsItem.getPath())); + keyPairElement.appendChild(pathElement3); + } + sSHElement.appendChild(keyPairsSequenceElement); + } + } + + if (parameters.getProvisioningConfiguration().getCustomData() != null) { + Element customDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CustomData"); + customDataElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration().getCustomData())); + provisioningConfigurationElement.appendChild(customDataElement); + } + } + + Element targetImageLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TargetImageLabel"); + targetImageLabelElement.appendChild(requestDoc.createTextNode(parameters.getTargetImageLabel())); + captureRoleOperationElement.appendChild(targetImageLabelElement); + + Element targetImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TargetImageName"); + targetImageNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetImageName())); + captureRoleOperationElement.appendChild(targetImageNameElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Begin capturing role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCapturingVMImageAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineCaptureVMImageParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginCapturingVMImage(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * Begin capturing role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginCapturingVMImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCapturingVMImageAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + virtualMachineName.trim() + "/Operations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element captureRoleAsVMImageOperationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CaptureRoleAsVMImageOperation"); + requestDoc.appendChild(captureRoleAsVMImageOperationElement); + + Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OperationType"); + operationTypeElement.appendChild(requestDoc.createTextNode("CaptureRoleAsVMImageOperation")); + captureRoleAsVMImageOperationElement.appendChild(operationTypeElement); + + if (parameters.getOSState() != null) { + Element oSStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSState"); + oSStateElement.appendChild(requestDoc.createTextNode(parameters.getOSState())); + captureRoleAsVMImageOperationElement.appendChild(oSStateElement); + } + + if (parameters.getVMImageName() != null) { + Element vMImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "VMImageName"); + vMImageNameElement.appendChild(requestDoc.createTextNode(parameters.getVMImageName())); + captureRoleAsVMImageOperationElement.appendChild(vMImageNameElement); + } + + if (parameters.getVMImageLabel() != null) { + Element vMImageLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "VMImageLabel"); + vMImageLabelElement.appendChild(requestDoc.createTextNode(parameters.getVMImageLabel())); + captureRoleAsVMImageOperationElement.appendChild(vMImageLabelElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Creating Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCreatingAsync(final String serviceName, final String deploymentName, final VirtualMachineCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginCreating(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Creating Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginCreating(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfigurationSets() != null) { + for (ConfigurationSet configurationSetsParameterItem : parameters.getConfigurationSets()) { + if (configurationSetsParameterItem.getDomainJoin() != null) { + if (configurationSetsParameterItem.getDomainJoin().getCredentials() != null) { + if (configurationSetsParameterItem.getDomainJoin().getCredentials().getPassword() == null) { + throw new NullPointerException("parameters.ConfigurationSets.DomainJoin.Credentials.Password"); + } + if (configurationSetsParameterItem.getDomainJoin().getCredentials().getUserName() == null) { + throw new NullPointerException("parameters.ConfigurationSets.DomainJoin.Credentials.UserName"); + } + } + } + if (configurationSetsParameterItem.getHostName() != null && configurationSetsParameterItem.getHostName().length() < 1) { + throw new IllegalArgumentException("parameters.ConfigurationSets.HostName"); + } + if (configurationSetsParameterItem.getHostName() != null && configurationSetsParameterItem.getHostName().length() > 64) { + throw new IllegalArgumentException("parameters.ConfigurationSets.HostName"); + } + if (configurationSetsParameterItem.getSshSettings() != null) { + if (configurationSetsParameterItem.getSshSettings().getKeyPairs() != null) { + for (SshSettingKeyPair keyPairsParameterItem : configurationSetsParameterItem.getSshSettings().getKeyPairs()) { + if (keyPairsParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.KeyPairs.Fingerprint"); + } + if (keyPairsParameterItem.getPath() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.KeyPairs.Path"); + } + } + } + if (configurationSetsParameterItem.getSshSettings().getPublicKeys() != null) { + for (SshSettingPublicKey publicKeysParameterItem : configurationSetsParameterItem.getSshSettings().getPublicKeys()) { + if (publicKeysParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.PublicKeys.Fingerprint"); + } + if (publicKeysParameterItem.getPath() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.PublicKeys.Path"); + } + } + } + } + if (configurationSetsParameterItem.getStoredCertificateSettings() != null) { + for (StoredCertificateSettings storedCertificateSettingsParameterItem : configurationSetsParameterItem.getStoredCertificateSettings()) { + if (storedCertificateSettingsParameterItem.getStoreName() == null) { + throw new NullPointerException("parameters.ConfigurationSets.StoredCertificateSettings.StoreName"); + } + if (storedCertificateSettingsParameterItem.getThumbprint() == null) { + throw new NullPointerException("parameters.ConfigurationSets.StoredCertificateSettings.Thumbprint"); + } + } + } + if (configurationSetsParameterItem.getUserName() != null && configurationSetsParameterItem.getUserName().length() < 1) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserName"); + } + if (configurationSetsParameterItem.getUserName() != null && configurationSetsParameterItem.getUserName().length() > 32) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserName"); + } + if (configurationSetsParameterItem.getUserPassword() != null && configurationSetsParameterItem.getUserPassword().length() < 6 && (configurationSetsParameterItem.isDisableSshPasswordAuthentication() == false || configurationSetsParameterItem.getUserPassword().length() != 0)) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword"); + } + if (configurationSetsParameterItem.getUserPassword() != null && configurationSetsParameterItem.getUserPassword().length() > 72) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword"); + } + } + } + if (parameters.getRoleName() == null) { + throw new NullPointerException("parameters.RoleName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element persistentVMRoleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PersistentVMRole"); + requestDoc.appendChild(persistentVMRoleElement); + + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(parameters.getRoleName())); + persistentVMRoleElement.appendChild(roleNameElement); + + Element roleTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleType"); + roleTypeElement.appendChild(requestDoc.createTextNode("PersistentVMRole")); + persistentVMRoleElement.appendChild(roleTypeElement); + + if (parameters.getConfigurationSets() != null) { + Element configurationSetsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSets"); + for (ConfigurationSet configurationSetsItem : parameters.getConfigurationSets()) { + Element configurationSetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSet"); + configurationSetsSequenceElement.appendChild(configurationSetElement); + + if (configurationSetsItem.getConfigurationSetType() != null) { + Element configurationSetTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + configurationSetTypeElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getConfigurationSetType())); + configurationSetElement.appendChild(configurationSetTypeElement); + } + + if (configurationSetsItem.getInputEndpoints() != null) { + Element inputEndpointsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + for (InputEndpoint inputEndpointsItem : configurationSetsItem.getInputEndpoints()) { + Element inputEndpointElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint"); + inputEndpointsSequenceElement.appendChild(inputEndpointElement); + + if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) { + Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + loadBalancedEndpointSetNameElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancedEndpointSetName())); + inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement); + } + + if (inputEndpointsItem.getLocalPort() != null) { + Element localPortElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort"); + localPortElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLocalPort()))); + inputEndpointElement.appendChild(localPortElement); + } + + if (inputEndpointsItem.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getName())); + inputEndpointElement.appendChild(nameElement); + } + + if (inputEndpointsItem.getPort() != null) { + Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort()))); + inputEndpointElement.appendChild(portElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe() != null) { + Element loadBalancerProbeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + inputEndpointElement.appendChild(loadBalancerProbeElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) { + Element pathElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerProbe().getPath())); + loadBalancerProbeElement.appendChild(pathElement); + } + + Element portElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement2.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getPort()))); + loadBalancerProbeElement.appendChild(portElement2); + + Element protocolElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement.appendChild(requestDoc.createTextNode(ComputeManagementClientImpl.loadBalancerProbeTransportProtocolToString(inputEndpointsItem.getLoadBalancerProbe().getProtocol()))); + loadBalancerProbeElement.appendChild(protocolElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) { + Element intervalInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + intervalInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds()))); + loadBalancerProbeElement.appendChild(intervalInSecondsElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) { + Element timeoutInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + timeoutInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds()))); + loadBalancerProbeElement.appendChild(timeoutInSecondsElement); + } + } + + if (inputEndpointsItem.getProtocol() != null) { + Element protocolElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement2.appendChild(requestDoc.createTextNode(inputEndpointsItem.getProtocol())); + inputEndpointElement.appendChild(protocolElement2); + } + + if (inputEndpointsItem.getVirtualIPAddress() != null) { + Element vipElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Vip"); + vipElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getVirtualIPAddress().getHostAddress())); + inputEndpointElement.appendChild(vipElement); + } + + if (inputEndpointsItem.isEnableDirectServerReturn() != null) { + Element enableDirectServerReturnElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(Boolean.toString(inputEndpointsItem.isEnableDirectServerReturn()).toLowerCase())); + inputEndpointElement.appendChild(enableDirectServerReturnElement); + } + + if (inputEndpointsItem.getEndpointAcl() != null) { + Element endpointAclElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + inputEndpointElement.appendChild(endpointAclElement); + + if (inputEndpointsItem.getEndpointAcl().getRules() != null) { + Element rulesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rules"); + for (AccessControlListRule rulesItem : inputEndpointsItem.getEndpointAcl().getRules()) { + Element ruleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rule"); + rulesSequenceElement.appendChild(ruleElement); + + if (rulesItem.getOrder() != null) { + Element orderElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Order"); + orderElement.appendChild(requestDoc.createTextNode(Integer.toString(rulesItem.getOrder()))); + ruleElement.appendChild(orderElement); + } + + if (rulesItem.getAction() != null) { + Element actionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Action"); + actionElement.appendChild(requestDoc.createTextNode(rulesItem.getAction())); + ruleElement.appendChild(actionElement); + } + + if (rulesItem.getRemoteSubnet() != null) { + Element remoteSubnetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + remoteSubnetElement.appendChild(requestDoc.createTextNode(rulesItem.getRemoteSubnet())); + ruleElement.appendChild(remoteSubnetElement); + } + + if (rulesItem.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(rulesItem.getDescription())); + ruleElement.appendChild(descriptionElement); + } + } + endpointAclElement.appendChild(rulesSequenceElement); + } + } + } + configurationSetElement.appendChild(inputEndpointsSequenceElement); + } + + if (configurationSetsItem.getSubnetNames() != null) { + Element subnetNamesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetNames"); + for (String subnetNamesItem : configurationSetsItem.getSubnetNames()) { + Element subnetNamesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName"); + subnetNamesItemElement.appendChild(requestDoc.createTextNode(subnetNamesItem)); + subnetNamesSequenceElement.appendChild(subnetNamesItemElement); + } + configurationSetElement.appendChild(subnetNamesSequenceElement); + } + + if (configurationSetsItem.getStaticVirtualNetworkIPAddress() != null) { + Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getStaticVirtualNetworkIPAddress())); + configurationSetElement.appendChild(staticVirtualNetworkIPAddressElement); + } + + if (configurationSetsItem.getComputerName() != null) { + Element computerNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ComputerName"); + computerNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getComputerName())); + configurationSetElement.appendChild(computerNameElement); + } + + if (configurationSetsItem.getAdminPassword() != null) { + Element adminPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminPassword"); + adminPasswordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminPassword())); + configurationSetElement.appendChild(adminPasswordElement); + } + + if (configurationSetsItem.isResetPasswordOnFirstLogon() != null) { + Element resetPasswordOnFirstLogonElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isResetPasswordOnFirstLogon()).toLowerCase())); + configurationSetElement.appendChild(resetPasswordOnFirstLogonElement); + } + + if (configurationSetsItem.isEnableAutomaticUpdates() != null) { + Element enableAutomaticUpdatesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isEnableAutomaticUpdates()).toLowerCase())); + configurationSetElement.appendChild(enableAutomaticUpdatesElement); + } + + if (configurationSetsItem.getTimeZone() != null) { + Element timeZoneElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeZone"); + timeZoneElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getTimeZone())); + configurationSetElement.appendChild(timeZoneElement); + } + + if (configurationSetsItem.getDomainJoin() != null) { + Element domainJoinElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DomainJoin"); + configurationSetElement.appendChild(domainJoinElement); + + if (configurationSetsItem.getDomainJoin().getCredentials() != null) { + Element credentialsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Credentials"); + domainJoinElement.appendChild(credentialsElement); + + if (configurationSetsItem.getDomainJoin().getCredentials().getDomain() != null) { + Element domainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Domain"); + domainElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getDomain())); + credentialsElement.appendChild(domainElement); + } + + Element usernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Username"); + usernameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getUserName())); + credentialsElement.appendChild(usernameElement); + + Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getPassword())); + credentialsElement.appendChild(passwordElement); + } + + if (configurationSetsItem.getDomainJoin().getDomainToJoin() != null) { + Element joinDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "JoinDomain"); + joinDomainElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getDomainToJoin())); + domainJoinElement.appendChild(joinDomainElement); + } + + if (configurationSetsItem.getDomainJoin().getLdapMachineObjectOU() != null) { + Element machineObjectOUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + machineObjectOUElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getLdapMachineObjectOU())); + domainJoinElement.appendChild(machineObjectOUElement); + } + + if (configurationSetsItem.getDomainJoin().getProvisioning() != null) { + Element provisioningElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Provisioning"); + domainJoinElement.appendChild(provisioningElement); + + if (configurationSetsItem.getDomainJoin().getProvisioning().getAccountData() != null) { + Element accountDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AccountData"); + accountDataElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getProvisioning().getAccountData())); + provisioningElement.appendChild(accountDataElement); + } + } + } + + if (configurationSetsItem.getStoredCertificateSettings() != null) { + Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + for (StoredCertificateSettings storedCertificateSettingsItem : configurationSetsItem.getStoredCertificateSettings()) { + Element certificateSettingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateSetting"); + storedCertificateSettingsSequenceElement.appendChild(certificateSettingElement); + + Element storeLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreLocation"); + storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine")); + certificateSettingElement.appendChild(storeLocationElement); + + Element storeNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreName"); + storeNameElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getStoreName())); + certificateSettingElement.appendChild(storeNameElement); + + Element thumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + thumbprintElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getThumbprint())); + certificateSettingElement.appendChild(thumbprintElement); + } + configurationSetElement.appendChild(storedCertificateSettingsSequenceElement); + } + + if (configurationSetsItem.getWindowsRemoteManagement() != null) { + Element winRMElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WinRM"); + configurationSetElement.appendChild(winRMElement); + + if (configurationSetsItem.getWindowsRemoteManagement().getListeners() != null) { + Element listenersSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listeners"); + for (WindowsRemoteManagementListener listenersItem : configurationSetsItem.getWindowsRemoteManagement().getListeners()) { + Element listenerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listener"); + listenersSequenceElement.appendChild(listenerElement); + + if (listenersItem.getCertificateThumbprint() != null) { + Element certificateThumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + certificateThumbprintElement.appendChild(requestDoc.createTextNode(listenersItem.getCertificateThumbprint())); + listenerElement.appendChild(certificateThumbprintElement); + } + + Element protocolElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement3.appendChild(requestDoc.createTextNode(listenersItem.getListenerType().toString())); + listenerElement.appendChild(protocolElement3); + } + winRMElement.appendChild(listenersSequenceElement); + } + } + + if (configurationSetsItem.getAdminUserName() != null) { + Element adminUsernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminUsername"); + adminUsernameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminUserName())); + configurationSetElement.appendChild(adminUsernameElement); + } + + if (configurationSetsItem.getHostName() != null) { + Element hostNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostName"); + hostNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getHostName())); + configurationSetElement.appendChild(hostNameElement); + } + + if (configurationSetsItem.getUserName() != null) { + Element userNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserName"); + userNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserName())); + configurationSetElement.appendChild(userNameElement); + } + + if (configurationSetsItem.getUserPassword() != null) { + Element userPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserPassword"); + userPasswordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserPassword())); + configurationSetElement.appendChild(userPasswordElement); + } + + if (configurationSetsItem.isDisableSshPasswordAuthentication() != null) { + Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isDisableSshPasswordAuthentication()).toLowerCase())); + configurationSetElement.appendChild(disableSshPasswordAuthenticationElement); + } + + if (configurationSetsItem.getSshSettings() != null) { + Element sSHElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SSH"); + configurationSetElement.appendChild(sSHElement); + + if (configurationSetsItem.getSshSettings().getPublicKeys() != null) { + Element publicKeysSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKeys"); + for (SshSettingPublicKey publicKeysItem : configurationSetsItem.getSshSettings().getPublicKeys()) { + Element publicKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKey"); + publicKeysSequenceElement.appendChild(publicKeyElement); + + Element fingerprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement.appendChild(requestDoc.createTextNode(publicKeysItem.getFingerprint())); + publicKeyElement.appendChild(fingerprintElement); + + Element pathElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement2.appendChild(requestDoc.createTextNode(publicKeysItem.getPath())); + publicKeyElement.appendChild(pathElement2); + } + sSHElement.appendChild(publicKeysSequenceElement); + } + + if (configurationSetsItem.getSshSettings().getKeyPairs() != null) { + Element keyPairsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPairs"); + for (SshSettingKeyPair keyPairsItem : configurationSetsItem.getSshSettings().getKeyPairs()) { + Element keyPairElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPair"); + keyPairsSequenceElement.appendChild(keyPairElement); + + Element fingerprintElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement2.appendChild(requestDoc.createTextNode(keyPairsItem.getFingerprint())); + keyPairElement.appendChild(fingerprintElement2); + + Element pathElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement3.appendChild(requestDoc.createTextNode(keyPairsItem.getPath())); + keyPairElement.appendChild(pathElement3); + } + sSHElement.appendChild(keyPairsSequenceElement); + } + } + + if (configurationSetsItem.getCustomData() != null) { + Element customDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CustomData"); + customDataElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getCustomData())); + configurationSetElement.appendChild(customDataElement); + } + } + persistentVMRoleElement.appendChild(configurationSetsSequenceElement); + } + + if (parameters.getAvailabilitySetName() != null) { + Element availabilitySetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AvailabilitySetName"); + availabilitySetNameElement.appendChild(requestDoc.createTextNode(parameters.getAvailabilitySetName())); + persistentVMRoleElement.appendChild(availabilitySetNameElement); + } + + if (parameters.getResourceExtensionReferences() != null) { + Element resourceExtensionReferencesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences"); + for (ResourceExtensionReference resourceExtensionReferencesItem : parameters.getResourceExtensionReferences()) { + Element resourceExtensionReferenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference"); + resourceExtensionReferencesSequenceElement.appendChild(resourceExtensionReferenceElement); + + if (resourceExtensionReferencesItem.getReferenceName() != null) { + Element referenceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ReferenceName"); + referenceNameElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getReferenceName())); + resourceExtensionReferenceElement.appendChild(referenceNameElement); + } + + if (resourceExtensionReferencesItem.getPublisher() != null) { + Element publisherElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Publisher"); + publisherElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getPublisher())); + resourceExtensionReferenceElement.appendChild(publisherElement); + } + + if (resourceExtensionReferencesItem.getName() != null) { + Element nameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement2.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getName())); + resourceExtensionReferenceElement.appendChild(nameElement2); + } + + if (resourceExtensionReferencesItem.getVersion() != null) { + Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version"); + versionElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getVersion())); + resourceExtensionReferenceElement.appendChild(versionElement); + } + + if (resourceExtensionReferencesItem.getResourceExtensionParameterValues() != null) { + Element resourceExtensionParameterValuesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValues"); + for (ResourceExtensionParameterValue resourceExtensionParameterValuesItem : resourceExtensionReferencesItem.getResourceExtensionParameterValues()) { + Element resourceExtensionParameterValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue"); + resourceExtensionParameterValuesSequenceElement.appendChild(resourceExtensionParameterValueElement); + + if (resourceExtensionParameterValuesItem.getKey() != null) { + Element keyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Key"); + keyElement.appendChild(requestDoc.createTextNode(resourceExtensionParameterValuesItem.getKey())); + resourceExtensionParameterValueElement.appendChild(keyElement); + } + + if (resourceExtensionParameterValuesItem.getValue() != null) { + Element valueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + valueElement.appendChild(requestDoc.createTextNode(Base64.encode(resourceExtensionParameterValuesItem.getValue().getBytes()))); + resourceExtensionParameterValueElement.appendChild(valueElement); + } + + if (resourceExtensionParameterValuesItem.getType() != null) { + Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); + typeElement.appendChild(requestDoc.createTextNode(resourceExtensionParameterValuesItem.getType())); + resourceExtensionParameterValueElement.appendChild(typeElement); + } + } + resourceExtensionReferenceElement.appendChild(resourceExtensionParameterValuesSequenceElement); + } + + if (resourceExtensionReferencesItem.getState() != null) { + Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State"); + stateElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getState())); + resourceExtensionReferenceElement.appendChild(stateElement); + } + } + persistentVMRoleElement.appendChild(resourceExtensionReferencesSequenceElement); + } + + if (parameters.getVMImageName() != null) { + Element vMImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "VMImageName"); + vMImageNameElement.appendChild(requestDoc.createTextNode(parameters.getVMImageName())); + persistentVMRoleElement.appendChild(vMImageNameElement); + } + + if (parameters.getDataVirtualHardDisks() != null) { + Element dataVirtualHardDisksSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks"); + for (DataVirtualHardDisk dataVirtualHardDisksItem : parameters.getDataVirtualHardDisks()) { + Element dataVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk"); + dataVirtualHardDisksSequenceElement.appendChild(dataVirtualHardDiskElement); + + if (dataVirtualHardDisksItem.getHostCaching() != null) { + Element hostCachingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getHostCaching().toString())); + dataVirtualHardDiskElement.appendChild(hostCachingElement); + } + + if (dataVirtualHardDisksItem.getLabel() != null) { + Element diskLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getLabel())); + dataVirtualHardDiskElement.appendChild(diskLabelElement); + } + + if (dataVirtualHardDisksItem.getName() != null) { + Element diskNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getName())); + dataVirtualHardDiskElement.appendChild(diskNameElement); + } + + if (dataVirtualHardDisksItem.getLogicalUnitNumber() != null) { + Element lunElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Lun"); + lunElement.appendChild(requestDoc.createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalUnitNumber()))); + dataVirtualHardDiskElement.appendChild(lunElement); + } + + if (dataVirtualHardDisksItem.getLogicalDiskSizeInGB() != null) { + Element logicalDiskSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalDiskSizeInGB()))); + dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement); + } + + if (dataVirtualHardDisksItem.getMediaLink() != null) { + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getMediaLink().toString())); + dataVirtualHardDiskElement.appendChild(mediaLinkElement); + } + + if (dataVirtualHardDisksItem.getSourceMediaLink() != null) { + Element sourceMediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + sourceMediaLinkElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getSourceMediaLink().toString())); + dataVirtualHardDiskElement.appendChild(sourceMediaLinkElement); + } + } + persistentVMRoleElement.appendChild(dataVirtualHardDisksSequenceElement); + } + + if (parameters.getOSVirtualHardDisk() != null) { + Element oSVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk"); + persistentVMRoleElement.appendChild(oSVirtualHardDiskElement); + + if (parameters.getOSVirtualHardDisk().getHostCaching() != null) { + Element hostCachingElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getHostCaching().toString())); + oSVirtualHardDiskElement.appendChild(hostCachingElement2); + } + + if (parameters.getOSVirtualHardDisk().getLabel() != null) { + Element diskLabelElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getLabel())); + oSVirtualHardDiskElement.appendChild(diskLabelElement2); + } + + if (parameters.getOSVirtualHardDisk().getName() != null) { + Element diskNameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getName())); + oSVirtualHardDiskElement.appendChild(diskNameElement2); + } + + if (parameters.getOSVirtualHardDisk().getMediaLink() != null) { + Element mediaLinkElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getMediaLink().toString())); + oSVirtualHardDiskElement.appendChild(mediaLinkElement2); + } + + if (parameters.getOSVirtualHardDisk().getSourceImageName() != null) { + Element sourceImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceImageName"); + sourceImageNameElement.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getSourceImageName())); + oSVirtualHardDiskElement.appendChild(sourceImageNameElement); + } + + if (parameters.getOSVirtualHardDisk().getOperatingSystem() != null) { + Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS"); + osElement.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getOperatingSystem())); + oSVirtualHardDiskElement.appendChild(osElement); + } + } + + if (parameters.getRoleSize() != null) { + Element roleSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleSize"); + roleSizeElement.appendChild(requestDoc.createTextNode(parameters.getRoleSize())); + persistentVMRoleElement.appendChild(roleSizeElement); + } + + if (parameters.isProvisionGuestAgent() != null) { + Element provisionGuestAgentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent"); + provisionGuestAgentElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isProvisionGuestAgent()).toLowerCase())); + persistentVMRoleElement.appendChild(provisionGuestAgentElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Creating Virtual Machine Deployment operation provisions a + * virtual machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine Deployment operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCreatingDeploymentAsync(final String serviceName, final VirtualMachineCreateDeploymentParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginCreatingDeployment(serviceName, parameters); + } + }); + } + + /** + * The Begin Creating Virtual Machine Deployment operation provisions a + * virtual machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Machine Deployment operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginCreatingDeployment(String serviceName, VirtualMachineCreateDeploymentParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getLabel().length() > 100) { + throw new IllegalArgumentException("parameters.Label"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + if (parameters.getRoles() == null) { + throw new NullPointerException("parameters.Roles"); + } + if (parameters.getRoles() != null) { + for (Role rolesParameterItem : parameters.getRoles()) { + if (rolesParameterItem.getConfigurationSets() != null) { + for (ConfigurationSet configurationSetsParameterItem : rolesParameterItem.getConfigurationSets()) { + if (configurationSetsParameterItem.getDomainJoin() != null) { + if (configurationSetsParameterItem.getDomainJoin().getCredentials() != null) { + if (configurationSetsParameterItem.getDomainJoin().getCredentials().getPassword() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.DomainJoin.Credentials.Password"); + } + if (configurationSetsParameterItem.getDomainJoin().getCredentials().getUserName() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.DomainJoin.Credentials.UserName"); + } + } + } + if (configurationSetsParameterItem.getHostName() != null && configurationSetsParameterItem.getHostName().length() < 1) { + throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.HostName"); + } + if (configurationSetsParameterItem.getHostName() != null && configurationSetsParameterItem.getHostName().length() > 64) { + throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.HostName"); + } + if (configurationSetsParameterItem.getSshSettings() != null) { + if (configurationSetsParameterItem.getSshSettings().getKeyPairs() != null) { + for (SshSettingKeyPair keyPairsParameterItem : configurationSetsParameterItem.getSshSettings().getKeyPairs()) { + if (keyPairsParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.SshSettings.KeyPairs.Fingerprint"); + } + if (keyPairsParameterItem.getPath() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.SshSettings.KeyPairs.Path"); + } + } + } + if (configurationSetsParameterItem.getSshSettings().getPublicKeys() != null) { + for (SshSettingPublicKey publicKeysParameterItem : configurationSetsParameterItem.getSshSettings().getPublicKeys()) { + if (publicKeysParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.SshSettings.PublicKeys.Fingerprint"); + } + if (publicKeysParameterItem.getPath() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.SshSettings.PublicKeys.Path"); + } + } + } + } + if (configurationSetsParameterItem.getStoredCertificateSettings() != null) { + for (StoredCertificateSettings storedCertificateSettingsParameterItem : configurationSetsParameterItem.getStoredCertificateSettings()) { + if (storedCertificateSettingsParameterItem.getStoreName() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.StoredCertificateSettings.StoreName"); + } + if (storedCertificateSettingsParameterItem.getThumbprint() == null) { + throw new NullPointerException("parameters.Roles.ConfigurationSets.StoredCertificateSettings.Thumbprint"); + } + } + } + if (configurationSetsParameterItem.getUserName() != null && configurationSetsParameterItem.getUserName().length() < 1) { + throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserName"); + } + if (configurationSetsParameterItem.getUserName() != null && configurationSetsParameterItem.getUserName().length() > 32) { + throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserName"); + } + if (configurationSetsParameterItem.getUserPassword() != null && configurationSetsParameterItem.getUserPassword().length() < 6 && (configurationSetsParameterItem.isDisableSshPasswordAuthentication() == false || configurationSetsParameterItem.getUserPassword().length() != 0)) { + throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserPassword"); + } + if (configurationSetsParameterItem.getUserPassword() != null && configurationSetsParameterItem.getUserPassword().length() > 72) { + throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserPassword"); + } + } + } + } + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCreatingDeploymentAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element deploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Deployment"); + requestDoc.appendChild(deploymentElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + deploymentElement.appendChild(nameElement); + + Element deploymentSlotElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DeploymentSlot"); + deploymentSlotElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentSlot().toString())); + deploymentElement.appendChild(deploymentSlotElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + deploymentElement.appendChild(labelElement); + + Element roleListSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleList"); + for (Role roleListItem : parameters.getRoles()) { + Element roleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Role"); + roleListSequenceElement.appendChild(roleElement); + + if (roleListItem.getRoleName() != null) { + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(roleListItem.getRoleName())); + roleElement.appendChild(roleNameElement); + } + + if (roleListItem.getOSVersion() != null) { + Element osVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OsVersion"); + osVersionElement.appendChild(requestDoc.createTextNode(roleListItem.getOSVersion())); + roleElement.appendChild(osVersionElement); + } + + if (roleListItem.getRoleType() != null) { + Element roleTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleType"); + roleTypeElement.appendChild(requestDoc.createTextNode(roleListItem.getRoleType())); + roleElement.appendChild(roleTypeElement); + } + + if (roleListItem.getConfigurationSets() != null) { + Element configurationSetsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSets"); + for (ConfigurationSet configurationSetsItem : roleListItem.getConfigurationSets()) { + Element configurationSetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSet"); + configurationSetsSequenceElement.appendChild(configurationSetElement); + + if (configurationSetsItem.getConfigurationSetType() != null) { + Element configurationSetTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + configurationSetTypeElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getConfigurationSetType())); + configurationSetElement.appendChild(configurationSetTypeElement); + } + + if (configurationSetsItem.getInputEndpoints() != null) { + Element inputEndpointsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + for (InputEndpoint inputEndpointsItem : configurationSetsItem.getInputEndpoints()) { + Element inputEndpointElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint"); + inputEndpointsSequenceElement.appendChild(inputEndpointElement); + + if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) { + Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + loadBalancedEndpointSetNameElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancedEndpointSetName())); + inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement); + } + + if (inputEndpointsItem.getLocalPort() != null) { + Element localPortElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort"); + localPortElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLocalPort()))); + inputEndpointElement.appendChild(localPortElement); + } + + if (inputEndpointsItem.getName() != null) { + Element nameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement2.appendChild(requestDoc.createTextNode(inputEndpointsItem.getName())); + inputEndpointElement.appendChild(nameElement2); + } + + if (inputEndpointsItem.getPort() != null) { + Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort()))); + inputEndpointElement.appendChild(portElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe() != null) { + Element loadBalancerProbeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + inputEndpointElement.appendChild(loadBalancerProbeElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) { + Element pathElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerProbe().getPath())); + loadBalancerProbeElement.appendChild(pathElement); + } + + Element portElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement2.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getPort()))); + loadBalancerProbeElement.appendChild(portElement2); + + Element protocolElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement.appendChild(requestDoc.createTextNode(ComputeManagementClientImpl.loadBalancerProbeTransportProtocolToString(inputEndpointsItem.getLoadBalancerProbe().getProtocol()))); + loadBalancerProbeElement.appendChild(protocolElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) { + Element intervalInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + intervalInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds()))); + loadBalancerProbeElement.appendChild(intervalInSecondsElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) { + Element timeoutInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + timeoutInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds()))); + loadBalancerProbeElement.appendChild(timeoutInSecondsElement); + } + } + + if (inputEndpointsItem.getProtocol() != null) { + Element protocolElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement2.appendChild(requestDoc.createTextNode(inputEndpointsItem.getProtocol())); + inputEndpointElement.appendChild(protocolElement2); + } + + if (inputEndpointsItem.getVirtualIPAddress() != null) { + Element vipElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Vip"); + vipElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getVirtualIPAddress().getHostAddress())); + inputEndpointElement.appendChild(vipElement); + } + + if (inputEndpointsItem.isEnableDirectServerReturn() != null) { + Element enableDirectServerReturnElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(Boolean.toString(inputEndpointsItem.isEnableDirectServerReturn()).toLowerCase())); + inputEndpointElement.appendChild(enableDirectServerReturnElement); + } + + if (inputEndpointsItem.getEndpointAcl() != null) { + Element endpointAclElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + inputEndpointElement.appendChild(endpointAclElement); + + if (inputEndpointsItem.getEndpointAcl().getRules() != null) { + Element rulesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rules"); + for (AccessControlListRule rulesItem : inputEndpointsItem.getEndpointAcl().getRules()) { + Element ruleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rule"); + rulesSequenceElement.appendChild(ruleElement); + + if (rulesItem.getOrder() != null) { + Element orderElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Order"); + orderElement.appendChild(requestDoc.createTextNode(Integer.toString(rulesItem.getOrder()))); + ruleElement.appendChild(orderElement); + } + + if (rulesItem.getAction() != null) { + Element actionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Action"); + actionElement.appendChild(requestDoc.createTextNode(rulesItem.getAction())); + ruleElement.appendChild(actionElement); + } + + if (rulesItem.getRemoteSubnet() != null) { + Element remoteSubnetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + remoteSubnetElement.appendChild(requestDoc.createTextNode(rulesItem.getRemoteSubnet())); + ruleElement.appendChild(remoteSubnetElement); + } + + if (rulesItem.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(rulesItem.getDescription())); + ruleElement.appendChild(descriptionElement); + } + } + endpointAclElement.appendChild(rulesSequenceElement); + } + } + } + configurationSetElement.appendChild(inputEndpointsSequenceElement); + } + + if (configurationSetsItem.getSubnetNames() != null) { + Element subnetNamesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetNames"); + for (String subnetNamesItem : configurationSetsItem.getSubnetNames()) { + Element subnetNamesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName"); + subnetNamesItemElement.appendChild(requestDoc.createTextNode(subnetNamesItem)); + subnetNamesSequenceElement.appendChild(subnetNamesItemElement); + } + configurationSetElement.appendChild(subnetNamesSequenceElement); + } + + if (configurationSetsItem.getStaticVirtualNetworkIPAddress() != null) { + Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getStaticVirtualNetworkIPAddress())); + configurationSetElement.appendChild(staticVirtualNetworkIPAddressElement); + } + + if (configurationSetsItem.getComputerName() != null) { + Element computerNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ComputerName"); + computerNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getComputerName())); + configurationSetElement.appendChild(computerNameElement); + } + + if (configurationSetsItem.getAdminPassword() != null) { + Element adminPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminPassword"); + adminPasswordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminPassword())); + configurationSetElement.appendChild(adminPasswordElement); + } + + if (configurationSetsItem.isResetPasswordOnFirstLogon() != null) { + Element resetPasswordOnFirstLogonElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isResetPasswordOnFirstLogon()).toLowerCase())); + configurationSetElement.appendChild(resetPasswordOnFirstLogonElement); + } + + if (configurationSetsItem.isEnableAutomaticUpdates() != null) { + Element enableAutomaticUpdatesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isEnableAutomaticUpdates()).toLowerCase())); + configurationSetElement.appendChild(enableAutomaticUpdatesElement); + } + + if (configurationSetsItem.getTimeZone() != null) { + Element timeZoneElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeZone"); + timeZoneElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getTimeZone())); + configurationSetElement.appendChild(timeZoneElement); + } + + if (configurationSetsItem.getDomainJoin() != null) { + Element domainJoinElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DomainJoin"); + configurationSetElement.appendChild(domainJoinElement); + + if (configurationSetsItem.getDomainJoin().getCredentials() != null) { + Element credentialsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Credentials"); + domainJoinElement.appendChild(credentialsElement); + + if (configurationSetsItem.getDomainJoin().getCredentials().getDomain() != null) { + Element domainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Domain"); + domainElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getDomain())); + credentialsElement.appendChild(domainElement); + } + + Element usernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Username"); + usernameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getUserName())); + credentialsElement.appendChild(usernameElement); + + Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getPassword())); + credentialsElement.appendChild(passwordElement); + } + + if (configurationSetsItem.getDomainJoin().getDomainToJoin() != null) { + Element joinDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "JoinDomain"); + joinDomainElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getDomainToJoin())); + domainJoinElement.appendChild(joinDomainElement); + } + + if (configurationSetsItem.getDomainJoin().getLdapMachineObjectOU() != null) { + Element machineObjectOUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + machineObjectOUElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getLdapMachineObjectOU())); + domainJoinElement.appendChild(machineObjectOUElement); + } + + if (configurationSetsItem.getDomainJoin().getProvisioning() != null) { + Element provisioningElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Provisioning"); + domainJoinElement.appendChild(provisioningElement); + + if (configurationSetsItem.getDomainJoin().getProvisioning().getAccountData() != null) { + Element accountDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AccountData"); + accountDataElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getProvisioning().getAccountData())); + provisioningElement.appendChild(accountDataElement); + } + } + } + + if (configurationSetsItem.getStoredCertificateSettings() != null) { + Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + for (StoredCertificateSettings storedCertificateSettingsItem : configurationSetsItem.getStoredCertificateSettings()) { + Element certificateSettingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateSetting"); + storedCertificateSettingsSequenceElement.appendChild(certificateSettingElement); + + Element storeLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreLocation"); + storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine")); + certificateSettingElement.appendChild(storeLocationElement); + + Element storeNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreName"); + storeNameElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getStoreName())); + certificateSettingElement.appendChild(storeNameElement); + + Element thumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + thumbprintElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getThumbprint())); + certificateSettingElement.appendChild(thumbprintElement); + } + configurationSetElement.appendChild(storedCertificateSettingsSequenceElement); + } + + if (configurationSetsItem.getWindowsRemoteManagement() != null) { + Element winRMElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WinRM"); + configurationSetElement.appendChild(winRMElement); + + if (configurationSetsItem.getWindowsRemoteManagement().getListeners() != null) { + Element listenersSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listeners"); + for (WindowsRemoteManagementListener listenersItem : configurationSetsItem.getWindowsRemoteManagement().getListeners()) { + Element listenerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listener"); + listenersSequenceElement.appendChild(listenerElement); + + if (listenersItem.getCertificateThumbprint() != null) { + Element certificateThumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + certificateThumbprintElement.appendChild(requestDoc.createTextNode(listenersItem.getCertificateThumbprint())); + listenerElement.appendChild(certificateThumbprintElement); + } + + Element protocolElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement3.appendChild(requestDoc.createTextNode(listenersItem.getListenerType().toString())); + listenerElement.appendChild(protocolElement3); + } + winRMElement.appendChild(listenersSequenceElement); + } + } + + if (configurationSetsItem.getAdminUserName() != null) { + Element adminUsernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminUsername"); + adminUsernameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminUserName())); + configurationSetElement.appendChild(adminUsernameElement); + } + + if (configurationSetsItem.getHostName() != null) { + Element hostNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostName"); + hostNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getHostName())); + configurationSetElement.appendChild(hostNameElement); + } + + if (configurationSetsItem.getUserName() != null) { + Element userNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserName"); + userNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserName())); + configurationSetElement.appendChild(userNameElement); + } + + if (configurationSetsItem.getUserPassword() != null) { + Element userPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserPassword"); + userPasswordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserPassword())); + configurationSetElement.appendChild(userPasswordElement); + } + + if (configurationSetsItem.isDisableSshPasswordAuthentication() != null) { + Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isDisableSshPasswordAuthentication()).toLowerCase())); + configurationSetElement.appendChild(disableSshPasswordAuthenticationElement); + } + + if (configurationSetsItem.getSshSettings() != null) { + Element sSHElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SSH"); + configurationSetElement.appendChild(sSHElement); + + if (configurationSetsItem.getSshSettings().getPublicKeys() != null) { + Element publicKeysSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKeys"); + for (SshSettingPublicKey publicKeysItem : configurationSetsItem.getSshSettings().getPublicKeys()) { + Element publicKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKey"); + publicKeysSequenceElement.appendChild(publicKeyElement); + + Element fingerprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement.appendChild(requestDoc.createTextNode(publicKeysItem.getFingerprint())); + publicKeyElement.appendChild(fingerprintElement); + + Element pathElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement2.appendChild(requestDoc.createTextNode(publicKeysItem.getPath())); + publicKeyElement.appendChild(pathElement2); + } + sSHElement.appendChild(publicKeysSequenceElement); + } + + if (configurationSetsItem.getSshSettings().getKeyPairs() != null) { + Element keyPairsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPairs"); + for (SshSettingKeyPair keyPairsItem : configurationSetsItem.getSshSettings().getKeyPairs()) { + Element keyPairElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPair"); + keyPairsSequenceElement.appendChild(keyPairElement); + + Element fingerprintElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement2.appendChild(requestDoc.createTextNode(keyPairsItem.getFingerprint())); + keyPairElement.appendChild(fingerprintElement2); + + Element pathElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement3.appendChild(requestDoc.createTextNode(keyPairsItem.getPath())); + keyPairElement.appendChild(pathElement3); + } + sSHElement.appendChild(keyPairsSequenceElement); + } + } + + if (configurationSetsItem.getCustomData() != null) { + Element customDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CustomData"); + customDataElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getCustomData())); + configurationSetElement.appendChild(customDataElement); + } + } + roleElement.appendChild(configurationSetsSequenceElement); + } + + if (roleListItem.getResourceExtensionReferences() != null) { + Element resourceExtensionReferencesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences"); + for (ResourceExtensionReference resourceExtensionReferencesItem : roleListItem.getResourceExtensionReferences()) { + Element resourceExtensionReferenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference"); + resourceExtensionReferencesSequenceElement.appendChild(resourceExtensionReferenceElement); + + if (resourceExtensionReferencesItem.getReferenceName() != null) { + Element referenceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ReferenceName"); + referenceNameElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getReferenceName())); + resourceExtensionReferenceElement.appendChild(referenceNameElement); + } + + if (resourceExtensionReferencesItem.getPublisher() != null) { + Element publisherElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Publisher"); + publisherElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getPublisher())); + resourceExtensionReferenceElement.appendChild(publisherElement); + } + + if (resourceExtensionReferencesItem.getName() != null) { + Element nameElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement3.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getName())); + resourceExtensionReferenceElement.appendChild(nameElement3); + } + + if (resourceExtensionReferencesItem.getVersion() != null) { + Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version"); + versionElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getVersion())); + resourceExtensionReferenceElement.appendChild(versionElement); + } + + if (resourceExtensionReferencesItem.getResourceExtensionParameterValues() != null) { + Element resourceExtensionParameterValuesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValues"); + for (ResourceExtensionParameterValue resourceExtensionParameterValuesItem : resourceExtensionReferencesItem.getResourceExtensionParameterValues()) { + Element resourceExtensionParameterValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue"); + resourceExtensionParameterValuesSequenceElement.appendChild(resourceExtensionParameterValueElement); + + if (resourceExtensionParameterValuesItem.getKey() != null) { + Element keyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Key"); + keyElement.appendChild(requestDoc.createTextNode(resourceExtensionParameterValuesItem.getKey())); + resourceExtensionParameterValueElement.appendChild(keyElement); + } + + if (resourceExtensionParameterValuesItem.getValue() != null) { + Element valueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + valueElement.appendChild(requestDoc.createTextNode(Base64.encode(resourceExtensionParameterValuesItem.getValue().getBytes()))); + resourceExtensionParameterValueElement.appendChild(valueElement); + } + + if (resourceExtensionParameterValuesItem.getType() != null) { + Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); + typeElement.appendChild(requestDoc.createTextNode(resourceExtensionParameterValuesItem.getType())); + resourceExtensionParameterValueElement.appendChild(typeElement); + } + } + resourceExtensionReferenceElement.appendChild(resourceExtensionParameterValuesSequenceElement); + } + + if (resourceExtensionReferencesItem.getState() != null) { + Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State"); + stateElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getState())); + resourceExtensionReferenceElement.appendChild(stateElement); + } + } + roleElement.appendChild(resourceExtensionReferencesSequenceElement); + } + + if (roleListItem.getVMImageName() != null) { + Element vMImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "VMImageName"); + vMImageNameElement.appendChild(requestDoc.createTextNode(roleListItem.getVMImageName())); + roleElement.appendChild(vMImageNameElement); + } + + if (roleListItem.getAvailabilitySetName() != null) { + Element availabilitySetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AvailabilitySetName"); + availabilitySetNameElement.appendChild(requestDoc.createTextNode(roleListItem.getAvailabilitySetName())); + roleElement.appendChild(availabilitySetNameElement); + } + + if (roleListItem.getDataVirtualHardDisks() != null) { + Element dataVirtualHardDisksSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks"); + for (DataVirtualHardDisk dataVirtualHardDisksItem : roleListItem.getDataVirtualHardDisks()) { + Element dataVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk"); + dataVirtualHardDisksSequenceElement.appendChild(dataVirtualHardDiskElement); + + if (dataVirtualHardDisksItem.getHostCaching() != null) { + Element hostCachingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getHostCaching().toString())); + dataVirtualHardDiskElement.appendChild(hostCachingElement); + } + + if (dataVirtualHardDisksItem.getLabel() != null) { + Element diskLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getLabel())); + dataVirtualHardDiskElement.appendChild(diskLabelElement); + } + + if (dataVirtualHardDisksItem.getName() != null) { + Element diskNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getName())); + dataVirtualHardDiskElement.appendChild(diskNameElement); + } + + if (dataVirtualHardDisksItem.getLogicalUnitNumber() != null) { + Element lunElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Lun"); + lunElement.appendChild(requestDoc.createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalUnitNumber()))); + dataVirtualHardDiskElement.appendChild(lunElement); + } + + if (dataVirtualHardDisksItem.getLogicalDiskSizeInGB() != null) { + Element logicalDiskSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalDiskSizeInGB()))); + dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement); + } + + if (dataVirtualHardDisksItem.getMediaLink() != null) { + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getMediaLink().toString())); + dataVirtualHardDiskElement.appendChild(mediaLinkElement); + } + + if (dataVirtualHardDisksItem.getSourceMediaLink() != null) { + Element sourceMediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + sourceMediaLinkElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getSourceMediaLink().toString())); + dataVirtualHardDiskElement.appendChild(sourceMediaLinkElement); + } + } + roleElement.appendChild(dataVirtualHardDisksSequenceElement); + } + + if (roleListItem.getLabel() != null) { + Element labelElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement2.appendChild(requestDoc.createTextNode(roleListItem.getLabel())); + roleElement.appendChild(labelElement2); + } + + if (roleListItem.getOSVirtualHardDisk() != null) { + Element oSVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk"); + roleElement.appendChild(oSVirtualHardDiskElement); + + if (roleListItem.getOSVirtualHardDisk().getHostCaching() != null) { + Element hostCachingElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement2.appendChild(requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getHostCaching().toString())); + oSVirtualHardDiskElement.appendChild(hostCachingElement2); + } + + if (roleListItem.getOSVirtualHardDisk().getLabel() != null) { + Element diskLabelElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement2.appendChild(requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getLabel())); + oSVirtualHardDiskElement.appendChild(diskLabelElement2); + } + + if (roleListItem.getOSVirtualHardDisk().getName() != null) { + Element diskNameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement2.appendChild(requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getName())); + oSVirtualHardDiskElement.appendChild(diskNameElement2); + } + + if (roleListItem.getOSVirtualHardDisk().getMediaLink() != null) { + Element mediaLinkElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement2.appendChild(requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getMediaLink().toString())); + oSVirtualHardDiskElement.appendChild(mediaLinkElement2); + } + + if (roleListItem.getOSVirtualHardDisk().getSourceImageName() != null) { + Element sourceImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceImageName"); + sourceImageNameElement.appendChild(requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getSourceImageName())); + oSVirtualHardDiskElement.appendChild(sourceImageNameElement); + } + + if (roleListItem.getOSVirtualHardDisk().getOperatingSystem() != null) { + Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS"); + osElement.appendChild(requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getOperatingSystem())); + oSVirtualHardDiskElement.appendChild(osElement); + } + } + + if (roleListItem.getRoleSize() != null) { + Element roleSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleSize"); + roleSizeElement.appendChild(requestDoc.createTextNode(roleListItem.getRoleSize())); + roleElement.appendChild(roleSizeElement); + } + + if (roleListItem.isProvisionGuestAgent() != null) { + Element provisionGuestAgentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent"); + provisionGuestAgentElement.appendChild(requestDoc.createTextNode(Boolean.toString(roleListItem.isProvisionGuestAgent()).toLowerCase())); + roleElement.appendChild(provisionGuestAgentElement); + } + + if (roleListItem.getDefaultWinRmCertificateThumbprint() != null) { + Element defaultWinRmCertificateThumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DefaultWinRmCertificateThumbprint"); + defaultWinRmCertificateThumbprintElement.appendChild(requestDoc.createTextNode(roleListItem.getDefaultWinRmCertificateThumbprint())); + roleElement.appendChild(defaultWinRmCertificateThumbprintElement); + } + } + deploymentElement.appendChild(roleListSequenceElement); + + if (parameters.getVirtualNetworkName() != null) { + Element virtualNetworkNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "VirtualNetworkName"); + virtualNetworkNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualNetworkName())); + deploymentElement.appendChild(virtualNetworkNameElement); + } + + if (parameters.getDnsSettings() != null) { + Element dnsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Dns"); + deploymentElement.appendChild(dnsElement); + + if (parameters.getDnsSettings().getDnsServers() != null) { + Element dnsServersSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DnsServers"); + for (DnsServer dnsServersItem : parameters.getDnsSettings().getDnsServers()) { + Element dnsServerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DnsServer"); + dnsServersSequenceElement.appendChild(dnsServerElement); + + if (dnsServersItem.getName() != null) { + Element nameElement4 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement4.appendChild(requestDoc.createTextNode(dnsServersItem.getName())); + dnsServerElement.appendChild(nameElement4); + } + + if (dnsServersItem.getAddress() != null) { + Element addressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Address"); + addressElement.appendChild(requestDoc.createTextNode(dnsServersItem.getAddress().getHostAddress())); + dnsServerElement.appendChild(addressElement); + } + } + dnsElement.appendChild(dnsServersSequenceElement); + } + } + + if (parameters.getReservedIPName() != null) { + Element reservedIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIPName"); + reservedIPNameElement.appendChild(requestDoc.createTextNode(parameters.getReservedIPName())); + deploymentElement.appendChild(reservedIPNameElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Deleting Role operation deletes the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeleting(serviceName, deploymentName, virtualMachineName, deleteFromStorage); + } + }); + } + + /** + * The Begin Deleting Role operation deletes the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeleting(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles/" + virtualMachineName.trim() + "?"; + if (deleteFromStorage == true) { + url = url + "comp=" + "media"; + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Restarting role operation restarts the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginRestartingAsync(final String serviceName, final String deploymentName, final String virtualMachineName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginRestarting(serviceName, deploymentName, virtualMachineName); + } + }); + } + + /** + * The Begin Restarting role operation restarts the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginRestarting(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + CloudTracing.enter(invocationId, this, "beginRestartingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + virtualMachineName.trim() + "/Operations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = "RestartRoleOperation"; + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown vm operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginShutdownAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineShutdownParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginShutdown(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown vm operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginShutdown(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginShutdownAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + virtualMachineName.trim() + "/Operations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element shutdownRoleOperationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ShutdownRoleOperation"); + requestDoc.appendChild(shutdownRoleOperationElement); + + Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OperationType"); + operationTypeElement.appendChild(requestDoc.createTextNode("ShutdownRoleOperation")); + shutdownRoleOperationElement.appendChild(operationTypeElement); + + Element postShutdownActionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PostShutdownAction"); + postShutdownActionElement.appendChild(requestDoc.createTextNode(parameters.getPostShutdownAction().toString())); + shutdownRoleOperationElement.appendChild(postShutdownActionElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Shutting Down Roles operation stops the specified set of + * virtual machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Shutting Down + * Roles operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginShuttingDownRolesAsync(final String serviceName, final String deploymentName, final VirtualMachineShutdownRolesParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginShuttingDownRoles(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Shutting Down Roles operation stops the specified set of + * virtual machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Shutting Down + * Roles operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginShuttingDownRoles(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginShuttingDownRolesAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/Roles/Operations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element shutdownRolesOperationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ShutdownRolesOperation"); + requestDoc.appendChild(shutdownRolesOperationElement); + + Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OperationType"); + operationTypeElement.appendChild(requestDoc.createTextNode("ShutdownRolesOperation")); + shutdownRolesOperationElement.appendChild(operationTypeElement); + + if (parameters.getRoles() != null) { + Element rolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Roles"); + for (String rolesItem : parameters.getRoles()) { + Element rolesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + rolesItemElement.appendChild(requestDoc.createTextNode(rolesItem)); + rolesSequenceElement.appendChild(rolesItemElement); + } + shutdownRolesOperationElement.appendChild(rolesSequenceElement); + } + + if (parameters.getPostShutdownAction() != null) { + Element postShutdownActionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PostShutdownAction"); + postShutdownActionElement.appendChild(requestDoc.createTextNode(parameters.getPostShutdownAction().toString())); + shutdownRolesOperationElement.appendChild(postShutdownActionElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Starting Role operation starts the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginStartingAsync(final String serviceName, final String deploymentName, final String virtualMachineName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginStarting(serviceName, deploymentName, virtualMachineName); + } + }); + } + + /** + * The Begin Starting Role operation starts the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginStarting(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + CloudTracing.enter(invocationId, this, "beginStartingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + virtualMachineName.trim() + "/Operations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = "StartRoleOperation"; + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Starting Roles operation starts the specified set of virtual + * machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Starting + * Roles operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginStartingRolesAsync(final String serviceName, final String deploymentName, final VirtualMachineStartRolesParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginStartingRoles(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Starting Roles operation starts the specified set of virtual + * machines. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Begin Starting + * Roles operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginStartingRoles(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginStartingRolesAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/Roles/Operations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element startRolesOperationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StartRolesOperation"); + requestDoc.appendChild(startRolesOperationElement); + + Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OperationType"); + operationTypeElement.appendChild(requestDoc.createTextNode("StartRolesOperation")); + startRolesOperationElement.appendChild(operationTypeElement); + + if (parameters.getRoles() != null) { + Element rolesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Roles"); + for (String rolesItem : parameters.getRoles()) { + Element rolesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + rolesItemElement.appendChild(requestDoc.createTextNode(rolesItem)); + rolesSequenceElement.appendChild(rolesItemElement); + } + startRolesOperationElement.appendChild(rolesSequenceElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Updating Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Begin Updating + * Virtual Machine operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginUpdatingAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginUpdating(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * The Begin Updating Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Begin Updating + * Virtual Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginUpdating(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfigurationSets() != null) { + for (ConfigurationSet configurationSetsParameterItem : parameters.getConfigurationSets()) { + if (configurationSetsParameterItem.getDomainJoin() != null) { + if (configurationSetsParameterItem.getDomainJoin().getCredentials() != null) { + if (configurationSetsParameterItem.getDomainJoin().getCredentials().getPassword() == null) { + throw new NullPointerException("parameters.ConfigurationSets.DomainJoin.Credentials.Password"); + } + if (configurationSetsParameterItem.getDomainJoin().getCredentials().getUserName() == null) { + throw new NullPointerException("parameters.ConfigurationSets.DomainJoin.Credentials.UserName"); + } + } + } + if (configurationSetsParameterItem.getHostName() != null && configurationSetsParameterItem.getHostName().length() < 1) { + throw new IllegalArgumentException("parameters.ConfigurationSets.HostName"); + } + if (configurationSetsParameterItem.getHostName() != null && configurationSetsParameterItem.getHostName().length() > 64) { + throw new IllegalArgumentException("parameters.ConfigurationSets.HostName"); + } + if (configurationSetsParameterItem.getSshSettings() != null) { + if (configurationSetsParameterItem.getSshSettings().getKeyPairs() != null) { + for (SshSettingKeyPair keyPairsParameterItem : configurationSetsParameterItem.getSshSettings().getKeyPairs()) { + if (keyPairsParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.KeyPairs.Fingerprint"); + } + if (keyPairsParameterItem.getPath() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.KeyPairs.Path"); + } + } + } + if (configurationSetsParameterItem.getSshSettings().getPublicKeys() != null) { + for (SshSettingPublicKey publicKeysParameterItem : configurationSetsParameterItem.getSshSettings().getPublicKeys()) { + if (publicKeysParameterItem.getFingerprint() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.PublicKeys.Fingerprint"); + } + if (publicKeysParameterItem.getPath() == null) { + throw new NullPointerException("parameters.ConfigurationSets.SshSettings.PublicKeys.Path"); + } + } + } + } + if (configurationSetsParameterItem.getStoredCertificateSettings() != null) { + for (StoredCertificateSettings storedCertificateSettingsParameterItem : configurationSetsParameterItem.getStoredCertificateSettings()) { + if (storedCertificateSettingsParameterItem.getStoreName() == null) { + throw new NullPointerException("parameters.ConfigurationSets.StoredCertificateSettings.StoreName"); + } + if (storedCertificateSettingsParameterItem.getThumbprint() == null) { + throw new NullPointerException("parameters.ConfigurationSets.StoredCertificateSettings.Thumbprint"); + } + } + } + if (configurationSetsParameterItem.getUserName() != null && configurationSetsParameterItem.getUserName().length() < 1) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserName"); + } + if (configurationSetsParameterItem.getUserName() != null && configurationSetsParameterItem.getUserName().length() > 32) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserName"); + } + if (configurationSetsParameterItem.getUserPassword() != null && configurationSetsParameterItem.getUserPassword().length() < 6 && (configurationSetsParameterItem.isDisableSshPasswordAuthentication() == false || configurationSetsParameterItem.getUserPassword().length() != 0)) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword"); + } + if (configurationSetsParameterItem.getUserPassword() != null && configurationSetsParameterItem.getUserPassword().length() > 72) { + throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword"); + } + } + } + if (parameters.getOSVirtualHardDisk() == null) { + throw new NullPointerException("parameters.OSVirtualHardDisk"); + } + if (parameters.getRoleName() == null) { + throw new NullPointerException("parameters.RoleName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginUpdatingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles/" + virtualMachineName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element persistentVMRoleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PersistentVMRole"); + requestDoc.appendChild(persistentVMRoleElement); + + Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName"); + roleNameElement.appendChild(requestDoc.createTextNode(parameters.getRoleName())); + persistentVMRoleElement.appendChild(roleNameElement); + + Element roleTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleType"); + roleTypeElement.appendChild(requestDoc.createTextNode("PersistentVMRole")); + persistentVMRoleElement.appendChild(roleTypeElement); + + if (parameters.getConfigurationSets() != null) { + Element configurationSetsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSets"); + for (ConfigurationSet configurationSetsItem : parameters.getConfigurationSets()) { + Element configurationSetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSet"); + configurationSetsSequenceElement.appendChild(configurationSetElement); + + if (configurationSetsItem.getConfigurationSetType() != null) { + Element configurationSetTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + configurationSetTypeElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getConfigurationSetType())); + configurationSetElement.appendChild(configurationSetTypeElement); + } + + if (configurationSetsItem.getInputEndpoints() != null) { + Element inputEndpointsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + for (InputEndpoint inputEndpointsItem : configurationSetsItem.getInputEndpoints()) { + Element inputEndpointElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint"); + inputEndpointsSequenceElement.appendChild(inputEndpointElement); + + if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) { + Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + loadBalancedEndpointSetNameElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancedEndpointSetName())); + inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement); + } + + if (inputEndpointsItem.getLocalPort() != null) { + Element localPortElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort"); + localPortElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLocalPort()))); + inputEndpointElement.appendChild(localPortElement); + } + + if (inputEndpointsItem.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getName())); + inputEndpointElement.appendChild(nameElement); + } + + if (inputEndpointsItem.getPort() != null) { + Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort()))); + inputEndpointElement.appendChild(portElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe() != null) { + Element loadBalancerProbeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + inputEndpointElement.appendChild(loadBalancerProbeElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) { + Element pathElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerProbe().getPath())); + loadBalancerProbeElement.appendChild(pathElement); + } + + Element portElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement2.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getPort()))); + loadBalancerProbeElement.appendChild(portElement2); + + Element protocolElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement.appendChild(requestDoc.createTextNode(ComputeManagementClientImpl.loadBalancerProbeTransportProtocolToString(inputEndpointsItem.getLoadBalancerProbe().getProtocol()))); + loadBalancerProbeElement.appendChild(protocolElement); + + if (inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) { + Element intervalInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + intervalInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds()))); + loadBalancerProbeElement.appendChild(intervalInSecondsElement); + } + + if (inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) { + Element timeoutInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + timeoutInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds()))); + loadBalancerProbeElement.appendChild(timeoutInSecondsElement); + } + } + + if (inputEndpointsItem.getProtocol() != null) { + Element protocolElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement2.appendChild(requestDoc.createTextNode(inputEndpointsItem.getProtocol())); + inputEndpointElement.appendChild(protocolElement2); + } + + if (inputEndpointsItem.getVirtualIPAddress() != null) { + Element vipElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Vip"); + vipElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getVirtualIPAddress().getHostAddress())); + inputEndpointElement.appendChild(vipElement); + } + + if (inputEndpointsItem.isEnableDirectServerReturn() != null) { + Element enableDirectServerReturnElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(Boolean.toString(inputEndpointsItem.isEnableDirectServerReturn()).toLowerCase())); + inputEndpointElement.appendChild(enableDirectServerReturnElement); + } + + if (inputEndpointsItem.getEndpointAcl() != null) { + Element endpointAclElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + inputEndpointElement.appendChild(endpointAclElement); + + if (inputEndpointsItem.getEndpointAcl().getRules() != null) { + Element rulesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rules"); + for (AccessControlListRule rulesItem : inputEndpointsItem.getEndpointAcl().getRules()) { + Element ruleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rule"); + rulesSequenceElement.appendChild(ruleElement); + + if (rulesItem.getOrder() != null) { + Element orderElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Order"); + orderElement.appendChild(requestDoc.createTextNode(Integer.toString(rulesItem.getOrder()))); + ruleElement.appendChild(orderElement); + } + + if (rulesItem.getAction() != null) { + Element actionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Action"); + actionElement.appendChild(requestDoc.createTextNode(rulesItem.getAction())); + ruleElement.appendChild(actionElement); + } + + if (rulesItem.getRemoteSubnet() != null) { + Element remoteSubnetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + remoteSubnetElement.appendChild(requestDoc.createTextNode(rulesItem.getRemoteSubnet())); + ruleElement.appendChild(remoteSubnetElement); + } + + if (rulesItem.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(rulesItem.getDescription())); + ruleElement.appendChild(descriptionElement); + } + } + endpointAclElement.appendChild(rulesSequenceElement); + } + } + } + configurationSetElement.appendChild(inputEndpointsSequenceElement); + } + + if (configurationSetsItem.getSubnetNames() != null) { + Element subnetNamesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetNames"); + for (String subnetNamesItem : configurationSetsItem.getSubnetNames()) { + Element subnetNamesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName"); + subnetNamesItemElement.appendChild(requestDoc.createTextNode(subnetNamesItem)); + subnetNamesSequenceElement.appendChild(subnetNamesItemElement); + } + configurationSetElement.appendChild(subnetNamesSequenceElement); + } + + if (configurationSetsItem.getStaticVirtualNetworkIPAddress() != null) { + Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getStaticVirtualNetworkIPAddress())); + configurationSetElement.appendChild(staticVirtualNetworkIPAddressElement); + } + + if (configurationSetsItem.getComputerName() != null) { + Element computerNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ComputerName"); + computerNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getComputerName())); + configurationSetElement.appendChild(computerNameElement); + } + + if (configurationSetsItem.getAdminPassword() != null) { + Element adminPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminPassword"); + adminPasswordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminPassword())); + configurationSetElement.appendChild(adminPasswordElement); + } + + if (configurationSetsItem.isResetPasswordOnFirstLogon() != null) { + Element resetPasswordOnFirstLogonElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isResetPasswordOnFirstLogon()).toLowerCase())); + configurationSetElement.appendChild(resetPasswordOnFirstLogonElement); + } + + if (configurationSetsItem.isEnableAutomaticUpdates() != null) { + Element enableAutomaticUpdatesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isEnableAutomaticUpdates()).toLowerCase())); + configurationSetElement.appendChild(enableAutomaticUpdatesElement); + } + + if (configurationSetsItem.getTimeZone() != null) { + Element timeZoneElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeZone"); + timeZoneElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getTimeZone())); + configurationSetElement.appendChild(timeZoneElement); + } + + if (configurationSetsItem.getDomainJoin() != null) { + Element domainJoinElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DomainJoin"); + configurationSetElement.appendChild(domainJoinElement); + + if (configurationSetsItem.getDomainJoin().getCredentials() != null) { + Element credentialsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Credentials"); + domainJoinElement.appendChild(credentialsElement); + + if (configurationSetsItem.getDomainJoin().getCredentials().getDomain() != null) { + Element domainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Domain"); + domainElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getDomain())); + credentialsElement.appendChild(domainElement); + } + + Element usernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Username"); + usernameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getUserName())); + credentialsElement.appendChild(usernameElement); + + Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getCredentials().getPassword())); + credentialsElement.appendChild(passwordElement); + } + + if (configurationSetsItem.getDomainJoin().getDomainToJoin() != null) { + Element joinDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "JoinDomain"); + joinDomainElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getDomainToJoin())); + domainJoinElement.appendChild(joinDomainElement); + } + + if (configurationSetsItem.getDomainJoin().getLdapMachineObjectOU() != null) { + Element machineObjectOUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + machineObjectOUElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getLdapMachineObjectOU())); + domainJoinElement.appendChild(machineObjectOUElement); + } + + if (configurationSetsItem.getDomainJoin().getProvisioning() != null) { + Element provisioningElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Provisioning"); + domainJoinElement.appendChild(provisioningElement); + + if (configurationSetsItem.getDomainJoin().getProvisioning().getAccountData() != null) { + Element accountDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AccountData"); + accountDataElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getDomainJoin().getProvisioning().getAccountData())); + provisioningElement.appendChild(accountDataElement); + } + } + } + + if (configurationSetsItem.getStoredCertificateSettings() != null) { + Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + for (StoredCertificateSettings storedCertificateSettingsItem : configurationSetsItem.getStoredCertificateSettings()) { + Element certificateSettingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateSetting"); + storedCertificateSettingsSequenceElement.appendChild(certificateSettingElement); + + Element storeLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreLocation"); + storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine")); + certificateSettingElement.appendChild(storeLocationElement); + + Element storeNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StoreName"); + storeNameElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getStoreName())); + certificateSettingElement.appendChild(storeNameElement); + + Element thumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + thumbprintElement.appendChild(requestDoc.createTextNode(storedCertificateSettingsItem.getThumbprint())); + certificateSettingElement.appendChild(thumbprintElement); + } + configurationSetElement.appendChild(storedCertificateSettingsSequenceElement); + } + + if (configurationSetsItem.getWindowsRemoteManagement() != null) { + Element winRMElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WinRM"); + configurationSetElement.appendChild(winRMElement); + + if (configurationSetsItem.getWindowsRemoteManagement().getListeners() != null) { + Element listenersSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listeners"); + for (WindowsRemoteManagementListener listenersItem : configurationSetsItem.getWindowsRemoteManagement().getListeners()) { + Element listenerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Listener"); + listenersSequenceElement.appendChild(listenerElement); + + if (listenersItem.getCertificateThumbprint() != null) { + Element certificateThumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + certificateThumbprintElement.appendChild(requestDoc.createTextNode(listenersItem.getCertificateThumbprint())); + listenerElement.appendChild(certificateThumbprintElement); + } + + Element protocolElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement3.appendChild(requestDoc.createTextNode(listenersItem.getListenerType().toString())); + listenerElement.appendChild(protocolElement3); + } + winRMElement.appendChild(listenersSequenceElement); + } + } + + if (configurationSetsItem.getAdminUserName() != null) { + Element adminUsernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminUsername"); + adminUsernameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminUserName())); + configurationSetElement.appendChild(adminUsernameElement); + } + + if (configurationSetsItem.getHostName() != null) { + Element hostNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostName"); + hostNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getHostName())); + configurationSetElement.appendChild(hostNameElement); + } + + if (configurationSetsItem.getUserName() != null) { + Element userNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserName"); + userNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserName())); + configurationSetElement.appendChild(userNameElement); + } + + if (configurationSetsItem.getUserPassword() != null) { + Element userPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UserPassword"); + userPasswordElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserPassword())); + configurationSetElement.appendChild(userPasswordElement); + } + + if (configurationSetsItem.isDisableSshPasswordAuthentication() != null) { + Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(Boolean.toString(configurationSetsItem.isDisableSshPasswordAuthentication()).toLowerCase())); + configurationSetElement.appendChild(disableSshPasswordAuthenticationElement); + } + + if (configurationSetsItem.getSshSettings() != null) { + Element sSHElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SSH"); + configurationSetElement.appendChild(sSHElement); + + if (configurationSetsItem.getSshSettings().getPublicKeys() != null) { + Element publicKeysSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKeys"); + for (SshSettingPublicKey publicKeysItem : configurationSetsItem.getSshSettings().getPublicKeys()) { + Element publicKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKey"); + publicKeysSequenceElement.appendChild(publicKeyElement); + + Element fingerprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement.appendChild(requestDoc.createTextNode(publicKeysItem.getFingerprint())); + publicKeyElement.appendChild(fingerprintElement); + + Element pathElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement2.appendChild(requestDoc.createTextNode(publicKeysItem.getPath())); + publicKeyElement.appendChild(pathElement2); + } + sSHElement.appendChild(publicKeysSequenceElement); + } + + if (configurationSetsItem.getSshSettings().getKeyPairs() != null) { + Element keyPairsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPairs"); + for (SshSettingKeyPair keyPairsItem : configurationSetsItem.getSshSettings().getKeyPairs()) { + Element keyPairElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPair"); + keyPairsSequenceElement.appendChild(keyPairElement); + + Element fingerprintElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint"); + fingerprintElement2.appendChild(requestDoc.createTextNode(keyPairsItem.getFingerprint())); + keyPairElement.appendChild(fingerprintElement2); + + Element pathElement3 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement3.appendChild(requestDoc.createTextNode(keyPairsItem.getPath())); + keyPairElement.appendChild(pathElement3); + } + sSHElement.appendChild(keyPairsSequenceElement); + } + } + + if (configurationSetsItem.getCustomData() != null) { + Element customDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CustomData"); + customDataElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getCustomData())); + configurationSetElement.appendChild(customDataElement); + } + } + persistentVMRoleElement.appendChild(configurationSetsSequenceElement); + } + + if (parameters.getAvailabilitySetName() != null) { + Element availabilitySetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AvailabilitySetName"); + availabilitySetNameElement.appendChild(requestDoc.createTextNode(parameters.getAvailabilitySetName())); + persistentVMRoleElement.appendChild(availabilitySetNameElement); + } + + if (parameters.getResourceExtensionReferences() != null) { + Element resourceExtensionReferencesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences"); + for (ResourceExtensionReference resourceExtensionReferencesItem : parameters.getResourceExtensionReferences()) { + Element resourceExtensionReferenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference"); + resourceExtensionReferencesSequenceElement.appendChild(resourceExtensionReferenceElement); + + if (resourceExtensionReferencesItem.getReferenceName() != null) { + Element referenceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ReferenceName"); + referenceNameElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getReferenceName())); + resourceExtensionReferenceElement.appendChild(referenceNameElement); + } + + if (resourceExtensionReferencesItem.getPublisher() != null) { + Element publisherElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Publisher"); + publisherElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getPublisher())); + resourceExtensionReferenceElement.appendChild(publisherElement); + } + + if (resourceExtensionReferencesItem.getName() != null) { + Element nameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement2.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getName())); + resourceExtensionReferenceElement.appendChild(nameElement2); + } + + if (resourceExtensionReferencesItem.getVersion() != null) { + Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version"); + versionElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getVersion())); + resourceExtensionReferenceElement.appendChild(versionElement); + } + + if (resourceExtensionReferencesItem.getResourceExtensionParameterValues() != null) { + Element resourceExtensionParameterValuesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValues"); + for (ResourceExtensionParameterValue resourceExtensionParameterValuesItem : resourceExtensionReferencesItem.getResourceExtensionParameterValues()) { + Element resourceExtensionParameterValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceExtensionParameterValue"); + resourceExtensionParameterValuesSequenceElement.appendChild(resourceExtensionParameterValueElement); + + if (resourceExtensionParameterValuesItem.getKey() != null) { + Element keyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Key"); + keyElement.appendChild(requestDoc.createTextNode(resourceExtensionParameterValuesItem.getKey())); + resourceExtensionParameterValueElement.appendChild(keyElement); + } + + if (resourceExtensionParameterValuesItem.getValue() != null) { + Element valueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + valueElement.appendChild(requestDoc.createTextNode(Base64.encode(resourceExtensionParameterValuesItem.getValue().getBytes()))); + resourceExtensionParameterValueElement.appendChild(valueElement); + } + + if (resourceExtensionParameterValuesItem.getType() != null) { + Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); + typeElement.appendChild(requestDoc.createTextNode(resourceExtensionParameterValuesItem.getType())); + resourceExtensionParameterValueElement.appendChild(typeElement); + } + } + resourceExtensionReferenceElement.appendChild(resourceExtensionParameterValuesSequenceElement); + } + + if (resourceExtensionReferencesItem.getState() != null) { + Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State"); + stateElement.appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getState())); + resourceExtensionReferenceElement.appendChild(stateElement); + } + } + persistentVMRoleElement.appendChild(resourceExtensionReferencesSequenceElement); + } + + if (parameters.getDataVirtualHardDisks() != null) { + Element dataVirtualHardDisksSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks"); + for (DataVirtualHardDisk dataVirtualHardDisksItem : parameters.getDataVirtualHardDisks()) { + Element dataVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk"); + dataVirtualHardDisksSequenceElement.appendChild(dataVirtualHardDiskElement); + + if (dataVirtualHardDisksItem.getHostCaching() != null) { + Element hostCachingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getHostCaching().toString())); + dataVirtualHardDiskElement.appendChild(hostCachingElement); + } + + if (dataVirtualHardDisksItem.getLabel() != null) { + Element diskLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getLabel())); + dataVirtualHardDiskElement.appendChild(diskLabelElement); + } + + if (dataVirtualHardDisksItem.getName() != null) { + Element diskNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getName())); + dataVirtualHardDiskElement.appendChild(diskNameElement); + } + + if (dataVirtualHardDisksItem.getLogicalUnitNumber() != null) { + Element lunElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Lun"); + lunElement.appendChild(requestDoc.createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalUnitNumber()))); + dataVirtualHardDiskElement.appendChild(lunElement); + } + + if (dataVirtualHardDisksItem.getLogicalDiskSizeInGB() != null) { + Element logicalDiskSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalDiskSizeInGB()))); + dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement); + } + + if (dataVirtualHardDisksItem.getMediaLink() != null) { + Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getMediaLink().toString())); + dataVirtualHardDiskElement.appendChild(mediaLinkElement); + } + + if (dataVirtualHardDisksItem.getSourceMediaLink() != null) { + Element sourceMediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + sourceMediaLinkElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getSourceMediaLink().toString())); + dataVirtualHardDiskElement.appendChild(sourceMediaLinkElement); + } + } + persistentVMRoleElement.appendChild(dataVirtualHardDisksSequenceElement); + } + + Element oSVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk"); + persistentVMRoleElement.appendChild(oSVirtualHardDiskElement); + + if (parameters.getOSVirtualHardDisk().getHostCaching() != null) { + Element hostCachingElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching"); + hostCachingElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getHostCaching().toString())); + oSVirtualHardDiskElement.appendChild(hostCachingElement2); + } + + if (parameters.getOSVirtualHardDisk().getLabel() != null) { + Element diskLabelElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel"); + diskLabelElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getLabel())); + oSVirtualHardDiskElement.appendChild(diskLabelElement2); + } + + if (parameters.getOSVirtualHardDisk().getName() != null) { + Element diskNameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName"); + diskNameElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getName())); + oSVirtualHardDiskElement.appendChild(diskNameElement2); + } + + if (parameters.getOSVirtualHardDisk().getMediaLink() != null) { + Element mediaLinkElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); + mediaLinkElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getMediaLink().toString())); + oSVirtualHardDiskElement.appendChild(mediaLinkElement2); + } + + if (parameters.getOSVirtualHardDisk().getSourceImageName() != null) { + Element sourceImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceImageName"); + sourceImageNameElement.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getSourceImageName())); + oSVirtualHardDiskElement.appendChild(sourceImageNameElement); + } + + if (parameters.getOSVirtualHardDisk().getOperatingSystem() != null) { + Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS"); + osElement.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getOperatingSystem())); + oSVirtualHardDiskElement.appendChild(osElement); + } + + if (parameters.getRoleSize() != null) { + Element roleSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RoleSize"); + roleSizeElement.appendChild(requestDoc.createTextNode(parameters.getRoleSize())); + persistentVMRoleElement.appendChild(roleSizeElement); + } + + if (parameters.isProvisionGuestAgent() != null) { + Element provisionGuestAgentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent"); + provisionGuestAgentElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isProvisionGuestAgent()).toLowerCase())); + persistentVMRoleElement.appendChild(provisionGuestAgentElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Updating Load Balanced Endpoint Set operation changes the + * specified load-balanced InputEndpoints on all the roles of an + * Infrastructure as a Service deployment. Non-load-balanced endpoints must + * be changed using UpdateRole. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Load Balanced Endpoint Set operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginUpdatingLoadBalancedEndpointSetAsync(final String serviceName, final String deploymentName, final VirtualMachineUpdateLoadBalancedSetParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginUpdatingLoadBalancedEndpointSet(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Begin Updating Load Balanced Endpoint Set operation changes the + * specified load-balanced InputEndpoints on all the roles of an + * Infrastructure as a Service deployment. Non-load-balanced endpoints must + * be changed using UpdateRole. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Begin Updating + * Load Balanced Endpoint Set operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginUpdatingLoadBalancedEndpointSet(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getLoadBalancedEndpoints() != null) { + for (VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint loadBalancedEndpointsParameterItem : parameters.getLoadBalancedEndpoints()) { + if (loadBalancedEndpointsParameterItem.getLoadBalancedEndpointSetName() == null) { + throw new NullPointerException("parameters.LoadBalancedEndpoints.LoadBalancedEndpointSetName"); + } + } + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginUpdatingLoadBalancedEndpointSetAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "?" + "comp=UpdateLbSet"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element loadBalancedEndpointListElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointList"); + requestDoc.appendChild(loadBalancedEndpointListElement); + + if (parameters.getLoadBalancedEndpoints() != null) { + for (VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint loadBalancedEndpointsItem : parameters.getLoadBalancedEndpoints()) { + Element inputEndpointElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint"); + loadBalancedEndpointListElement.appendChild(inputEndpointElement); + + Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + loadBalancedEndpointSetNameElement.appendChild(requestDoc.createTextNode(loadBalancedEndpointsItem.getLoadBalancedEndpointSetName())); + inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement); + + if (loadBalancedEndpointsItem.getLocalPort() != null) { + Element localPortElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort"); + localPortElement.appendChild(requestDoc.createTextNode(Integer.toString(loadBalancedEndpointsItem.getLocalPort()))); + inputEndpointElement.appendChild(localPortElement); + } + + if (loadBalancedEndpointsItem.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(loadBalancedEndpointsItem.getName())); + inputEndpointElement.appendChild(nameElement); + } + + if (loadBalancedEndpointsItem.getPort() != null) { + Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement.appendChild(requestDoc.createTextNode(Integer.toString(loadBalancedEndpointsItem.getPort()))); + inputEndpointElement.appendChild(portElement); + } + + if (loadBalancedEndpointsItem.getLoadBalancerProbe() != null) { + Element loadBalancerProbeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + inputEndpointElement.appendChild(loadBalancerProbeElement); + + if (loadBalancedEndpointsItem.getLoadBalancerProbe().getPath() != null) { + Element pathElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Path"); + pathElement.appendChild(requestDoc.createTextNode(loadBalancedEndpointsItem.getLoadBalancerProbe().getPath())); + loadBalancerProbeElement.appendChild(pathElement); + } + + Element portElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); + portElement2.appendChild(requestDoc.createTextNode(Integer.toString(loadBalancedEndpointsItem.getLoadBalancerProbe().getPort()))); + loadBalancerProbeElement.appendChild(portElement2); + + Element protocolElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement.appendChild(requestDoc.createTextNode(ComputeManagementClientImpl.loadBalancerProbeTransportProtocolToString(loadBalancedEndpointsItem.getLoadBalancerProbe().getProtocol()))); + loadBalancerProbeElement.appendChild(protocolElement); + + if (loadBalancedEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) { + Element intervalInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + intervalInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(loadBalancedEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds()))); + loadBalancerProbeElement.appendChild(intervalInSecondsElement); + } + + if (loadBalancedEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) { + Element timeoutInSecondsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + timeoutInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(loadBalancedEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds()))); + loadBalancerProbeElement.appendChild(timeoutInSecondsElement); + } + } + + if (loadBalancedEndpointsItem.getProtocol() != null) { + Element protocolElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); + protocolElement2.appendChild(requestDoc.createTextNode(loadBalancedEndpointsItem.getProtocol())); + inputEndpointElement.appendChild(protocolElement2); + } + + if (loadBalancedEndpointsItem.getVirtualIPAddress() != null) { + Element vipElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Vip"); + vipElement.appendChild(requestDoc.createTextNode(loadBalancedEndpointsItem.getVirtualIPAddress().getHostAddress())); + inputEndpointElement.appendChild(vipElement); + } + + if (loadBalancedEndpointsItem.isEnableDirectServerReturn() != null) { + Element enableDirectServerReturnElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(Boolean.toString(loadBalancedEndpointsItem.isEnableDirectServerReturn()).toLowerCase())); + inputEndpointElement.appendChild(enableDirectServerReturnElement); + } + + Element endpointAclElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + inputEndpointElement.appendChild(endpointAclElement); + + if (loadBalancedEndpointsItem.getRules() != null) { + Element rulesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rules"); + for (AccessControlListRule rulesItem : loadBalancedEndpointsItem.getRules()) { + Element ruleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Rule"); + rulesSequenceElement.appendChild(ruleElement); + + if (rulesItem.getOrder() != null) { + Element orderElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Order"); + orderElement.appendChild(requestDoc.createTextNode(Integer.toString(rulesItem.getOrder()))); + ruleElement.appendChild(orderElement); + } + + if (rulesItem.getAction() != null) { + Element actionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Action"); + actionElement.appendChild(requestDoc.createTextNode(rulesItem.getAction())); + ruleElement.appendChild(actionElement); + } + + if (rulesItem.getRemoteSubnet() != null) { + Element remoteSubnetElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + remoteSubnetElement.appendChild(requestDoc.createTextNode(rulesItem.getRemoteSubnet())); + ruleElement.appendChild(remoteSubnetElement); + } + + if (rulesItem.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(rulesItem.getDescription())); + ruleElement.appendChild(descriptionElement); + } + } + endpointAclElement.appendChild(rulesSequenceElement); + } + } + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Capture Role operation creates a copy of the operating system virtual + * hard disk (VHD) that is deployed in the virtual machine, saves the VHD + * copy in the same storage location as the operating system VHD, and + * registers the copy as an image in your image gallery. From the captured + * image, you can create additional customized virtual machines. For more + * information about images and disks, see Manage Disks and Images at + * http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For + * more information about capturing images, see How to Capture an Image of + * a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future captureOSImageAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineCaptureOSImageParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return captureOSImage(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * The Capture Role operation creates a copy of the operating system virtual + * hard disk (VHD) that is deployed in the virtual machine, saves the VHD + * copy in the same storage location as the operating system VHD, and + * registers the copy as an image in your image gallery. From the captured + * image, you can create additional customized virtual machines. For more + * information about images and disks, see Manage Disks and Images at + * http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For + * more information about capturing images, see How to Capture an Image of + * a Virtual Machine Running Windows Server 2008 R2 at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/ + * or How to Capture an Image of a Virtual Machine Running Linux at + * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse captureOSImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "captureOSImageAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginCapturingOSImageAsync(serviceName, deploymentName, virtualMachineName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * Capture role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future captureVMImageAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineCaptureVMImageParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return captureVMImage(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * Capture role as VM template. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @param parameters Required. Parameters supplied to the Capture Virtual + * Machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse captureVMImage(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "captureVMImageAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginCapturingVMImageAsync(serviceName, deploymentName, virtualMachineName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Create Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future createAsync(final String serviceName, final String deploymentName, final VirtualMachineCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return create(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Create Role operation adds a virtual machine to an existing + * deployment. You can refer to the OSDisk in the Add Role operation in the + * following ways: Platform/User Image - Set the SourceImageName to a + * platform or user image. You can optionally specify the DiskName and + * MediaLink values as part the operation to control the name and location + * of target disk. When DiskName and MediaLink are specified in this mode, + * they must not already exist in the system, otherwise a conflict fault is + * returned; UserDisk - Set DiskName to a user supplied image in image + * repository. SourceImageName must be set to NULL. All other properties + * are ignored; or Blob in a Storage Account - Set MediaLink to a blob + * containing the image. SourceImageName and DiskName are set to NULL. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse create(String serviceName, String deploymentName, VirtualMachineCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginCreatingAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Create Virtual Machine Deployment operation provisions a virtual + * machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Deployment operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future createDeploymentAsync(final String serviceName, final VirtualMachineCreateDeploymentParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return createDeployment(serviceName, parameters); + } + }); + } + + /** + * The Create Virtual Machine Deployment operation provisions a virtual + * machine based on the supplied configuration. When you create a + * deployment of a virtual machine, you should make sure that the cloud + * service and the disk or image that you use are located in the same + * region. For example, if the cloud service was created in the West US + * region, the disk or image that you use should also be located in a + * storage account in the West US region. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param parameters Required. Parameters supplied to the Create Virtual + * Machine Deployment operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse createDeployment(String serviceName, VirtualMachineCreateDeploymentParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createDeploymentAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginCreatingDeploymentAsync(serviceName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Role operation deletes the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return delete(serviceName, deploymentName, virtualMachineName, deleteFromStorage); + } + }); + } + + /** + * The Delete Role operation deletes the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob(s) for + * the virtual machine should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse delete(String serviceName, String deploymentName, String virtualMachineName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginDeletingAsync(serviceName, deploymentName, virtualMachineName, deleteFromStorage).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Get Role operation retrieves information about the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @return The Get Virtual Machine operation response. + */ + @Override + public Future getAsync(final String serviceName, final String deploymentName, final String virtualMachineName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineGetResponse call() throws Exception { + return get(serviceName, deploymentName, virtualMachineName); + } + }); + } + + /** + * The Get Role operation retrieves information about the specified virtual + * machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Virtual Machine operation response. + */ + @Override + public VirtualMachineGetResponse get(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roles/" + virtualMachineName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element persistentVMRoleElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "PersistentVMRole"); + if (persistentVMRoleElement != null) { + Element roleNameElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + result.setRoleName(roleNameInstance); + } + + Element osVersionElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "OsVersion"); + if (osVersionElement != null) { + String osVersionInstance; + osVersionInstance = osVersionElement.getTextContent(); + result.setOsVersion(osVersionInstance); + } + + Element roleTypeElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "RoleType"); + if (roleTypeElement != null) { + VirtualMachineRoleType roleTypeInstance; + roleTypeInstance = VirtualMachineRoleType.valueOf(roleTypeElement.getTextContent()); + result.setRoleType(roleTypeInstance); + } + + Element availabilitySetNameElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "AvailabilitySetName"); + if (availabilitySetNameElement != null) { + String availabilitySetNameInstance; + availabilitySetNameInstance = availabilitySetNameElement.getTextContent(); + result.setAvailabilitySetName(availabilitySetNameInstance); + } + + Element roleSizeElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "RoleSize"); + if (roleSizeElement != null) { + String roleSizeInstance; + roleSizeInstance = roleSizeElement.getTextContent(); + result.setRoleSize(roleSizeInstance); + } + + Element defaultWinRmCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "DefaultWinRmCertificateThumbprint"); + if (defaultWinRmCertificateThumbprintElement != null) { + String defaultWinRmCertificateThumbprintInstance; + defaultWinRmCertificateThumbprintInstance = defaultWinRmCertificateThumbprintElement.getTextContent(); + result.setDefaultWinRmCertificateThumbprint(defaultWinRmCertificateThumbprintInstance); + } + + Element configurationSetsSequenceElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSets"); + if (configurationSetsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").size(); i1 = i1 + 1) { + org.w3c.dom.Element configurationSetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(configurationSetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSet").get(i1)); + ConfigurationSet configurationSetInstance = new ConfigurationSet(); + result.getConfigurationSets().add(configurationSetInstance); + + Element configurationSetTypeElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ConfigurationSetType"); + if (configurationSetTypeElement != null) { + String configurationSetTypeInstance; + configurationSetTypeInstance = configurationSetTypeElement.getTextContent(); + configurationSetInstance.setConfigurationSetType(configurationSetTypeInstance); + } + + Element inputEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoints"); + if (inputEndpointsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").size(); i2 = i2 + 1) { + org.w3c.dom.Element inputEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(inputEndpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "InputEndpoint").get(i2)); + InputEndpoint inputEndpointInstance = new InputEndpoint(); + configurationSetInstance.getInputEndpoints().add(inputEndpointInstance); + + Element loadBalancedEndpointSetNameElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName"); + if (loadBalancedEndpointSetNameElement != null) { + String loadBalancedEndpointSetNameInstance; + loadBalancedEndpointSetNameInstance = loadBalancedEndpointSetNameElement.getTextContent(); + inputEndpointInstance.setLoadBalancedEndpointSetName(loadBalancedEndpointSetNameInstance); + } + + Element localPortElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LocalPort"); + if (localPortElement != null && (localPortElement.getTextContent() == null || localPortElement.getTextContent().isEmpty() == true) == false) { + int localPortInstance; + localPortInstance = DatatypeConverter.parseInt(localPortElement.getTextContent()); + inputEndpointInstance.setLocalPort(localPortInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + inputEndpointInstance.setName(nameInstance); + } + + Element portElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement != null && (portElement.getTextContent() == null || portElement.getTextContent().isEmpty() == true) == false) { + int portInstance; + portInstance = DatatypeConverter.parseInt(portElement.getTextContent()); + inputEndpointInstance.setPort(portInstance); + } + + Element loadBalancerProbeElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe"); + if (loadBalancerProbeElement != null) { + LoadBalancerProbe loadBalancerProbeInstance = new LoadBalancerProbe(); + inputEndpointInstance.setLoadBalancerProbe(loadBalancerProbeInstance); + + Element pathElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement != null) { + String pathInstance; + pathInstance = pathElement.getTextContent(); + loadBalancerProbeInstance.setPath(pathInstance); + } + + Element portElement2 = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Port"); + if (portElement2 != null) { + int portInstance2; + portInstance2 = DatatypeConverter.parseInt(portElement2.getTextContent()); + loadBalancerProbeInstance.setPort(portInstance2); + } + + Element protocolElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement != null) { + LoadBalancerProbeTransportProtocol protocolInstance; + protocolInstance = ComputeManagementClientImpl.parseLoadBalancerProbeTransportProtocol(protocolElement.getTextContent()); + loadBalancerProbeInstance.setProtocol(protocolInstance); + } + + Element intervalInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds"); + if (intervalInSecondsElement != null && (intervalInSecondsElement.getTextContent() == null || intervalInSecondsElement.getTextContent().isEmpty() == true) == false) { + int intervalInSecondsInstance; + intervalInSecondsInstance = DatatypeConverter.parseInt(intervalInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setIntervalInSeconds(intervalInSecondsInstance); + } + + Element timeoutInSecondsElement = XmlUtility.getElementByTagNameNS(loadBalancerProbeElement, "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds"); + if (timeoutInSecondsElement != null && (timeoutInSecondsElement.getTextContent() == null || timeoutInSecondsElement.getTextContent().isEmpty() == true) == false) { + int timeoutInSecondsInstance; + timeoutInSecondsInstance = DatatypeConverter.parseInt(timeoutInSecondsElement.getTextContent()); + loadBalancerProbeInstance.setTimeoutInSeconds(timeoutInSecondsInstance); + } + } + + Element protocolElement2 = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement2 != null) { + String protocolInstance2; + protocolInstance2 = protocolElement2.getTextContent(); + inputEndpointInstance.setProtocol(protocolInstance2); + } + + Element vipElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "Vip"); + if (vipElement != null) { + InetAddress vipInstance; + vipInstance = InetAddress.getByName(vipElement.getTextContent()); + inputEndpointInstance.setVirtualIPAddress(vipInstance); + } + + Element enableDirectServerReturnElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn"); + if (enableDirectServerReturnElement != null && (enableDirectServerReturnElement.getTextContent() == null || enableDirectServerReturnElement.getTextContent().isEmpty() == true) == false) { + boolean enableDirectServerReturnInstance; + enableDirectServerReturnInstance = DatatypeConverter.parseBoolean(enableDirectServerReturnElement.getTextContent().toLowerCase()); + inputEndpointInstance.setEnableDirectServerReturn(enableDirectServerReturnInstance); + } + + Element endpointAclElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement, "http://schemas.microsoft.com/windowsazure", "EndpointAcl"); + if (endpointAclElement != null) { + EndpointAcl endpointAclInstance = new EndpointAcl(); + inputEndpointInstance.setEndpointAcl(endpointAclInstance); + + Element rulesSequenceElement = XmlUtility.getElementByTagNameNS(endpointAclElement, "http://schemas.microsoft.com/windowsazure", "Rules"); + if (rulesSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").size(); i3 = i3 + 1) { + org.w3c.dom.Element rulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(rulesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Rule").get(i3)); + AccessControlListRule ruleInstance = new AccessControlListRule(); + endpointAclInstance.getRules().add(ruleInstance); + + Element orderElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Order"); + if (orderElement != null && (orderElement.getTextContent() == null || orderElement.getTextContent().isEmpty() == true) == false) { + int orderInstance; + orderInstance = DatatypeConverter.parseInt(orderElement.getTextContent()); + ruleInstance.setOrder(orderInstance); + } + + Element actionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Action"); + if (actionElement != null) { + String actionInstance; + actionInstance = actionElement.getTextContent(); + ruleInstance.setAction(actionInstance); + } + + Element remoteSubnetElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "RemoteSubnet"); + if (remoteSubnetElement != null) { + String remoteSubnetInstance; + remoteSubnetInstance = remoteSubnetElement.getTextContent(); + ruleInstance.setRemoteSubnet(remoteSubnetInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(rulesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + ruleInstance.setDescription(descriptionInstance); + } + } + } + } + } + } + + Element subnetNamesSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SubnetNames"); + if (subnetNamesSequenceElement != null) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").size(); i4 = i4 + 1) { + org.w3c.dom.Element subnetNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetNamesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubnetName").get(i4)); + configurationSetInstance.getSubnetNames().add(subnetNamesElement.getTextContent()); + } + } + + Element staticVirtualNetworkIPAddressElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress"); + if (staticVirtualNetworkIPAddressElement != null) { + String staticVirtualNetworkIPAddressInstance; + staticVirtualNetworkIPAddressInstance = staticVirtualNetworkIPAddressElement.getTextContent(); + configurationSetInstance.setStaticVirtualNetworkIPAddress(staticVirtualNetworkIPAddressInstance); + } + + Element computerNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ComputerName"); + if (computerNameElement != null) { + String computerNameInstance; + computerNameInstance = computerNameElement.getTextContent(); + configurationSetInstance.setComputerName(computerNameInstance); + } + + Element adminPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminPassword"); + if (adminPasswordElement != null) { + String adminPasswordInstance; + adminPasswordInstance = adminPasswordElement.getTextContent(); + configurationSetInstance.setAdminPassword(adminPasswordInstance); + } + + Element resetPasswordOnFirstLogonElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon"); + if (resetPasswordOnFirstLogonElement != null && (resetPasswordOnFirstLogonElement.getTextContent() == null || resetPasswordOnFirstLogonElement.getTextContent().isEmpty() == true) == false) { + boolean resetPasswordOnFirstLogonInstance; + resetPasswordOnFirstLogonInstance = DatatypeConverter.parseBoolean(resetPasswordOnFirstLogonElement.getTextContent().toLowerCase()); + configurationSetInstance.setResetPasswordOnFirstLogon(resetPasswordOnFirstLogonInstance); + } + + Element enableAutomaticUpdatesElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates"); + if (enableAutomaticUpdatesElement != null && (enableAutomaticUpdatesElement.getTextContent() == null || enableAutomaticUpdatesElement.getTextContent().isEmpty() == true) == false) { + boolean enableAutomaticUpdatesInstance; + enableAutomaticUpdatesInstance = DatatypeConverter.parseBoolean(enableAutomaticUpdatesElement.getTextContent().toLowerCase()); + configurationSetInstance.setEnableAutomaticUpdates(enableAutomaticUpdatesInstance); + } + + Element timeZoneElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "TimeZone"); + if (timeZoneElement != null) { + String timeZoneInstance; + timeZoneInstance = timeZoneElement.getTextContent(); + configurationSetInstance.setTimeZone(timeZoneInstance); + } + + Element domainJoinElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DomainJoin"); + if (domainJoinElement != null) { + DomainJoinSettings domainJoinInstance = new DomainJoinSettings(); + configurationSetInstance.setDomainJoin(domainJoinInstance); + + Element credentialsElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Credentials"); + if (credentialsElement != null) { + DomainJoinCredentials credentialsInstance = new DomainJoinCredentials(); + domainJoinInstance.setCredentials(credentialsInstance); + + Element domainElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Domain"); + if (domainElement != null) { + String domainInstance; + domainInstance = domainElement.getTextContent(); + credentialsInstance.setDomain(domainInstance); + } + + Element usernameElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Username"); + if (usernameElement != null) { + String usernameInstance; + usernameInstance = usernameElement.getTextContent(); + credentialsInstance.setUserName(usernameInstance); + } + + Element passwordElement = XmlUtility.getElementByTagNameNS(credentialsElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement != null) { + String passwordInstance; + passwordInstance = passwordElement.getTextContent(); + credentialsInstance.setPassword(passwordInstance); + } + } + + Element joinDomainElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "JoinDomain"); + if (joinDomainElement != null) { + String joinDomainInstance; + joinDomainInstance = joinDomainElement.getTextContent(); + domainJoinInstance.setDomainToJoin(joinDomainInstance); + } + + Element machineObjectOUElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "MachineObjectOU"); + if (machineObjectOUElement != null) { + String machineObjectOUInstance; + machineObjectOUInstance = machineObjectOUElement.getTextContent(); + domainJoinInstance.setLdapMachineObjectOU(machineObjectOUInstance); + } + + Element provisioningElement = XmlUtility.getElementByTagNameNS(domainJoinElement, "http://schemas.microsoft.com/windowsazure", "Provisioning"); + if (provisioningElement != null) { + DomainJoinProvisioning provisioningInstance = new DomainJoinProvisioning(); + domainJoinInstance.setProvisioning(provisioningInstance); + + Element accountDataElement = XmlUtility.getElementByTagNameNS(provisioningElement, "http://schemas.microsoft.com/windowsazure", "AccountData"); + if (accountDataElement != null) { + String accountDataInstance; + accountDataInstance = accountDataElement.getTextContent(); + provisioningInstance.setAccountData(accountDataInstance); + } + } + } + + Element storedCertificateSettingsSequenceElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings"); + if (storedCertificateSettingsSequenceElement != null) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").size(); i5 = i5 + 1) { + org.w3c.dom.Element storedCertificateSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storedCertificateSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "CertificateSetting").get(i5)); + StoredCertificateSettings certificateSettingInstance = new StoredCertificateSettings(); + configurationSetInstance.getStoredCertificateSettings().add(certificateSettingInstance); + + Element storeLocationElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreLocation"); + if (storeLocationElement != null) { + } + + Element storeNameElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "StoreName"); + if (storeNameElement != null) { + String storeNameInstance; + storeNameInstance = storeNameElement.getTextContent(); + certificateSettingInstance.setStoreName(storeNameInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(storedCertificateSettingsElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + certificateSettingInstance.setThumbprint(thumbprintInstance); + } + } + } + + Element winRMElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "WinRM"); + if (winRMElement != null) { + WindowsRemoteManagementSettings winRMInstance = new WindowsRemoteManagementSettings(); + configurationSetInstance.setWindowsRemoteManagement(winRMInstance); + + Element listenersSequenceElement = XmlUtility.getElementByTagNameNS(winRMElement, "http://schemas.microsoft.com/windowsazure", "Listeners"); + if (listenersSequenceElement != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").size(); i6 = i6 + 1) { + org.w3c.dom.Element listenersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(listenersSequenceElement, "http://schemas.microsoft.com/windowsazure", "Listener").get(i6)); + WindowsRemoteManagementListener listenerInstance = new WindowsRemoteManagementListener(); + winRMInstance.getListeners().add(listenerInstance); + + Element protocolElement3 = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "Protocol"); + if (protocolElement3 != null) { + VirtualMachineWindowsRemoteManagementListenerType protocolInstance3; + protocolInstance3 = VirtualMachineWindowsRemoteManagementListenerType.valueOf(protocolElement3.getTextContent()); + listenerInstance.setListenerType(protocolInstance3); + } + + Element certificateThumbprintElement = XmlUtility.getElementByTagNameNS(listenersElement, "http://schemas.microsoft.com/windowsazure", "CertificateThumbprint"); + if (certificateThumbprintElement != null) { + String certificateThumbprintInstance; + certificateThumbprintInstance = certificateThumbprintElement.getTextContent(); + listenerInstance.setCertificateThumbprint(certificateThumbprintInstance); + } + } + } + } + + Element adminUsernameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "AdminUsername"); + if (adminUsernameElement != null) { + String adminUsernameInstance; + adminUsernameInstance = adminUsernameElement.getTextContent(); + configurationSetInstance.setAdminUserName(adminUsernameInstance); + } + + Element hostNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "HostName"); + if (hostNameElement != null) { + String hostNameInstance; + hostNameInstance = hostNameElement.getTextContent(); + configurationSetInstance.setHostName(hostNameInstance); + } + + Element userNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserName"); + if (userNameElement != null) { + String userNameInstance; + userNameInstance = userNameElement.getTextContent(); + configurationSetInstance.setUserName(userNameInstance); + } + + Element userPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "UserPassword"); + if (userPasswordElement != null) { + String userPasswordInstance; + userPasswordInstance = userPasswordElement.getTextContent(); + configurationSetInstance.setUserPassword(userPasswordInstance); + } + + Element disableSshPasswordAuthenticationElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication"); + if (disableSshPasswordAuthenticationElement != null && (disableSshPasswordAuthenticationElement.getTextContent() == null || disableSshPasswordAuthenticationElement.getTextContent().isEmpty() == true) == false) { + boolean disableSshPasswordAuthenticationInstance; + disableSshPasswordAuthenticationInstance = DatatypeConverter.parseBoolean(disableSshPasswordAuthenticationElement.getTextContent().toLowerCase()); + configurationSetInstance.setDisableSshPasswordAuthentication(disableSshPasswordAuthenticationInstance); + } + + Element sSHElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "SSH"); + if (sSHElement != null) { + SshSettings sSHInstance = new SshSettings(); + configurationSetInstance.setSshSettings(sSHInstance); + + Element publicKeysSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "PublicKeys"); + if (publicKeysSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").size(); i7 = i7 + 1) { + org.w3c.dom.Element publicKeysElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publicKeysSequenceElement, "http://schemas.microsoft.com/windowsazure", "PublicKey").get(i7)); + SshSettingPublicKey publicKeyInstance = new SshSettingPublicKey(); + sSHInstance.getPublicKeys().add(publicKeyInstance); + + Element fingerprintElement = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement != null) { + String fingerprintInstance; + fingerprintInstance = fingerprintElement.getTextContent(); + publicKeyInstance.setFingerprint(fingerprintInstance); + } + + Element pathElement2 = XmlUtility.getElementByTagNameNS(publicKeysElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement2 != null) { + String pathInstance2; + pathInstance2 = pathElement2.getTextContent(); + publicKeyInstance.setPath(pathInstance2); + } + } + } + + Element keyPairsSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement, "http://schemas.microsoft.com/windowsazure", "KeyPairs"); + if (keyPairsSequenceElement != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").size(); i8 = i8 + 1) { + org.w3c.dom.Element keyPairsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(keyPairsSequenceElement, "http://schemas.microsoft.com/windowsazure", "KeyPair").get(i8)); + SshSettingKeyPair keyPairInstance = new SshSettingKeyPair(); + sSHInstance.getKeyPairs().add(keyPairInstance); + + Element fingerprintElement2 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Fingerprint"); + if (fingerprintElement2 != null) { + String fingerprintInstance2; + fingerprintInstance2 = fingerprintElement2.getTextContent(); + keyPairInstance.setFingerprint(fingerprintInstance2); + } + + Element pathElement3 = XmlUtility.getElementByTagNameNS(keyPairsElement, "http://schemas.microsoft.com/windowsazure", "Path"); + if (pathElement3 != null) { + String pathInstance3; + pathInstance3 = pathElement3.getTextContent(); + keyPairInstance.setPath(pathInstance3); + } + } + } + } + + Element customDataElement = XmlUtility.getElementByTagNameNS(configurationSetsElement, "http://schemas.microsoft.com/windowsazure", "CustomData"); + if (customDataElement != null) { + String customDataInstance; + customDataInstance = customDataElement.getTextContent(); + configurationSetInstance.setCustomData(customDataInstance); + } + } + } + + Element dataVirtualHardDisksSequenceElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks"); + if (dataVirtualHardDisksSequenceElement != null) { + for (int i9 = 0; i9 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").size(); i9 = i9 + 1) { + org.w3c.dom.Element dataVirtualHardDisksElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataVirtualHardDisksSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk").get(i9)); + DataVirtualHardDisk dataVirtualHardDiskInstance = new DataVirtualHardDisk(); + result.getDataVirtualHardDisks().add(dataVirtualHardDiskInstance); + + Element hostCachingElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement != null && (hostCachingElement.getTextContent() == null || hostCachingElement.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance; + hostCachingInstance = VirtualHardDiskHostCaching.valueOf(hostCachingElement.getTextContent()); + dataVirtualHardDiskInstance.setHostCaching(hostCachingInstance); + } + + Element diskLabelElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement != null) { + String diskLabelInstance; + diskLabelInstance = diskLabelElement.getTextContent(); + dataVirtualHardDiskInstance.setLabel(diskLabelInstance); + } + + Element diskNameElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement != null) { + String diskNameInstance; + diskNameInstance = diskNameElement.getTextContent(); + dataVirtualHardDiskInstance.setName(diskNameInstance); + } + + Element lunElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "Lun"); + if (lunElement != null && (lunElement.getTextContent() == null || lunElement.getTextContent().isEmpty() == true) == false) { + int lunInstance; + lunInstance = DatatypeConverter.parseInt(lunElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalUnitNumber(lunInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null && (logicalDiskSizeInGBElement.getTextContent() == null || logicalDiskSizeInGBElement.getTextContent().isEmpty() == true) == false) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + dataVirtualHardDiskInstance.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setMediaLink(mediaLinkInstance); + } + + Element sourceMediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure", "SourceMediaLink"); + if (sourceMediaLinkElement != null) { + URI sourceMediaLinkInstance; + sourceMediaLinkInstance = new URI(sourceMediaLinkElement.getTextContent()); + dataVirtualHardDiskInstance.setSourceMediaLink(sourceMediaLinkInstance); + } + } + } + + Element oSVirtualHardDiskElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk"); + if (oSVirtualHardDiskElement != null) { + OSVirtualHardDisk oSVirtualHardDiskInstance = new OSVirtualHardDisk(); + result.setOSVirtualHardDisk(oSVirtualHardDiskInstance); + + Element hostCachingElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement2 != null && (hostCachingElement2.getTextContent() == null || hostCachingElement2.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance2; + hostCachingInstance2 = VirtualHardDiskHostCaching.valueOf(hostCachingElement2.getTextContent()); + oSVirtualHardDiskInstance.setHostCaching(hostCachingInstance2); + } + + Element diskLabelElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskLabel"); + if (diskLabelElement2 != null) { + String diskLabelInstance2; + diskLabelInstance2 = diskLabelElement2.getTextContent(); + oSVirtualHardDiskInstance.setLabel(diskLabelInstance2); + } + + Element diskNameElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "DiskName"); + if (diskNameElement2 != null) { + String diskNameInstance2; + diskNameInstance2 = diskNameElement2.getTextContent(); + oSVirtualHardDiskInstance.setName(diskNameInstance2); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance2; + mediaLinkInstance2 = new URI(mediaLinkElement2.getTextContent()); + oSVirtualHardDiskInstance.setMediaLink(mediaLinkInstance2); + } + + Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); + if (sourceImageNameElement != null) { + String sourceImageNameInstance; + sourceImageNameInstance = sourceImageNameElement.getTextContent(); + oSVirtualHardDiskInstance.setSourceImageName(sourceImageNameInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + oSVirtualHardDiskInstance.setOperatingSystem(osInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Download RDP file operation retrieves the Remote Desktop Protocol + * configuration file from the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @return The Download RDP file operation response. + */ + @Override + public Future getRemoteDesktopFileAsync(final String serviceName, final String deploymentName, final String virtualMachineName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineGetRemoteDesktopFileResponse call() throws Exception { + return getRemoteDesktopFile(serviceName, deploymentName, virtualMachineName); + } + }); + } + + /** + * The Download RDP file operation retrieves the Remote Desktop Protocol + * configuration file from the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The Download RDP file operation response. + */ + @Override + public VirtualMachineGetRemoteDesktopFileResponse getRemoteDesktopFile(String serviceName, String deploymentName, String virtualMachineName) throws IOException, ServiceException { + // Validate + if (serviceName == null) { + throw new NullPointerException("serviceName"); + } + if (deploymentName == null) { + throw new NullPointerException("deploymentName"); + } + if (virtualMachineName == null) { + throw new NullPointerException("virtualMachineName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + CloudTracing.enter(invocationId, this, "getRemoteDesktopFileAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/hostedservices/" + serviceName.trim() + "/deployments/" + deploymentName.trim() + "/roleinstances/" + virtualMachineName.trim() + "/ModelFile" + "?" + "FileType=RDP"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineGetRemoteDesktopFileResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineGetRemoteDesktopFileResponse(); + result.setRemoteDesktopFile(StreamUtils.toString(responseContent).getBytes("UTF-8")); + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Restart role operation restarts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future restartAsync(final String serviceName, final String deploymentName, final String virtualMachineName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return restart(serviceName, deploymentName, virtualMachineName); + } + }); + } + + /** + * The Restart role operation restarts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * restart. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse restart(String serviceName, String deploymentName, String virtualMachineName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + CloudTracing.enter(invocationId, this, "restartAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginRestartingAsync(serviceName, deploymentName, virtualMachineName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown virtual + * machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future shutdownAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineShutdownParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return shutdown(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * The Shutdown Role operation shuts down the specified virtual machine. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx + * for more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * shutdown. + * @param parameters Required. The parameters for the shutdown virtual + * machine operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse shutdown(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineShutdownParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "shutdownAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginShutdownAsync(serviceName, deploymentName, virtualMachineName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Shutdown Roles operation stops the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Shutdown Roles + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future shutdownRolesAsync(final String serviceName, final String deploymentName, final VirtualMachineShutdownRolesParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return shutdownRoles(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Shutdown Roles operation stops the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Shutdown Roles + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse shutdownRoles(String serviceName, String deploymentName, VirtualMachineShutdownRolesParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "shutdownRolesAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginShuttingDownRolesAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Start Role operation starts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future startAsync(final String serviceName, final String deploymentName, final String virtualMachineName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return start(serviceName, deploymentName, virtualMachineName); + } + }); + } + + /** + * The Start Role operation starts the specified virtual machine. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of the virtual machine to + * start. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse start(String serviceName, String deploymentName, String virtualMachineName) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + CloudTracing.enter(invocationId, this, "startAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginStartingAsync(serviceName, deploymentName, virtualMachineName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Start Roles operation starts the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Start Roles + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future startRolesAsync(final String serviceName, final String deploymentName, final VirtualMachineStartRolesParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return startRoles(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Start Roles operation starts the specified set of virtual machines. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters to pass to the Start Roles + * operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse startRoles(String serviceName, String deploymentName, VirtualMachineStartRolesParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "startRolesAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginStartingRolesAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Update Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future updateAsync(final String serviceName, final String deploymentName, final String virtualMachineName, final VirtualMachineUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return update(serviceName, deploymentName, virtualMachineName, parameters); + } + }); + } + + /** + * The Update Role operation adds a virtual machine to an existing + * deployment. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for + * more information) + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param virtualMachineName Required. The name of your virtual machine. + * @param parameters Required. Parameters supplied to the Update Virtual + * Machine operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse update(String serviceName, String deploymentName, String virtualMachineName, VirtualMachineUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, InterruptedException, ExecutionException, URISyntaxException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("virtualMachineName", virtualMachineName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginUpdatingAsync(serviceName, deploymentName, virtualMachineName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Update Load Balanced Endpoint Set operation changes the specified + * load-balanced InputEndpoints on all the roles of an Infrastructure as a + * Service deployment. Non-load-balanced endpoints must be changed using + * UpdateRole. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Load + * Balanced Endpoint Set operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future updateLoadBalancedEndpointSetAsync(final String serviceName, final String deploymentName, final VirtualMachineUpdateLoadBalancedSetParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return updateLoadBalancedEndpointSet(serviceName, deploymentName, parameters); + } + }); + } + + /** + * The Update Load Balanced Endpoint Set operation changes the specified + * load-balanced InputEndpoints on all the roles of an Infrastructure as a + * Service deployment. Non-load-balanced endpoints must be changed using + * UpdateRole. + * + * @param serviceName Required. The name of your service. + * @param deploymentName Required. The name of your deployment. + * @param parameters Required. Parameters supplied to the Update Load + * Balanced Endpoint Set operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse updateLoadBalancedEndpointSet(String serviceName, String deploymentName, VirtualMachineUpdateLoadBalancedSetParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serviceName", serviceName); + tracingParameters.put("deploymentName", deploymentName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateLoadBalancedEndpointSetAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachinesOperations().beginUpdatingLoadBalancedEndpointSetAsync(serviceName, deploymentName, parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineVMImageOperations.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineVMImageOperations.java new file mode 100644 index 0000000000000..5970f968facfb --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineVMImageOperations.java @@ -0,0 +1,149 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineVMImageListResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* machine templates in your subscription. +*/ +public interface VirtualMachineVMImageOperations { + /** + * The Begin Deleting Virtual Machine Image operation deletes the specified + * virtual machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeleting(String vmImageName, boolean deleteFromStorage) throws IOException, ServiceException; + + /** + * The Begin Deleting Virtual Machine Image operation deletes the specified + * virtual machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginDeletingAsync(String vmImageName, boolean deleteFromStorage); + + /** + * The Delete Virtual Machine Image operation deletes the specified virtual + * machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + OperationStatusResponse delete(String vmImageName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException; + + /** + * The Delete Virtual Machine Image operation deletes the specified virtual + * machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + Future deleteAsync(String vmImageName, boolean deleteFromStorage); + + /** + * The List Virtual Machine Images operation retrieves a list of the virtual + * machine images. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List VM Images operation response. + */ + VirtualMachineVMImageListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Virtual Machine Images operation retrieves a list of the virtual + * machine images. + * + * @return The List VM Images operation response. + */ + Future listAsync(); +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineVMImageOperationsImpl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineVMImageOperationsImpl.java new file mode 100644 index 0000000000000..6e1dd8c8caae6 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/VirtualMachineVMImageOperationsImpl.java @@ -0,0 +1,575 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.compute.models.VirtualHardDiskHostCaching; +import com.microsoft.windowsazure.management.compute.models.VirtualMachineVMImageListResponse; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* machine templates in your subscription. +*/ +public class VirtualMachineVMImageOperationsImpl implements ServiceOperations, VirtualMachineVMImageOperations { + /** + * Initializes a new instance of the VirtualMachineVMImageOperationsImpl + * class. + * + * @param client Reference to the service client. + */ + VirtualMachineVMImageOperationsImpl(ComputeManagementClientImpl client) { + this.client = client; + } + + private ComputeManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.compute.ComputeManagementClientImpl. + * @return The Client value. + */ + public ComputeManagementClientImpl getClient() { + return this.client; + } + + /** + * The Begin Deleting Virtual Machine Image operation deletes the specified + * virtual machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingAsync(final String vmImageName, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeleting(vmImageName, deleteFromStorage); + } + }); + } + + /** + * The Begin Deleting Virtual Machine Image operation deletes the specified + * virtual machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeleting(String vmImageName, boolean deleteFromStorage) throws IOException, ServiceException { + // Validate + if (vmImageName == null) { + throw new NullPointerException("vmImageName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("vmImageName", vmImageName); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/vmimages/" + vmImageName.trim() + "?"; + if (deleteFromStorage == true) { + url = url + "comp=" + "media"; + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Virtual Machine Image operation deletes the specified virtual + * machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public Future deleteAsync(final String vmImageName, final boolean deleteFromStorage) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return delete(vmImageName, deleteFromStorage); + } + }); + } + + /** + * The Delete Virtual Machine Image operation deletes the specified virtual + * machine image. + * + * @param vmImageName Required. The name of the virtual machine image to + * delete. + * @param deleteFromStorage Required. Specifies that the source blob for the + * image should also be deleted from storage. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request and error information regarding the failure. + */ + @Override + public OperationStatusResponse delete(String vmImageName, boolean deleteFromStorage) throws IOException, ServiceException, InterruptedException, ExecutionException { + ComputeManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("vmImageName", vmImageName); + tracingParameters.put("deleteFromStorage", deleteFromStorage); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getVirtualMachineVMImagesOperations().beginDeletingAsync(vmImageName, deleteFromStorage).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The List Virtual Machine Images operation retrieves a list of the virtual + * machine images. + * + * @return The List VM Images operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public VirtualMachineVMImageListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Virtual Machine Images operation retrieves a list of the virtual + * machine images. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List VM Images operation response. + */ + @Override + public VirtualMachineVMImageListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/vmimages"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2014-04-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + VirtualMachineVMImageListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new VirtualMachineVMImageListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element vMImagesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "VMImages"); + if (vMImagesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(vMImagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "VMImage").size(); i1 = i1 + 1) { + org.w3c.dom.Element vMImagesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(vMImagesSequenceElement, "http://schemas.microsoft.com/windowsazure", "VMImage").get(i1)); + VirtualMachineVMImageListResponse.VirtualMachineVMImage vMImageInstance = new VirtualMachineVMImageListResponse.VirtualMachineVMImage(); + result.getVMImages().add(vMImageInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + vMImageInstance.setName(nameInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + vMImageInstance.setLabel(labelInstance); + } + + Element categoryElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "Category"); + if (categoryElement != null) { + String categoryInstance; + categoryInstance = categoryElement.getTextContent(); + vMImageInstance.setCategory(categoryInstance); + } + + Element oSDiskConfigurationElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "OSDiskConfiguration"); + if (oSDiskConfigurationElement != null) { + VirtualMachineVMImageListResponse.OSDiskConfiguration oSDiskConfigurationInstance = new VirtualMachineVMImageListResponse.OSDiskConfiguration(); + vMImageInstance.setOSDiskConfiguration(oSDiskConfigurationInstance); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(oSDiskConfigurationElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + oSDiskConfigurationInstance.setName(nameInstance2); + } + + Element hostCachingElement = XmlUtility.getElementByTagNameNS(oSDiskConfigurationElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement != null && (hostCachingElement.getTextContent() == null || hostCachingElement.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance; + hostCachingInstance = VirtualHardDiskHostCaching.valueOf(hostCachingElement.getTextContent()); + oSDiskConfigurationInstance.setHostCaching(hostCachingInstance); + } + + Element oSStateElement = XmlUtility.getElementByTagNameNS(oSDiskConfigurationElement, "http://schemas.microsoft.com/windowsazure", "OSState"); + if (oSStateElement != null) { + String oSStateInstance; + oSStateInstance = oSStateElement.getTextContent(); + oSDiskConfigurationInstance.setOSState(oSStateInstance); + } + + Element osElement = XmlUtility.getElementByTagNameNS(oSDiskConfigurationElement, "http://schemas.microsoft.com/windowsazure", "OS"); + if (osElement != null) { + String osInstance; + osInstance = osElement.getTextContent(); + oSDiskConfigurationInstance.setOperatingSystem(osInstance); + } + + Element mediaLinkElement = XmlUtility.getElementByTagNameNS(oSDiskConfigurationElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement != null) { + URI mediaLinkInstance; + mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); + oSDiskConfigurationInstance.setMediaLink(mediaLinkInstance); + } + + Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(oSDiskConfigurationElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement != null) { + int logicalDiskSizeInGBInstance; + logicalDiskSizeInGBInstance = DatatypeConverter.parseInt(logicalDiskSizeInGBElement.getTextContent()); + oSDiskConfigurationInstance.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance); + } + } + + Element dataDiskConfigurationsSequenceElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "DataDiskConfigurations"); + if (dataDiskConfigurationsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataDiskConfigurationsSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataDiskConfiguration").size(); i2 = i2 + 1) { + org.w3c.dom.Element dataDiskConfigurationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dataDiskConfigurationsSequenceElement, "http://schemas.microsoft.com/windowsazure", "DataDiskConfiguration").get(i2)); + VirtualMachineVMImageListResponse.DataDiskConfiguration dataDiskConfigurationInstance = new VirtualMachineVMImageListResponse.DataDiskConfiguration(); + vMImageInstance.getDataDiskConfigurations().add(dataDiskConfigurationInstance); + + Element nameElement3 = XmlUtility.getElementByTagNameNS(dataDiskConfigurationsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement3 != null) { + String nameInstance3; + nameInstance3 = nameElement3.getTextContent(); + dataDiskConfigurationInstance.setName(nameInstance3); + } + + Element hostCachingElement2 = XmlUtility.getElementByTagNameNS(dataDiskConfigurationsElement, "http://schemas.microsoft.com/windowsazure", "HostCaching"); + if (hostCachingElement2 != null && (hostCachingElement2.getTextContent() == null || hostCachingElement2.getTextContent().isEmpty() == true) == false) { + VirtualHardDiskHostCaching hostCachingInstance2; + hostCachingInstance2 = VirtualHardDiskHostCaching.valueOf(hostCachingElement2.getTextContent()); + dataDiskConfigurationInstance.setHostCaching(hostCachingInstance2); + } + + Element lunElement = XmlUtility.getElementByTagNameNS(dataDiskConfigurationsElement, "http://schemas.microsoft.com/windowsazure", "Lun"); + if (lunElement != null && (lunElement.getTextContent() == null || lunElement.getTextContent().isEmpty() == true) == false) { + int lunInstance; + lunInstance = DatatypeConverter.parseInt(lunElement.getTextContent()); + dataDiskConfigurationInstance.setLogicalUnitNumber(lunInstance); + } + + Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(dataDiskConfigurationsElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); + if (mediaLinkElement2 != null) { + URI mediaLinkInstance2; + mediaLinkInstance2 = new URI(mediaLinkElement2.getTextContent()); + dataDiskConfigurationInstance.setMediaLink(mediaLinkInstance2); + } + + Element logicalDiskSizeInGBElement2 = XmlUtility.getElementByTagNameNS(dataDiskConfigurationsElement, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); + if (logicalDiskSizeInGBElement2 != null) { + int logicalDiskSizeInGBInstance2; + logicalDiskSizeInGBInstance2 = DatatypeConverter.parseInt(logicalDiskSizeInGBElement2.getTextContent()); + dataDiskConfigurationInstance.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance2); + } + } + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + vMImageInstance.setServiceName(serviceNameInstance); + } + + Element deploymentNameElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "DeploymentName"); + if (deploymentNameElement != null) { + String deploymentNameInstance; + deploymentNameInstance = deploymentNameElement.getTextContent(); + vMImageInstance.setDeploymentName(deploymentNameInstance); + } + + Element roleNameElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); + if (roleNameElement != null) { + String roleNameInstance; + roleNameInstance = roleNameElement.getTextContent(); + vMImageInstance.setRoleName(roleNameInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + vMImageInstance.setAffinityGroup(affinityGroupInstance); + } + + Element createdTimeElement = XmlUtility.getElementByTagNameNS(vMImagesElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); + if (createdTimeElement != null && (createdTimeElement.getTextContent() == null || createdTimeElement.getTextContent().isEmpty() == true) == false) { + Calendar createdTimeInstance; + createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); + vMImageInstance.setCreatedTime(createdTimeInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/AccessControlListRule.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/AccessControlListRule.java new file mode 100644 index 0000000000000..8ba4808b90441 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/AccessControlListRule.java @@ -0,0 +1,103 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* An access control rule for a public endpoint. +*/ +public class AccessControlListRule { + private String action; + + /** + * Optional. The action allowed by this Access Control List Rule. + * @return The Action value. + */ + public String getAction() { + return this.action; + } + + /** + * Optional. The action allowed by this Access Control List Rule. + * @param actionValue The Action value. + */ + public void setAction(final String actionValue) { + this.action = actionValue; + } + + private String description; + + /** + * Optional. The description for this Access Control List Rule. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. The description for this Access Control List Rule. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private Integer order; + + /** + * Optional. The order of application for this Access Control List Rule. + * @return The Order value. + */ + public Integer getOrder() { + return this.order; + } + + /** + * Optional. The order of application for this Access Control List Rule. + * @param orderValue The Order value. + */ + public void setOrder(final Integer orderValue) { + this.order = orderValue; + } + + private String remoteSubnet; + + /** + * Optional. The remote subnet that is granted access for this Access + * Control List Rule. + * @return The RemoteSubnet value. + */ + public String getRemoteSubnet() { + return this.remoteSubnet; + } + + /** + * Optional. The remote subnet that is granted access for this Access + * Control List Rule. + * @param remoteSubnetValue The RemoteSubnet value. + */ + public void setRemoteSubnet(final String remoteSubnetValue) { + this.remoteSubnet = remoteSubnetValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/CertificateFormat.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/CertificateFormat.java new file mode 100644 index 0000000000000..6cdbfee4e2f84 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/CertificateFormat.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The service certificate format. Azure supports the pfx and cer file formats. +*/ +public enum CertificateFormat { + Pfx, + + Cer, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/CertificateThumbprintAlgorithms.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/CertificateThumbprintAlgorithms.java new file mode 100644 index 0000000000000..8a2f4414a44d2 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/CertificateThumbprintAlgorithms.java @@ -0,0 +1,31 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Algorithm that was used to hash a service certificate. +*/ +public abstract class CertificateThumbprintAlgorithms { + public static final String SHA1 = "sha1"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ConfigurationSet.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ConfigurationSet.java new file mode 100644 index 0000000000000..9e7201d755d58 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ConfigurationSet.java @@ -0,0 +1,463 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Objects that provide system or application data. +*/ +public class ConfigurationSet { + private String adminPassword; + + /** + * Optional. Specifies the string representing the administrator password to + * use for the virtual machine. If the VM will be created from a + * 'Specialized' VM image, the password is not required. + * @return The AdminPassword value. + */ + public String getAdminPassword() { + return this.adminPassword; + } + + /** + * Optional. Specifies the string representing the administrator password to + * use for the virtual machine. If the VM will be created from a + * 'Specialized' VM image, the password is not required. + * @param adminPasswordValue The AdminPassword value. + */ + public void setAdminPassword(final String adminPasswordValue) { + this.adminPassword = adminPasswordValue; + } + + private String adminUserName; + + /** + * Optional. Specifies the name that is used to rename the default + * administrator account. If the VM will be created from a 'Specialized' VM + * image, the user name is not required. + * @return The AdminUserName value. + */ + public String getAdminUserName() { + return this.adminUserName; + } + + /** + * Optional. Specifies the name that is used to rename the default + * administrator account. If the VM will be created from a 'Specialized' VM + * image, the user name is not required. + * @param adminUserNameValue The AdminUserName value. + */ + public void setAdminUserName(final String adminUserNameValue) { + this.adminUserName = adminUserNameValue; + } + + private String computerName; + + /** + * Optional. Specifies the computer name for the virtual machine. If the + * computer name is not specified, a name is created based on the name of + * the role. Computer names must be 1 to 15 characters in length. This + * element is only used with the WindowsProvisioningConfiguration set. + * @return The ComputerName value. + */ + public String getComputerName() { + return this.computerName; + } + + /** + * Optional. Specifies the computer name for the virtual machine. If the + * computer name is not specified, a name is created based on the name of + * the role. Computer names must be 1 to 15 characters in length. This + * element is only used with the WindowsProvisioningConfiguration set. + * @param computerNameValue The ComputerName value. + */ + public void setComputerName(final String computerNameValue) { + this.computerName = computerNameValue; + } + + private String configurationSetType; + + /** + * Optional. Specifies the configuration type for the configuration set. + * @return The ConfigurationSetType value. + */ + public String getConfigurationSetType() { + return this.configurationSetType; + } + + /** + * Optional. Specifies the configuration type for the configuration set. + * @param configurationSetTypeValue The ConfigurationSetType value. + */ + public void setConfigurationSetType(final String configurationSetTypeValue) { + this.configurationSetType = configurationSetTypeValue; + } + + private String customData; + + /** + * Optional. Optional. Provides base64 encoded custom data to be passed to + * VM. + * @return The CustomData value. + */ + public String getCustomData() { + return this.customData; + } + + /** + * Optional. Optional. Provides base64 encoded custom data to be passed to + * VM. + * @param customDataValue The CustomData value. + */ + public void setCustomData(final String customDataValue) { + this.customData = customDataValue; + } + + private Boolean disableSshPasswordAuthentication; + + /** + * Optional. Specifies whether or not SSH authentication is disabled for the + * password. This element is only used with the + * LinuxProvisioningConfiguration set. By default this value is set to true. + * @return The DisableSshPasswordAuthentication value. + */ + public Boolean isDisableSshPasswordAuthentication() { + return this.disableSshPasswordAuthentication; + } + + /** + * Optional. Specifies whether or not SSH authentication is disabled for the + * password. This element is only used with the + * LinuxProvisioningConfiguration set. By default this value is set to true. + * @param disableSshPasswordAuthenticationValue The + * DisableSshPasswordAuthentication value. + */ + public void setDisableSshPasswordAuthentication(final Boolean disableSshPasswordAuthenticationValue) { + this.disableSshPasswordAuthentication = disableSshPasswordAuthenticationValue; + } + + private DomainJoinSettings domainJoin; + + /** + * Optional. Contains properties that specify a domain to which the virtual + * machine will be joined. This element is only used with the + * WindowsProvisioningConfiguration set. + * @return The DomainJoin value. + */ + public DomainJoinSettings getDomainJoin() { + return this.domainJoin; + } + + /** + * Optional. Contains properties that specify a domain to which the virtual + * machine will be joined. This element is only used with the + * WindowsProvisioningConfiguration set. + * @param domainJoinValue The DomainJoin value. + */ + public void setDomainJoin(final DomainJoinSettings domainJoinValue) { + this.domainJoin = domainJoinValue; + } + + private Boolean enableAutomaticUpdates; + + /** + * Optional. Specifies whether automatic updates are enabled for the virtual + * machine. This element is only used with the + * WindowsProvisioningConfiguration set. The default value is false. + * @return The EnableAutomaticUpdates value. + */ + public Boolean isEnableAutomaticUpdates() { + return this.enableAutomaticUpdates; + } + + /** + * Optional. Specifies whether automatic updates are enabled for the virtual + * machine. This element is only used with the + * WindowsProvisioningConfiguration set. The default value is false. + * @param enableAutomaticUpdatesValue The EnableAutomaticUpdates value. + */ + public void setEnableAutomaticUpdates(final Boolean enableAutomaticUpdatesValue) { + this.enableAutomaticUpdates = enableAutomaticUpdatesValue; + } + + private String hostName; + + /** + * Optional. Specifies the host name for the VM. Host names are ASCII + * character strings 1 to 64 characters in length. This element is only + * used with the LinuxProvisioningConfiguration set. + * @return The HostName value. + */ + public String getHostName() { + return this.hostName; + } + + /** + * Optional. Specifies the host name for the VM. Host names are ASCII + * character strings 1 to 64 characters in length. This element is only + * used with the LinuxProvisioningConfiguration set. + * @param hostNameValue The HostName value. + */ + public void setHostName(final String hostNameValue) { + this.hostName = hostNameValue; + } + + private ArrayList inputEndpoints; + + /** + * Optional. Contains a collection of external endpoints for the virtual + * machine. This element is only used with the NetworkConfigurationSet type. + * @return The InputEndpoints value. + */ + public ArrayList getInputEndpoints() { + return this.inputEndpoints; + } + + /** + * Optional. Contains a collection of external endpoints for the virtual + * machine. This element is only used with the NetworkConfigurationSet type. + * @param inputEndpointsValue The InputEndpoints value. + */ + public void setInputEndpoints(final ArrayList inputEndpointsValue) { + this.inputEndpoints = inputEndpointsValue; + } + + private Boolean resetPasswordOnFirstLogon; + + /** + * Optional. Specifies whether password should be reset the first time the + * administrator logs in. + * @return The ResetPasswordOnFirstLogon value. + */ + public Boolean isResetPasswordOnFirstLogon() { + return this.resetPasswordOnFirstLogon; + } + + /** + * Optional. Specifies whether password should be reset the first time the + * administrator logs in. + * @param resetPasswordOnFirstLogonValue The ResetPasswordOnFirstLogon value. + */ + public void setResetPasswordOnFirstLogon(final Boolean resetPasswordOnFirstLogonValue) { + this.resetPasswordOnFirstLogon = resetPasswordOnFirstLogonValue; + } + + private SshSettings sshSettings; + + /** + * Optional. Specifies the SSH public keys and key pairs to populate in the + * image during provisioning. This element is only used with the + * LinuxProvisioningConfiguration set. + * @return The SshSettings value. + */ + public SshSettings getSshSettings() { + return this.sshSettings; + } + + /** + * Optional. Specifies the SSH public keys and key pairs to populate in the + * image during provisioning. This element is only used with the + * LinuxProvisioningConfiguration set. + * @param sshSettingsValue The SshSettings value. + */ + public void setSshSettings(final SshSettings sshSettingsValue) { + this.sshSettings = sshSettingsValue; + } + + private String staticVirtualNetworkIPAddress; + + /** + * Optional. Specifies a Customer Address, i.e. an IP address assigned to a + * VM in a VNet's SubNet. For example: 10.0.0.4. + * @return The StaticVirtualNetworkIPAddress value. + */ + public String getStaticVirtualNetworkIPAddress() { + return this.staticVirtualNetworkIPAddress; + } + + /** + * Optional. Specifies a Customer Address, i.e. an IP address assigned to a + * VM in a VNet's SubNet. For example: 10.0.0.4. + * @param staticVirtualNetworkIPAddressValue The + * StaticVirtualNetworkIPAddress value. + */ + public void setStaticVirtualNetworkIPAddress(final String staticVirtualNetworkIPAddressValue) { + this.staticVirtualNetworkIPAddress = staticVirtualNetworkIPAddressValue; + } + + private ArrayList storedCertificateSettings; + + /** + * Optional. Contains a list of service certificates with which to provision + * to the new role. This element is only used with the + * WindowsProvisioningConfiguration set. + * @return The StoredCertificateSettings value. + */ + public ArrayList getStoredCertificateSettings() { + return this.storedCertificateSettings; + } + + /** + * Optional. Contains a list of service certificates with which to provision + * to the new role. This element is only used with the + * WindowsProvisioningConfiguration set. + * @param storedCertificateSettingsValue The StoredCertificateSettings value. + */ + public void setStoredCertificateSettings(final ArrayList storedCertificateSettingsValue) { + this.storedCertificateSettings = storedCertificateSettingsValue; + } + + private ArrayList subnetNames; + + /** + * Optional. The list of Virtual Network subnet names that the deployment + * belongs to. This element is only used with the NetworkConfigurationSet + * type. + * @return The SubnetNames value. + */ + public ArrayList getSubnetNames() { + return this.subnetNames; + } + + /** + * Optional. The list of Virtual Network subnet names that the deployment + * belongs to. This element is only used with the NetworkConfigurationSet + * type. + * @param subnetNamesValue The SubnetNames value. + */ + public void setSubnetNames(final ArrayList subnetNamesValue) { + this.subnetNames = subnetNamesValue; + } + + private String timeZone; + + /** + * Optional. Specifies the time zone for the virtual machine. This element + * is only used with the WindowsProvisioningConfiguration set. For a + * complete list of supported time zone entries, you can refer to the + * values listed in the registry entry + * HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows + * NT\\CurrentVersion\\Time Zones on a computer running Windows 7, Windows + * Server 2008, and Windows Server 2008 R2 or you can use the tzutil + * command-line tool to list the valid time. The tzutil tool is installed + * by default on Windows 7, Windows Server 2008, and Windows Server 2008 R2. + * @return The TimeZone value. + */ + public String getTimeZone() { + return this.timeZone; + } + + /** + * Optional. Specifies the time zone for the virtual machine. This element + * is only used with the WindowsProvisioningConfiguration set. For a + * complete list of supported time zone entries, you can refer to the + * values listed in the registry entry + * HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows + * NT\\CurrentVersion\\Time Zones on a computer running Windows 7, Windows + * Server 2008, and Windows Server 2008 R2 or you can use the tzutil + * command-line tool to list the valid time. The tzutil tool is installed + * by default on Windows 7, Windows Server 2008, and Windows Server 2008 R2. + * @param timeZoneValue The TimeZone value. + */ + public void setTimeZone(final String timeZoneValue) { + this.timeZone = timeZoneValue; + } + + private String userName; + + /** + * Optional. Specifies the name of a user to be created in the sudoer group + * of the virtual machine. User names are ASCII character strings 1 to 32 + * characters in length. This element is only used with the + * LinuxProvisioningConfiguration set. + * @return The UserName value. + */ + public String getUserName() { + return this.userName; + } + + /** + * Optional. Specifies the name of a user to be created in the sudoer group + * of the virtual machine. User names are ASCII character strings 1 to 32 + * characters in length. This element is only used with the + * LinuxProvisioningConfiguration set. + * @param userNameValue The UserName value. + */ + public void setUserName(final String userNameValue) { + this.userName = userNameValue; + } + + private String userPassword; + + /** + * Optional. Specifies the password for user name. Passwords are ASCII + * character strings 6 to 72 characters in length. This element is only + * used with the LinuxProvisioningConfiguration set. + * @return The UserPassword value. + */ + public String getUserPassword() { + return this.userPassword; + } + + /** + * Optional. Specifies the password for user name. Passwords are ASCII + * character strings 6 to 72 characters in length. This element is only + * used with the LinuxProvisioningConfiguration set. + * @param userPasswordValue The UserPassword value. + */ + public void setUserPassword(final String userPasswordValue) { + this.userPassword = userPasswordValue; + } + + private WindowsRemoteManagementSettings windowsRemoteManagement; + + /** + * Optional. Configures the Windows Remote Management service on the virtual + * machine, which enables remote Windows PowerShell. + * @return The WindowsRemoteManagement value. + */ + public WindowsRemoteManagementSettings getWindowsRemoteManagement() { + return this.windowsRemoteManagement; + } + + /** + * Optional. Configures the Windows Remote Management service on the virtual + * machine, which enables remote Windows PowerShell. + * @param windowsRemoteManagementValue The WindowsRemoteManagement value. + */ + public void setWindowsRemoteManagement(final WindowsRemoteManagementSettings windowsRemoteManagementValue) { + this.windowsRemoteManagement = windowsRemoteManagementValue; + } + + /** + * Initializes a new instance of the ConfigurationSet class. + * + */ + public ConfigurationSet() { + this.inputEndpoints = new ArrayList(); + this.storedCertificateSettings = new ArrayList(); + this.subnetNames = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ConfigurationSetTypes.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ConfigurationSetTypes.java new file mode 100644 index 0000000000000..22c152c6fb36c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ConfigurationSetTypes.java @@ -0,0 +1,35 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the configuration type for the configuration set. +*/ +public abstract class ConfigurationSetTypes { + public static final String NETWORKCONFIGURATION = "NetworkConfiguration"; + + public static final String WINDOWSPROVISIONINGCONFIGURATION = "WindowsProvisioningConfiguration"; + + public static final String LINUXPROVISIONINGCONFIGURATION = "LinuxProvisioningConfiguration"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DataVirtualHardDisk.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DataVirtualHardDisk.java new file mode 100644 index 0000000000000..8739e61aa5a11 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DataVirtualHardDisk.java @@ -0,0 +1,195 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; + +/** +* Objects that are used to create a data disk for a virtual machine. +*/ +public class DataVirtualHardDisk { + private VirtualHardDiskHostCaching hostCaching; + + /** + * Optional. Specifies the platform caching behavior of the data disk blob + * for read/write efficiency. The default value is ReadOnly. + * @return The HostCaching value. + */ + public VirtualHardDiskHostCaching getHostCaching() { + return this.hostCaching; + } + + /** + * Optional. Specifies the platform caching behavior of the data disk blob + * for read/write efficiency. The default value is ReadOnly. + * @param hostCachingValue The HostCaching value. + */ + public void setHostCaching(final VirtualHardDiskHostCaching hostCachingValue) { + this.hostCaching = hostCachingValue; + } + + private String label; + + /** + * Optional. Specifies the friendly name of the VHD used to create the data + * disk for the virtual machine. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Specifies the friendly name of the VHD used to create the data + * disk for the virtual machine. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private Integer logicalDiskSizeInGB; + + /** + * Optional. Specifies the size, in GB, of an empty VHD to be attached to + * the virtual machine. The VHD can be created as part of an attached disk + * or created as a virtual machine call by specifying the value for this + * property. Azure creates the empty VHD based on the size preference and + * attaches the newly created VHD to the virtual machine. + * @return The LogicalDiskSizeInGB value. + */ + public Integer getLogicalDiskSizeInGB() { + return this.logicalDiskSizeInGB; + } + + /** + * Optional. Specifies the size, in GB, of an empty VHD to be attached to + * the virtual machine. The VHD can be created as part of an attached disk + * or created as a virtual machine call by specifying the value for this + * property. Azure creates the empty VHD based on the size preference and + * attaches the newly created VHD to the virtual machine. + * @param logicalDiskSizeInGBValue The LogicalDiskSizeInGB value. + */ + public void setLogicalDiskSizeInGB(final Integer logicalDiskSizeInGBValue) { + this.logicalDiskSizeInGB = logicalDiskSizeInGBValue; + } + + private Integer logicalUnitNumber; + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the data disk. The + * LUN specifies the slot in which the data drive appears when mounted for + * usage by the virtual machine. This element is only listed when more than + * one data disk is attached to a virtual machine. + * @return The LogicalUnitNumber value. + */ + public Integer getLogicalUnitNumber() { + return this.logicalUnitNumber; + } + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the data disk. The + * LUN specifies the slot in which the data drive appears when mounted for + * usage by the virtual machine. This element is only listed when more than + * one data disk is attached to a virtual machine. + * @param logicalUnitNumberValue The LogicalUnitNumber value. + */ + public void setLogicalUnitNumber(final Integer logicalUnitNumberValue) { + this.logicalUnitNumber = logicalUnitNumberValue; + } + + private URI mediaLink; + + /** + * Optional. Optional. If the disk that is being added is already registered + * in the subscription or the VHD for the disk already exists in blob + * storage, this element is ignored. If a VHD file does not exist in blob + * storage, this element defines the location of the new VHD that is + * created when the new disk is added.Example: + * http://example.blob.core.windows.net/disks/mydatadisk.vhd + * @return The MediaLink value. + */ + public URI getMediaLink() { + return this.mediaLink; + } + + /** + * Optional. Optional. If the disk that is being added is already registered + * in the subscription or the VHD for the disk already exists in blob + * storage, this element is ignored. If a VHD file does not exist in blob + * storage, this element defines the location of the new VHD that is + * created when the new disk is added.Example: + * http://example.blob.core.windows.net/disks/mydatadisk.vhd + * @param mediaLinkValue The MediaLink value. + */ + public void setMediaLink(final URI mediaLinkValue) { + this.mediaLink = mediaLinkValue; + } + + private String name; + + /** + * Optional. Specifies the name of the VHD used to create the data disk for + * the virtual machine. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name of the VHD used to create the data disk for + * the virtual machine. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private URI sourceMediaLink; + + /** + * Optional. Optional. If the disk that is being added is already registered + * in the subscription or the VHD for the disk does not exist in blob + * storage, this element is ignored. If the VHD file exists in blob + * storage, this element defines the path to the VHD and a disk is + * registered from it and attached to the virtual machine. + * @return The SourceMediaLink value. + */ + public URI getSourceMediaLink() { + return this.sourceMediaLink; + } + + /** + * Optional. Optional. If the disk that is being added is already registered + * in the subscription or the VHD for the disk does not exist in blob + * storage, this element is ignored. If the VHD file exists in blob + * storage, this element defines the path to the VHD and a disk is + * registered from it and attached to the virtual machine. + * @param sourceMediaLinkValue The SourceMediaLink value. + */ + public void setSourceMediaLink(final URI sourceMediaLinkValue) { + this.sourceMediaLink = sourceMediaLinkValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentChangeConfigurationMode.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentChangeConfigurationMode.java new file mode 100644 index 0000000000000..6007287b6946f --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentChangeConfigurationMode.java @@ -0,0 +1,30 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +public enum DeploymentChangeConfigurationMode { + Auto, + + Manual, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentChangeConfigurationParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentChangeConfigurationParameters.java new file mode 100644 index 0000000000000..9f21e38c88edf --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentChangeConfigurationParameters.java @@ -0,0 +1,168 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.HashMap; + +/** +* Parameters supplied to the Change Configuration Deployment operation. +*/ +public class DeploymentChangeConfigurationParameters { + private String configuration; + + /** + * Required. The encoded service configuration file for the deployment. + * @return The Configuration value. + */ + public String getConfiguration() { + return this.configuration; + } + + /** + * Required. The encoded service configuration file for the deployment. + * @param configurationValue The Configuration value. + */ + public void setConfiguration(final String configurationValue) { + this.configuration = configurationValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended deployment property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 25 extended property name/value pairs. The maximum length of + * the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and the name must start with a + * letter. Attempting to use other characters, starting the name with a + * non-letter character, or entering a name that is identical to that of + * another extended property owned by the same hosted service will result + * in a status code 400 (Bad Request) error. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended deployment property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 25 extended property name/value pairs. The maximum length of + * the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and the name must start with a + * letter. Attempting to use other characters, starting the name with a + * non-letter character, or entering a name that is identical to that of + * another extended property owned by the same hosted service will result + * in a status code 400 (Bad Request) error. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private ExtensionConfiguration extensionConfiguration; + + /** + * Optional. Represents an extension that is added to the cloud service. In + * Azure, a process can run as an extension of a cloud service. For + * example, Remote Desktop Access or the Azure Diagnostics Agent can run as + * extensions to the cloud service. You must add an extension to the cloud + * service by using Add Extension before it can be added to the deployment. + * @return The ExtensionConfiguration value. + */ + public ExtensionConfiguration getExtensionConfiguration() { + return this.extensionConfiguration; + } + + /** + * Optional. Represents an extension that is added to the cloud service. In + * Azure, a process can run as an extension of a cloud service. For + * example, Remote Desktop Access or the Azure Diagnostics Agent can run as + * extensions to the cloud service. You must add an extension to the cloud + * service by using Add Extension before it can be added to the deployment. + * @param extensionConfigurationValue The ExtensionConfiguration value. + */ + public void setExtensionConfiguration(final ExtensionConfiguration extensionConfigurationValue) { + this.extensionConfiguration = extensionConfigurationValue; + } + + private DeploymentChangeConfigurationMode mode; + + /** + * Optional. The Change Configuration Deployment mode. Possible values are: + * Auto and Manual. If not specified, the default value is Auto. If set to + * Manual, WalkUpgradeDomain must be called to apply the update. If set to + * Auto, the update is automatically applied to each update domain for the + * service. + * @return The Mode value. + */ + public DeploymentChangeConfigurationMode getMode() { + return this.mode; + } + + /** + * Optional. The Change Configuration Deployment mode. Possible values are: + * Auto and Manual. If not specified, the default value is Auto. If set to + * Manual, WalkUpgradeDomain must be called to apply the update. If set to + * Auto, the update is automatically applied to each update domain for the + * service. + * @param modeValue The Mode value. + */ + public void setMode(final DeploymentChangeConfigurationMode modeValue) { + this.mode = modeValue; + } + + private Boolean treatWarningsAsError; + + /** + * Optional. Indicates whether to treat package validation warnings as + * errors. The default value is false. If set to true, the Created + * Deployment operation fails if there are validation warnings on the + * service package. + * @return The TreatWarningsAsError value. + */ + public Boolean isTreatWarningsAsError() { + return this.treatWarningsAsError; + } + + /** + * Optional. Indicates whether to treat package validation warnings as + * errors. The default value is false. If set to true, the Created + * Deployment operation fails if there are validation warnings on the + * service package. + * @param treatWarningsAsErrorValue The TreatWarningsAsError value. + */ + public void setTreatWarningsAsError(final Boolean treatWarningsAsErrorValue) { + this.treatWarningsAsError = treatWarningsAsErrorValue; + } + + /** + * Initializes a new instance of the DeploymentChangeConfigurationParameters + * class. + * + */ + public DeploymentChangeConfigurationParameters() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentCreateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentCreateParameters.java new file mode 100644 index 0000000000000..48b7629995888 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentCreateParameters.java @@ -0,0 +1,246 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; +import java.util.HashMap; + +/** +* Parameters supplied to the Create Deployment operation. +*/ +public class DeploymentCreateParameters { + private String configuration; + + /** + * Required. The service configuration file for the deployment. + * @return The Configuration value. + */ + public String getConfiguration() { + return this.configuration; + } + + /** + * Required. The service configuration file for the deployment. + * @param configurationValue The Configuration value. + */ + public void setConfiguration(final String configurationValue) { + this.configuration = configurationValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended deployment property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 25 extended property name/value pairs. The maximum length of + * the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and the name must start with a + * letter. Attempting to use other characters, starting the name with a + * non-letter character, or entering a name that is identical to that of + * another extended property owned by the same hosted service will result + * in a status code 400 (Bad Request) error. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended deployment property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 25 extended property name/value pairs. The maximum length of + * the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and the name must start with a + * letter. Attempting to use other characters, starting the name with a + * non-letter character, or entering a name that is identical to that of + * another extended property owned by the same hosted service will result + * in a status code 400 (Bad Request) error. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private ExtensionConfiguration extensionConfiguration; + + /** + * Optional. Represents an extension that is added to the cloud service. In + * Azure, a process can run as an extension of a cloud service. For + * example, Remote Desktop Access or the Azure Diagnostics Agent can run as + * extensions to the cloud service. You must add an extension to the cloud + * service by using Add Extension before it can be added to the deployment. + * @return The ExtensionConfiguration value. + */ + public ExtensionConfiguration getExtensionConfiguration() { + return this.extensionConfiguration; + } + + /** + * Optional. Represents an extension that is added to the cloud service. In + * Azure, a process can run as an extension of a cloud service. For + * example, Remote Desktop Access or the Azure Diagnostics Agent can run as + * extensions to the cloud service. You must add an extension to the cloud + * service by using Add Extension before it can be added to the deployment. + * @param extensionConfigurationValue The ExtensionConfiguration value. + */ + public void setExtensionConfiguration(final ExtensionConfiguration extensionConfigurationValue) { + this.extensionConfiguration = extensionConfigurationValue; + } + + private String label; + + /** + * Required. A name for the hosted service. The name can be up to 100 + * characters in length. It is recommended that the label be unique within + * the subscription. The name can be used identify the hosted service for + * your tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. A name for the hosted service. The name can be up to 100 + * characters in length. It is recommended that the label be unique within + * the subscription. The name can be used identify the hosted service for + * your tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Required. The name for the deployment. The deployment name must be unique + * among other deployments for the cloud service. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. The name for the deployment. The deployment name must be unique + * among other deployments for the cloud service. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private URI packageUri; + + /** + * Required. A URL that refers to the location of the service package in the + * Blob service. The service package can be located either in a storage + * account beneath the same subscription or a Shared Access Signature (SAS) + * URI from any storage account. For more info about Shared Access + * Signatures, see Delegating Access with a Shared Access Signature (REST + * API) at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee395415.aspx. + * @return The PackageUri value. + */ + public URI getPackageUri() { + return this.packageUri; + } + + /** + * Required. A URL that refers to the location of the service package in the + * Blob service. The service package can be located either in a storage + * account beneath the same subscription or a Shared Access Signature (SAS) + * URI from any storage account. For more info about Shared Access + * Signatures, see Delegating Access with a Shared Access Signature (REST + * API) at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee395415.aspx. + * @param packageUriValue The PackageUri value. + */ + public void setPackageUri(final URI packageUriValue) { + this.packageUri = packageUriValue; + } + + private Boolean startDeployment; + + /** + * Optional. Indicates whether to start the deployment immediately after it + * is created. The default value is false. If false, the service model is + * still deployed to the virtual machines but the code is not run + * immediately. Instead, the service is Suspended until you call Update + * Deployment Status and set the status toRunning, at which time the + * service will be started. A deployed service still incurs charges, even + * if it is suspended. + * @return The StartDeployment value. + */ + public Boolean isStartDeployment() { + return this.startDeployment; + } + + /** + * Optional. Indicates whether to start the deployment immediately after it + * is created. The default value is false. If false, the service model is + * still deployed to the virtual machines but the code is not run + * immediately. Instead, the service is Suspended until you call Update + * Deployment Status and set the status toRunning, at which time the + * service will be started. A deployed service still incurs charges, even + * if it is suspended. + * @param startDeploymentValue The StartDeployment value. + */ + public void setStartDeployment(final Boolean startDeploymentValue) { + this.startDeployment = startDeploymentValue; + } + + private Boolean treatWarningsAsError; + + /** + * Optional. Indicates whether to treat package validation warnings as + * errors. The default value is false. If set to true, the Created + * Deployment operation fails if there are validation warnings on the + * service package. + * @return The TreatWarningsAsError value. + */ + public Boolean isTreatWarningsAsError() { + return this.treatWarningsAsError; + } + + /** + * Optional. Indicates whether to treat package validation warnings as + * errors. The default value is false. If set to true, the Created + * Deployment operation fails if there are validation warnings on the + * service package. + * @param treatWarningsAsErrorValue The TreatWarningsAsError value. + */ + public void setTreatWarningsAsError(final Boolean treatWarningsAsErrorValue) { + this.treatWarningsAsError = treatWarningsAsErrorValue; + } + + /** + * Initializes a new instance of the DeploymentCreateParameters class. + * + */ + public DeploymentCreateParameters() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentDeleteRoleInstanceParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentDeleteRoleInstanceParameters.java new file mode 100644 index 0000000000000..e9b5594dc05ab --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentDeleteRoleInstanceParameters.java @@ -0,0 +1,58 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Parameters supplied to the delete role instance by deployment name operation. +*/ +public class DeploymentDeleteRoleInstanceParameters { + private ArrayList name; + + /** + * Optional. + * @return The Name value. + */ + public ArrayList getName() { + return this.name; + } + + /** + * Optional. + * @param nameValue The Name value. + */ + public void setName(final ArrayList nameValue) { + this.name = nameValue; + } + + /** + * Initializes a new instance of the DeploymentDeleteRoleInstanceParameters + * class. + * + */ + public DeploymentDeleteRoleInstanceParameters() { + this.name = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentGetPackageParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentGetPackageParameters.java new file mode 100644 index 0000000000000..cd5c47306281e --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentGetPackageParameters.java @@ -0,0 +1,71 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; + +/** +* Parameters supplied to the Get Package operation. +*/ +public class DeploymentGetPackageParameters { + private URI containerUri; + + /** + * Required. Specifies the URI of the container to which the packages will + * be saved. + * @return The ContainerUri value. + */ + public URI getContainerUri() { + return this.containerUri; + } + + /** + * Required. Specifies the URI of the container to which the packages will + * be saved. + * @param containerUriValue The ContainerUri value. + */ + public void setContainerUri(final URI containerUriValue) { + this.containerUri = containerUriValue; + } + + private Boolean overwriteExisting; + + /** + * Optional. Specifies whether an existing package in the storage container + * should be overwritten. + * @return The OverwriteExisting value. + */ + public Boolean isOverwriteExisting() { + return this.overwriteExisting; + } + + /** + * Optional. Specifies whether an existing package in the storage container + * should be overwritten. + * @param overwriteExistingValue The OverwriteExisting value. + */ + public void setOverwriteExisting(final Boolean overwriteExistingValue) { + this.overwriteExisting = overwriteExistingValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentGetResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentGetResponse.java new file mode 100644 index 0000000000000..91ea36ccf169c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentGetResponse.java @@ -0,0 +1,501 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; + +/** +* A deployment that exists in the cloud service. +*/ +public class DeploymentGetResponse extends OperationResponse { + private String configuration; + + /** + * Optional. The configuration file of the deployment. + * @return The Configuration value. + */ + public String getConfiguration() { + return this.configuration; + } + + /** + * Optional. The configuration file of the deployment. + * @param configurationValue The Configuration value. + */ + public void setConfiguration(final String configurationValue) { + this.configuration = configurationValue; + } + + private Calendar createdTime; + + /** + * Optional. The time that the deployment was created. + * @return The CreatedTime value. + */ + public Calendar getCreatedTime() { + return this.createdTime; + } + + /** + * Optional. The time that the deployment was created. + * @param createdTimeValue The CreatedTime value. + */ + public void setCreatedTime(final Calendar createdTimeValue) { + this.createdTime = createdTimeValue; + } + + private DeploymentSlot deploymentSlot; + + /** + * Optional. The deployment environment in which this deployment is running. + * @return The DeploymentSlot value. + */ + public DeploymentSlot getDeploymentSlot() { + return this.deploymentSlot; + } + + /** + * Optional. The deployment environment in which this deployment is running. + * @param deploymentSlotValue The DeploymentSlot value. + */ + public void setDeploymentSlot(final DeploymentSlot deploymentSlotValue) { + this.deploymentSlot = deploymentSlotValue; + } + + private DnsSettings dnsSettings; + + /** + * Optional. The custom DNS settings that are specified for deployment. + * @return The DnsSettings value. + */ + public DnsSettings getDnsSettings() { + return this.dnsSettings; + } + + /** + * Optional. The custom DNS settings that are specified for deployment. + * @param dnsSettingsValue The DnsSettings value. + */ + public void setDnsSettings(final DnsSettings dnsSettingsValue) { + this.dnsSettings = dnsSettingsValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum + * length of the name element is 64 characters, only alphanumeric + * characters and underscores are valid in the name, and it must start with + * a letter. Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum + * length of the name element is 64 characters, only alphanumeric + * characters and underscores are valid in the name, and it must start with + * a letter. Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private ExtensionConfiguration extensionConfiguration; + + /** + * Optional. Represents an extension that is added to the cloud service. + * @return The ExtensionConfiguration value. + */ + public ExtensionConfiguration getExtensionConfiguration() { + return this.extensionConfiguration; + } + + /** + * Optional. Represents an extension that is added to the cloud service. + * @param extensionConfigurationValue The ExtensionConfiguration value. + */ + public void setExtensionConfiguration(final ExtensionConfiguration extensionConfigurationValue) { + this.extensionConfiguration = extensionConfigurationValue; + } + + private String label; + + /** + * Optional. The user-supplied name of the deployment. This name can be used + * identify the deployment for tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The user-supplied name of the deployment. This name can be used + * identify the deployment for tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private Calendar lastModifiedTime; + + /** + * Optional. The last time that the deployment was modified. + * @return The LastModifiedTime value. + */ + public Calendar getLastModifiedTime() { + return this.lastModifiedTime; + } + + /** + * Optional. The last time that the deployment was modified. + * @param lastModifiedTimeValue The LastModifiedTime value. + */ + public void setLastModifiedTime(final Calendar lastModifiedTimeValue) { + this.lastModifiedTime = lastModifiedTimeValue; + } + + private boolean locked; + + /** + * Optional. Indicates whether the deployment is locked for new write + * operations because an existing operation is updating the deployment. + * @return The Locked value. + */ + public boolean isLocked() { + return this.locked; + } + + /** + * Optional. Indicates whether the deployment is locked for new write + * operations because an existing operation is updating the deployment. + * @param lockedValue The Locked value. + */ + public void setLocked(final boolean lockedValue) { + this.locked = lockedValue; + } + + private String name; + + /** + * Optional. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private PersistentVMDowntime persistentVMDowntime; + + /** + * Optional. Specifies information about when the virtual machine has been + * started and stopped. + * @return The PersistentVMDowntime value. + */ + public PersistentVMDowntime getPersistentVMDowntime() { + return this.persistentVMDowntime; + } + + /** + * Optional. Specifies information about when the virtual machine has been + * started and stopped. + * @param persistentVMDowntimeValue The PersistentVMDowntime value. + */ + public void setPersistentVMDowntime(final PersistentVMDowntime persistentVMDowntimeValue) { + this.persistentVMDowntime = persistentVMDowntimeValue; + } + + private String privateId; + + /** + * Optional. The unique identifier for this deployment. + * @return The PrivateId value. + */ + public String getPrivateId() { + return this.privateId; + } + + /** + * Optional. The unique identifier for this deployment. + * @param privateIdValue The PrivateId value. + */ + public void setPrivateId(final String privateIdValue) { + this.privateId = privateIdValue; + } + + private String reservedIPName; + + /** + * Optional. Preview Only. The name of the Reserved IP that the deployment + * belongs to. + * @return The ReservedIPName value. + */ + public String getReservedIPName() { + return this.reservedIPName; + } + + /** + * Optional. Preview Only. The name of the Reserved IP that the deployment + * belongs to. + * @param reservedIPNameValue The ReservedIPName value. + */ + public void setReservedIPName(final String reservedIPNameValue) { + this.reservedIPName = reservedIPNameValue; + } + + private ArrayList roleInstances; + + /** + * Optional. The list of role instances in the deployment. + * @return The RoleInstances value. + */ + public ArrayList getRoleInstances() { + return this.roleInstances; + } + + /** + * Optional. The list of role instances in the deployment. + * @param roleInstancesValue The RoleInstances value. + */ + public void setRoleInstances(final ArrayList roleInstancesValue) { + this.roleInstances = roleInstancesValue; + } + + private ArrayList roles; + + /** + * Optional. The list of roles in the deployment. + * @return The Roles value. + */ + public ArrayList getRoles() { + return this.roles; + } + + /** + * Optional. The list of roles in the deployment. + * @param rolesValue The Roles value. + */ + public void setRoles(final ArrayList rolesValue) { + this.roles = rolesValue; + } + + private boolean rollbackAllowed; + + /** + * Optional. Indicates whether the Rollback Update Or Upgrade operation is + * allowed at this time. + * @return The RollbackAllowed value. + */ + public boolean isRollbackAllowed() { + return this.rollbackAllowed; + } + + /** + * Optional. Indicates whether the Rollback Update Or Upgrade operation is + * allowed at this time. + * @param rollbackAllowedValue The RollbackAllowed value. + */ + public void setRollbackAllowed(final boolean rollbackAllowedValue) { + this.rollbackAllowed = rollbackAllowedValue; + } + + private String sdkVersion; + + /** + * Optional. The version of the Azure SDK that was used to generate the + * .cspkg that created this deployment. The first two numerical components + * of the returned version represent the version of the SDK used to create + * the package. + * @return The SdkVersion value. + */ + public String getSdkVersion() { + return this.sdkVersion; + } + + /** + * Optional. The version of the Azure SDK that was used to generate the + * .cspkg that created this deployment. The first two numerical components + * of the returned version represent the version of the SDK used to create + * the package. + * @param sdkVersionValue The SdkVersion value. + */ + public void setSdkVersion(final String sdkVersionValue) { + this.sdkVersion = sdkVersionValue; + } + + private DeploymentStatus status; + + /** + * Optional. The status of the deployment. + * @return The Status value. + */ + public DeploymentStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the deployment. + * @param statusValue The Status value. + */ + public void setStatus(final DeploymentStatus statusValue) { + this.status = statusValue; + } + + private int upgradeDomainCount; + + /** + * Optional. The number of upgrade domains available to this cloud service. + * @return The UpgradeDomainCount value. + */ + public int getUpgradeDomainCount() { + return this.upgradeDomainCount; + } + + /** + * Optional. The number of upgrade domains available to this cloud service. + * @param upgradeDomainCountValue The UpgradeDomainCount value. + */ + public void setUpgradeDomainCount(final int upgradeDomainCountValue) { + this.upgradeDomainCount = upgradeDomainCountValue; + } + + private UpgradeStatus upgradeStatus; + + /** + * Optional. Information about an update occurring on the deployment. + * @return The UpgradeStatus value. + */ + public UpgradeStatus getUpgradeStatus() { + return this.upgradeStatus; + } + + /** + * Optional. Information about an update occurring on the deployment. + * @param upgradeStatusValue The UpgradeStatus value. + */ + public void setUpgradeStatus(final UpgradeStatus upgradeStatusValue) { + this.upgradeStatus = upgradeStatusValue; + } + + private URI uri; + + /** + * Optional. The URL used to access the hosted service. For example, if the + * service name is MyService you could access the access the service by + * calling: http://MyService.cloudapp.net. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The URL used to access the hosted service. For example, if the + * service name is MyService you could access the access the service by + * calling: http://MyService.cloudapp.net. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + + private ArrayList virtualIPAddresses; + + /** + * Optional. The virtual IP addresses that are specified for the deployment. + * @return The VirtualIPAddresses value. + */ + public ArrayList getVirtualIPAddresses() { + return this.virtualIPAddresses; + } + + /** + * Optional. The virtual IP addresses that are specified for the deployment. + * @param virtualIPAddressesValue The VirtualIPAddresses value. + */ + public void setVirtualIPAddresses(final ArrayList virtualIPAddressesValue) { + this.virtualIPAddresses = virtualIPAddressesValue; + } + + private String virtualNetworkName; + + /** + * Optional. The name of the Virtual Network that the virtual machine + * connects to. + * @return The VirtualNetworkName value. + */ + public String getVirtualNetworkName() { + return this.virtualNetworkName; + } + + /** + * Optional. The name of the Virtual Network that the virtual machine + * connects to. + * @param virtualNetworkNameValue The VirtualNetworkName value. + */ + public void setVirtualNetworkName(final String virtualNetworkNameValue) { + this.virtualNetworkName = virtualNetworkNameValue; + } + + /** + * Initializes a new instance of the DeploymentGetResponse class. + * + */ + public DeploymentGetResponse() { + super(); + this.extendedProperties = new HashMap(); + this.roleInstances = new ArrayList(); + this.roles = new ArrayList(); + this.virtualIPAddresses = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentRollbackUpdateOrUpgradeParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentRollbackUpdateOrUpgradeParameters.java new file mode 100644 index 0000000000000..535918e7d0ec6 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentRollbackUpdateOrUpgradeParameters.java @@ -0,0 +1,69 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Rollback Update Or Upgrade operation. +*/ +public class DeploymentRollbackUpdateOrUpgradeParameters { + private boolean force; + + /** + * Optional. Specifies whether the rollback should proceed even when it will + * cause local data to be lost from some role instances. True if the + * rollback should proceed; otherwise false. + * @return The Force value. + */ + public boolean isForce() { + return this.force; + } + + /** + * Optional. Specifies whether the rollback should proceed even when it will + * cause local data to be lost from some role instances. True if the + * rollback should proceed; otherwise false. + * @param forceValue The Force value. + */ + public void setForce(final boolean forceValue) { + this.force = forceValue; + } + + private RollbackUpdateOrUpgradeMode mode; + + /** + * Required. Specifies whether the rollback should proceed automatically. + * @return The Mode value. + */ + public RollbackUpdateOrUpgradeMode getMode() { + return this.mode; + } + + /** + * Required. Specifies whether the rollback should proceed automatically. + * @param modeValue The Mode value. + */ + public void setMode(final RollbackUpdateOrUpgradeMode modeValue) { + this.mode = modeValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentSlot.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentSlot.java new file mode 100644 index 0000000000000..31c204df0971a --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentSlot.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The deployment environment in which this deployment is running. +*/ +public enum DeploymentSlot { + Staging, + + Production, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentStatus.java new file mode 100644 index 0000000000000..803ca8b035892 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentStatus.java @@ -0,0 +1,45 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The status of the deployment. +*/ +public enum DeploymentStatus { + Running, + + Suspended, + + RunningTransitioning, + + SuspendedTransitioning, + + Starting, + + Suspending, + + Deploying, + + Deleting, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentSwapParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentSwapParameters.java new file mode 100644 index 0000000000000..e94acf5b60062 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentSwapParameters.java @@ -0,0 +1,65 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Swap Deployment operation. +*/ +public class DeploymentSwapParameters { + private String productionDeployment; + + /** + * Optional. The optional name of the production deployment. + * @return The ProductionDeployment value. + */ + public String getProductionDeployment() { + return this.productionDeployment; + } + + /** + * Optional. The optional name of the production deployment. + * @param productionDeploymentValue The ProductionDeployment value. + */ + public void setProductionDeployment(final String productionDeploymentValue) { + this.productionDeployment = productionDeploymentValue; + } + + private String sourceDeployment; + + /** + * Required. The name of the source deployment. + * @return The SourceDeployment value. + */ + public String getSourceDeployment() { + return this.sourceDeployment; + } + + /** + * Required. The name of the source deployment. + * @param sourceDeploymentValue The SourceDeployment value. + */ + public void setSourceDeployment(final String sourceDeploymentValue) { + this.sourceDeployment = sourceDeploymentValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpdateStatusParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpdateStatusParameters.java new file mode 100644 index 0000000000000..ab12ed2e968c0 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpdateStatusParameters.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Update Deployment Status operation. +*/ +public class DeploymentUpdateStatusParameters { + private UpdatedDeploymentStatus status; + + /** + * Required. The new status of the deployment. + * @return The Status value. + */ + public UpdatedDeploymentStatus getStatus() { + return this.status; + } + + /** + * Required. The new status of the deployment. + * @param statusValue The Status value. + */ + public void setStatus(final UpdatedDeploymentStatus statusValue) { + this.status = statusValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeMode.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeMode.java new file mode 100644 index 0000000000000..eb1c89e9b2d57 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeMode.java @@ -0,0 +1,32 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +public enum DeploymentUpgradeMode { + Auto, + + Manual, + + Simultaneous, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeParameters.java new file mode 100644 index 0000000000000..36ce0a33b91f5 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeParameters.java @@ -0,0 +1,240 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; +import java.util.HashMap; + +/** +* Parameters supplied to the Upgrade Deployment operation. +*/ +public class DeploymentUpgradeParameters { + private String configuration; + + /** + * Required. The service configuration file for the deployment. + * @return The Configuration value. + */ + public String getConfiguration() { + return this.configuration; + } + + /** + * Required. The service configuration file for the deployment. + * @param configurationValue The Configuration value. + */ + public void setConfiguration(final String configurationValue) { + this.configuration = configurationValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended deployment property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 25 extended property name/value pairs. The maximum length of + * the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and the name must start with a + * letter. Attempting to use other characters, starting the name with a + * non-letter character, or entering a name that is identical to that of + * another extended property owned by the same hosted service will result + * in a status code 400 (Bad Request) error. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended deployment property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 25 extended property name/value pairs. The maximum length of + * the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and the name must start with a + * letter. Attempting to use other characters, starting the name with a + * non-letter character, or entering a name that is identical to that of + * another extended property owned by the same hosted service will result + * in a status code 400 (Bad Request) error. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private ExtensionConfiguration extensionConfiguration; + + /** + * Optional. Represents an extension that is added to the cloud service. In + * Azure, a process can run as an extension of a cloud service. For + * example, Remote Desktop Access or the Azure Diagnostics Agent can run as + * extensions to the cloud service. You must add an extension to the cloud + * service by using Add Extension before it can be added to the deployment. + * @return The ExtensionConfiguration value. + */ + public ExtensionConfiguration getExtensionConfiguration() { + return this.extensionConfiguration; + } + + /** + * Optional. Represents an extension that is added to the cloud service. In + * Azure, a process can run as an extension of a cloud service. For + * example, Remote Desktop Access or the Azure Diagnostics Agent can run as + * extensions to the cloud service. You must add an extension to the cloud + * service by using Add Extension before it can be added to the deployment. + * @param extensionConfigurationValue The ExtensionConfiguration value. + */ + public void setExtensionConfiguration(final ExtensionConfiguration extensionConfigurationValue) { + this.extensionConfiguration = extensionConfigurationValue; + } + + private boolean force; + + /** + * Required. Specifies whether the rollback should proceed even when it will + * cause local data to be lost from some role instances. + * @return The Force value. + */ + public boolean isForce() { + return this.force; + } + + /** + * Required. Specifies whether the rollback should proceed even when it will + * cause local data to be lost from some role instances. + * @param forceValue The Force value. + */ + public void setForce(final boolean forceValue) { + this.force = forceValue; + } + + private String label; + + /** + * Required. A name for the hosted service. The name can be up to 100 + * characters in length. It is recommended that the label be unique within + * the subscription. The name can be used identify the hosted service for + * your tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. A name for the hosted service. The name can be up to 100 + * characters in length. It is recommended that the label be unique within + * the subscription. The name can be used identify the hosted service for + * your tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private DeploymentUpgradeMode mode; + + /** + * Required. The type of update to initiate. Role instances are allocated to + * update domains when the service is deployed. Updates can be initiated + * manually in each update domain or initiated automatically in all update + * domains. Possible values are Auto or Manual. If not specified, the + * default value is Auto. If set to Manual, WalkUpgradeDomain must be + * called to apply the update. If set to Auto, the update is automatically + * applied to each update domain in sequence. + * @return The Mode value. + */ + public DeploymentUpgradeMode getMode() { + return this.mode; + } + + /** + * Required. The type of update to initiate. Role instances are allocated to + * update domains when the service is deployed. Updates can be initiated + * manually in each update domain or initiated automatically in all update + * domains. Possible values are Auto or Manual. If not specified, the + * default value is Auto. If set to Manual, WalkUpgradeDomain must be + * called to apply the update. If set to Auto, the update is automatically + * applied to each update domain in sequence. + * @param modeValue The Mode value. + */ + public void setMode(final DeploymentUpgradeMode modeValue) { + this.mode = modeValue; + } + + private URI packageUri; + + /** + * Required. A URL that refers to the location of the service package in the + * Blob service. The service package can be located either in a storage + * account beneath the same subscription or a Shared Access Signature (SAS) + * URI from any storage account. For more information about Shared Access + * Signatures, see Delegating Access with a Shared Access Signature (REST + * API) at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee395415.aspx. + * @return The PackageUri value. + */ + public URI getPackageUri() { + return this.packageUri; + } + + /** + * Required. A URL that refers to the location of the service package in the + * Blob service. The service package can be located either in a storage + * account beneath the same subscription or a Shared Access Signature (SAS) + * URI from any storage account. For more information about Shared Access + * Signatures, see Delegating Access with a Shared Access Signature (REST + * API) at + * http://msdn.microsoft.com/en-us/library/windowsazure/ee395415.aspx. + * @param packageUriValue The PackageUri value. + */ + public void setPackageUri(final URI packageUriValue) { + this.packageUri = packageUriValue; + } + + private String roleToUpgrade; + + /** + * Optional. The name of the specific role instance to update. + * @return The RoleToUpgrade value. + */ + public String getRoleToUpgrade() { + return this.roleToUpgrade; + } + + /** + * Optional. The name of the specific role instance to update. + * @param roleToUpgradeValue The RoleToUpgrade value. + */ + public void setRoleToUpgrade(final String roleToUpgradeValue) { + this.roleToUpgrade = roleToUpgradeValue; + } + + /** + * Initializes a new instance of the DeploymentUpgradeParameters class. + * + */ + public DeploymentUpgradeParameters() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeType.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeType.java new file mode 100644 index 0000000000000..9a5ba7b5e9207 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentUpgradeType.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The type of the upgrade. +*/ +public enum DeploymentUpgradeType { + Auto, + + Manual, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentWalkUpgradeDomainParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentWalkUpgradeDomainParameters.java new file mode 100644 index 0000000000000..03c1873ae426b --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DeploymentWalkUpgradeDomainParameters.java @@ -0,0 +1,51 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Walk Upgrade Domain operation. +*/ +public class DeploymentWalkUpgradeDomainParameters { + private int upgradeDomain; + + /** + * Required. An integer value that identifies the update domain to update. + * Update domains are identified with a zero-based index: the first update + * domain has an ID of 0, the second has an ID of 1, and so on. + * @return The UpgradeDomain value. + */ + public int getUpgradeDomain() { + return this.upgradeDomain; + } + + /** + * Required. An integer value that identifies the update domain to update. + * Update domains are identified with a zero-based index: the first update + * domain has an ID of 0, the second has an ID of 1, and so on. + * @param upgradeDomainValue The UpgradeDomain value. + */ + public void setUpgradeDomain(final int upgradeDomainValue) { + this.upgradeDomain = upgradeDomainValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DnsServer.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DnsServer.java new file mode 100644 index 0000000000000..65698aff8d91c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DnsServer.java @@ -0,0 +1,67 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.InetAddress; + +/** +* Information about a DNS Server in the virtual network. +*/ +public class DnsServer { + private InetAddress address; + + /** + * Optional. The DNS server address. + * @return The Address value. + */ + public InetAddress getAddress() { + return this.address; + } + + /** + * Optional. The DNS server address. + * @param addressValue The Address value. + */ + public void setAddress(final InetAddress addressValue) { + this.address = addressValue; + } + + private String name; + + /** + * Optional. The name of the DNS server. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the DNS server. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DnsSettings.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DnsSettings.java new file mode 100644 index 0000000000000..ec5fa216d41b0 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DnsSettings.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* The custom DNS settings that are specified for the deployment. +*/ +public class DnsSettings { + private ArrayList dnsServers; + + /** + * Optional. Contains a collection of objects that define the DNS server + * settings. + * @return The DnsServers value. + */ + public ArrayList getDnsServers() { + return this.dnsServers; + } + + /** + * Optional. Contains a collection of objects that define the DNS server + * settings. + * @param dnsServersValue The DnsServers value. + */ + public void setDnsServers(final ArrayList dnsServersValue) { + this.dnsServers = dnsServersValue; + } + + /** + * Initializes a new instance of the DnsSettings class. + * + */ + public DnsSettings() { + this.dnsServers = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinCredentials.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinCredentials.java new file mode 100644 index 0000000000000..915c06a3b2bd2 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinCredentials.java @@ -0,0 +1,93 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the values to use to join the virtual machine to the domain. +*/ +public class DomainJoinCredentials { + private String domain; + + /** + * Optional. Specifies the name of the domain used to authenticate an + * account. The value is a fully qualified DNS domain. If the domains name + * is not specified, Username must specify the user principal name (UPN) + * format (user@fully-qualified-DNS-domain) or the + * fully-qualified-DNS-domain\\username format. Example: example.com. + * @return The Domain value. + */ + public String getDomain() { + return this.domain; + } + + /** + * Optional. Specifies the name of the domain used to authenticate an + * account. The value is a fully qualified DNS domain. If the domains name + * is not specified, Username must specify the user principal name (UPN) + * format (user@fully-qualified-DNS-domain) or the + * fully-qualified-DNS-domain\\username format. Example: example.com. + * @param domainValue The Domain value. + */ + public void setDomain(final String domainValue) { + this.domain = domainValue; + } + + private String password; + + /** + * Required. Specifies the password to use to join the domain. + * @return The Password value. + */ + public String getPassword() { + return this.password; + } + + /** + * Required. Specifies the password to use to join the domain. + * @param passwordValue The Password value. + */ + public void setPassword(final String passwordValue) { + this.password = passwordValue; + } + + private String userName; + + /** + * Required. Specifies a user name in the domain that can be used to join + * the domain. + * @return The UserName value. + */ + public String getUserName() { + return this.userName; + } + + /** + * Required. Specifies a user name in the domain that can be used to join + * the domain. + * @param userNameValue The UserName value. + */ + public void setUserName(final String userNameValue) { + this.userName = userNameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinProvisioning.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinProvisioning.java new file mode 100644 index 0000000000000..325b9578faa64 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinProvisioning.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The configuration needed to provision the machine in the domain. +*/ +public class DomainJoinProvisioning { + private String accountData; + + /** + * Optional. The account info for joining the domain. + * @return The AccountData value. + */ + public String getAccountData() { + return this.accountData; + } + + /** + * Optional. The account info for joining the domain. + * @param accountDataValue The AccountData value. + */ + public void setAccountData(final String accountDataValue) { + this.accountData = accountDataValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinSettings.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinSettings.java new file mode 100644 index 0000000000000..a9f40caa7aed5 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/DomainJoinSettings.java @@ -0,0 +1,113 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Contains properties that specify a domain to which the virtual machine will +* be joined. This element is only used with the +* WindowsProvisioningConfiguration set. +*/ +public class DomainJoinSettings { + private DomainJoinCredentials credentials; + + /** + * Optional. Specifies the values to use to join the virtual machine to the + * domain. + * @return The Credentials value. + */ + public DomainJoinCredentials getCredentials() { + return this.credentials; + } + + /** + * Optional. Specifies the values to use to join the virtual machine to the + * domain. + * @param credentialsValue The Credentials value. + */ + public void setCredentials(final DomainJoinCredentials credentialsValue) { + this.credentials = credentialsValue; + } + + private String domainToJoin; + + /** + * Optional. Specifies the domain to join. + * @return The DomainToJoin value. + */ + public String getDomainToJoin() { + return this.domainToJoin; + } + + /** + * Optional. Specifies the domain to join. + * @param domainToJoinValue The DomainToJoin value. + */ + public void setDomainToJoin(final String domainToJoinValue) { + this.domainToJoin = domainToJoinValue; + } + + private String ldapMachineObjectOU; + + /** + * Optional. Specifies the Lightweight Directory Access Protocol (LDAP) X + * 500-distinguished name of the organizational unit (OU) in which the + * computer account is created. This account is in Active Directory on a + * domain controller in the domain to which the computer is being joined. + * Example: OU=MyOu,OU=MyParentOu,DC=example.com,DC=MyCompany,DC=com. + * @return The LdapMachineObjectOU value. + */ + public String getLdapMachineObjectOU() { + return this.ldapMachineObjectOU; + } + + /** + * Optional. Specifies the Lightweight Directory Access Protocol (LDAP) X + * 500-distinguished name of the organizational unit (OU) in which the + * computer account is created. This account is in Active Directory on a + * domain controller in the domain to which the computer is being joined. + * Example: OU=MyOu,OU=MyParentOu,DC=example.com,DC=MyCompany,DC=com. + * @param ldapMachineObjectOUValue The LdapMachineObjectOU value. + */ + public void setLdapMachineObjectOU(final String ldapMachineObjectOUValue) { + this.ldapMachineObjectOU = ldapMachineObjectOUValue; + } + + private DomainJoinProvisioning provisioning; + + /** + * Optional. Additional information for domain join provisioning. + * @return The Provisioning value. + */ + public DomainJoinProvisioning getProvisioning() { + return this.provisioning; + } + + /** + * Optional. Additional information for domain join provisioning. + * @param provisioningValue The Provisioning value. + */ + public void setProvisioning(final DomainJoinProvisioning provisioningValue) { + this.provisioning = provisioningValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/EndpointAcl.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/EndpointAcl.java new file mode 100644 index 0000000000000..95d7f57097284 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/EndpointAcl.java @@ -0,0 +1,57 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* The set of access control rules for the endpoint. +*/ +public class EndpointAcl { + private ArrayList rules; + + /** + * Optional. The set of access control rules for the endpoint. + * @return The Rules value. + */ + public ArrayList getRules() { + return this.rules; + } + + /** + * Optional. The set of access control rules for the endpoint. + * @param rulesValue The Rules value. + */ + public void setRules(final ArrayList rulesValue) { + this.rules = rulesValue; + } + + /** + * Initializes a new instance of the EndpointAcl class. + * + */ + public EndpointAcl() { + this.rules = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ExtensionConfiguration.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ExtensionConfiguration.java new file mode 100644 index 0000000000000..bb9d114762ef1 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ExtensionConfiguration.java @@ -0,0 +1,162 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Represents an extension that is added to the cloud service. +*/ +public class ExtensionConfiguration { + private ArrayList allRoles; + + /** + * Optional. Specifies a list of extensions that are applied to all roles in + * a deployment. + * @return The AllRoles value. + */ + public ArrayList getAllRoles() { + return this.allRoles; + } + + /** + * Optional. Specifies a list of extensions that are applied to all roles in + * a deployment. + * @param allRolesValue The AllRoles value. + */ + public void setAllRoles(final ArrayList allRolesValue) { + this.allRoles = allRolesValue; + } + + private ArrayList namedRoles; + + /** + * Optional. Specifies a list of extensions that are applied to specific + * roles in a deployment. + * @return The NamedRoles value. + */ + public ArrayList getNamedRoles() { + return this.namedRoles; + } + + /** + * Optional. Specifies a list of extensions that are applied to specific + * roles in a deployment. + * @param namedRolesValue The NamedRoles value. + */ + public void setNamedRoles(final ArrayList namedRolesValue) { + this.namedRoles = namedRolesValue; + } + + /** + * Initializes a new instance of the ExtensionConfiguration class. + * + */ + public ExtensionConfiguration() { + this.allRoles = new ArrayList(); + this.namedRoles = new ArrayList(); + } + + /** + * Represents an extension that is to be deployed to a role in a cloud + * service. + */ + public static class Extension { + private String id; + + /** + * Required. The identifier of the extension. The identifier is created + * when the extension is added to the cloud service. You can find the + * ID of an extension that was added to a cloud service by using List + * Extensions. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Required. The identifier of the extension. The identifier is created + * when the extension is added to the cloud service. You can find the + * ID of an extension that was added to a cloud service by using List + * Extensions. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + } + + /** + * Specifies a list of extensions that are applied to specific roles in a + * deployment. + */ + public static class NamedRole { + private ArrayList extensions; + + /** + * Required. Represents an extension that is to be deployed to a role in + * a cloud service. + * @return The Extensions value. + */ + public ArrayList getExtensions() { + return this.extensions; + } + + /** + * Required. Represents an extension that is to be deployed to a role in + * a cloud service. + * @param extensionsValue The Extensions value. + */ + public void setExtensions(final ArrayList extensionsValue) { + this.extensions = extensionsValue; + } + + private String roleName; + + /** + * Required. Specifies the name of the role. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Required. Specifies the name of the role. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + + /** + * Initializes a new instance of the NamedRole class. + * + */ + public NamedRole() { + this.extensions = new ArrayList(); + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentFormattedMessage.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentFormattedMessage.java new file mode 100644 index 0000000000000..b8ac98435ae3f --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentFormattedMessage.java @@ -0,0 +1,67 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* This object encapsulates a localized status message from the Guest Agent. +*/ +public class GuestAgentFormattedMessage { + private String language; + + /** + * Optional. Language code. Eg. "en-US". + * @return The Language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Optional. Language code. Eg. "en-US". + * @param languageValue The Language value. + */ + public void setLanguage(final String languageValue) { + this.language = languageValue; + } + + private String message; + + /** + * Optional. A string containing a message about the status of the Guest + * Agent or Resource Extension. + * @return The Message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Optional. A string containing a message about the status of the Guest + * Agent or Resource Extension. + * @param messageValue The Message value. + */ + public void setMessage(final String messageValue) { + this.message = messageValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentMessage.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentMessage.java new file mode 100644 index 0000000000000..e42ad75bd5e86 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentMessage.java @@ -0,0 +1,75 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* The guest agent message. +*/ +public class GuestAgentMessage { + private String messageResourceId; + + /** + * Optional. The message resource ID. + * @return The MessageResourceId value. + */ + public String getMessageResourceId() { + return this.messageResourceId; + } + + /** + * Optional. The message resource ID. + * @param messageResourceIdValue The MessageResourceId value. + */ + public void setMessageResourceId(final String messageResourceIdValue) { + this.messageResourceId = messageResourceIdValue; + } + + private ArrayList paramList; + + /** + * Optional. The guest agent message parameter list. + * @return The ParamList value. + */ + public ArrayList getParamList() { + return this.paramList; + } + + /** + * Optional. The guest agent message parameter list. + * @param paramListValue The ParamList value. + */ + public void setParamList(final ArrayList paramListValue) { + this.paramList = paramListValue; + } + + /** + * Initializes a new instance of the GuestAgentMessage class. + * + */ + public GuestAgentMessage() { + this.paramList = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentStatus.java new file mode 100644 index 0000000000000..d783553a020d3 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentStatus.java @@ -0,0 +1,166 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.Calendar; + +/** +* Optional. This object contains status information of the Guest Agent +* installed on a RoleInstance. Guest Agent can be installed on a role instance +* by setting "ProvisionGuestAgent" to true in Create Deployment or Add Role +* API calls. Version header: Required to be "2014-04-01" or later. +*/ +public class GuestAgentStatus { + private Integer code; + + /** + * Optional. Integer. Status code from the result of applying the GA + * settings. + * @return The Code value. + */ + public Integer getCode() { + return this.code; + } + + /** + * Optional. Integer. Status code from the result of applying the GA + * settings. + * @param codeValue The Code value. + */ + public void setCode(final Integer codeValue) { + this.code = codeValue; + } + + private GuestAgentFormattedMessage formattedMessage; + + /** + * Optional. This object encapsulates a formatted localized status message + * from the Guest Agent. + * @return The FormattedMessage value. + */ + public GuestAgentFormattedMessage getFormattedMessage() { + return this.formattedMessage; + } + + /** + * Optional. This object encapsulates a formatted localized status message + * from the Guest Agent. + * @param formattedMessageValue The FormattedMessage value. + */ + public void setFormattedMessage(final GuestAgentFormattedMessage formattedMessageValue) { + this.formattedMessage = formattedMessageValue; + } + + private String guestAgentVersion; + + /** + * Optional. Version of the Guest Agent installed on the role instance. + * @return The GuestAgentVersion value. + */ + public String getGuestAgentVersion() { + return this.guestAgentVersion; + } + + /** + * Optional. Version of the Guest Agent installed on the role instance. + * @param guestAgentVersionValue The GuestAgentVersion value. + */ + public void setGuestAgentVersion(final String guestAgentVersionValue) { + this.guestAgentVersion = guestAgentVersionValue; + } + + private GuestAgentMessage message; + + /** + * Optional. This object encapsulates a localized status message from the + * Guest Agent. + * @return The Message value. + */ + public GuestAgentMessage getMessage() { + return this.message; + } + + /** + * Optional. This object encapsulates a localized status message from the + * Guest Agent. + * @param messageValue The Message value. + */ + public void setMessage(final GuestAgentMessage messageValue) { + this.message = messageValue; + } + + private String protocolVersion; + + /** + * Optional. Protocol version used by the Guest Agent for status reporting. + * @return The ProtocolVersion value. + */ + public String getProtocolVersion() { + return this.protocolVersion; + } + + /** + * Optional. Protocol version used by the Guest Agent for status reporting. + * @param protocolVersionValue The ProtocolVersion value. + */ + public void setProtocolVersion(final String protocolVersionValue) { + this.protocolVersion = protocolVersionValue; + } + + private String status; + + /** + * Optional. The guest agent status, which can be: "Ready" or "NotReady". + * @return The Status value. + */ + public String getStatus() { + return this.status; + } + + /** + * Optional. The guest agent status, which can be: "Ready" or "NotReady". + * @param statusValue The Status value. + */ + public void setStatus(final String statusValue) { + this.status = statusValue; + } + + private Calendar timestamp; + + /** + * Optional. UTC time at which the status was reported. + * @return The Timestamp value. + */ + public Calendar getTimestamp() { + return this.timestamp; + } + + /** + * Optional. UTC time at which the status was reported. + * @param timestampValue The Timestamp value. + */ + public void setTimestamp(final Calendar timestampValue) { + this.timestamp = timestampValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentStatusTypes.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentStatusTypes.java new file mode 100644 index 0000000000000..3b700b30d201e --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/GuestAgentStatusTypes.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The guest agent status, which can be: "Ready" or "NotReady". +*/ +public abstract class GuestAgentStatusTypes { + public static final String READY = "Ready"; + + public static final String NOTREADY = "NotReady"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceAddExtensionParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceAddExtensionParameters.java new file mode 100644 index 0000000000000..905e9ecb96c77 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceAddExtensionParameters.java @@ -0,0 +1,201 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Add Extension operation. +*/ +public class HostedServiceAddExtensionParameters { + private String id; + + /** + * Required. The identifier of the extension. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Required. The identifier of the extension. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private String privateConfiguration; + + /** + * Optional. The private configuration that is defined using the schema + * returned by the List Available Extensions operation. + * @return The PrivateConfiguration value. + */ + public String getPrivateConfiguration() { + return this.privateConfiguration; + } + + /** + * Optional. The private configuration that is defined using the schema + * returned by the List Available Extensions operation. + * @param privateConfigurationValue The PrivateConfiguration value. + */ + public void setPrivateConfiguration(final String privateConfigurationValue) { + this.privateConfiguration = privateConfigurationValue; + } + + private String providerNamespace; + + /** + * Optional. The provider namespace of the extension. The provider namespace + * for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @return The ProviderNamespace value. + */ + public String getProviderNamespace() { + return this.providerNamespace; + } + + /** + * Optional. The provider namespace of the extension. The provider namespace + * for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @param providerNamespaceValue The ProviderNamespace value. + */ + public void setProviderNamespace(final String providerNamespaceValue) { + this.providerNamespace = providerNamespaceValue; + } + + private String publicConfiguration; + + /** + * Optional. The public configuration that is defined using the schema + * returned by the List Available Extensions operation. + * @return The PublicConfiguration value. + */ + public String getPublicConfiguration() { + return this.publicConfiguration; + } + + /** + * Optional. The public configuration that is defined using the schema + * returned by the List Available Extensions operation. + * @param publicConfigurationValue The PublicConfiguration value. + */ + public void setPublicConfiguration(final String publicConfigurationValue) { + this.publicConfiguration = publicConfigurationValue; + } + + private String thumbprint; + + /** + * Optional. The thumbprint of the certificate that is used to encrypt the + * configuration specified in PrivateConfiguration. If this element is not + * specified, a certificate may be automatically generated and added to the + * cloud service. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. The thumbprint of the certificate that is used to encrypt the + * configuration specified in PrivateConfiguration. If this element is not + * specified, a certificate may be automatically generated and added to the + * cloud service. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private String thumbprintAlgorithm; + + /** + * Optional. The thumbprint algorithm of the certificate that is used to + * encrypt the configuration specified in PrivateConfiguration. + * @return The ThumbprintAlgorithm value. + */ + public String getThumbprintAlgorithm() { + return this.thumbprintAlgorithm; + } + + /** + * Optional. The thumbprint algorithm of the certificate that is used to + * encrypt the configuration specified in PrivateConfiguration. + * @param thumbprintAlgorithmValue The ThumbprintAlgorithm value. + */ + public void setThumbprintAlgorithm(final String thumbprintAlgorithmValue) { + this.thumbprintAlgorithm = thumbprintAlgorithmValue; + } + + private String type; + + /** + * Required. The type of the extension. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Required. The type of the extension. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + + private String version; + + /** + * Optional. Specifies the version of the extension. If this element is not + * specified or an asterisk (*) is used as the value, the latest version of + * the extension is used. If the value is specified with a major version + * number and an asterisk as the minor version number (X.*), the latest + * minor version of the specified major version is selected. If a major + * version number and a minor version number are specified (X.Y), the + * specific extension version is selected. If a version is specified, an + * auto-upgrade is performed on the role instance. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. Specifies the version of the extension. If this element is not + * specified or an asterisk (*) is used as the value, the latest version of + * the extension is used. If the value is specified with a major version + * number and an asterisk as the minor version number (X.*), the latest + * minor version of the specified major version is selected. If a major + * version number and a minor version number are specified (X.Y), the + * specific extension version is selected. If a version is specified, an + * auto-upgrade is performed on the role instance. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceCheckNameAvailabilityResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceCheckNameAvailabilityResponse.java new file mode 100644 index 0000000000000..4366a96abf7eb --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceCheckNameAvailabilityResponse.java @@ -0,0 +1,71 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Check Hosted Service Name Availability operation response. +*/ +public class HostedServiceCheckNameAvailabilityResponse extends OperationResponse { + private boolean isAvailable; + + /** + * Optional. Indicates whether the name is available for you to use. The + * operation returns false for reserved or profane words. + * @return The IsAvailable value. + */ + public boolean isAvailable() { + return this.isAvailable; + } + + /** + * Optional. Indicates whether the name is available for you to use. The + * operation returns false for reserved or profane words. + * @param isAvailableValue The IsAvailable value. + */ + public void setIsAvailable(final boolean isAvailableValue) { + this.isAvailable = isAvailableValue; + } + + private String reason; + + /** + * Optional. Describes why the name cannot be used to create the cloud + * service. + * @return The Reason value. + */ + public String getReason() { + return this.reason; + } + + /** + * Optional. Describes why the name cannot be used to create the cloud + * service. + * @param reasonValue The Reason value. + */ + public void setReason(final String reasonValue) { + this.reason = reasonValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceCreateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceCreateParameters.java new file mode 100644 index 0000000000000..1600ffeddf67c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceCreateParameters.java @@ -0,0 +1,193 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.HashMap; + +/** +* Parameters supplied to the Create Hosted Service operation. +*/ +public class HostedServiceCreateParameters { + private String affinityGroup; + + /** + * Optional. The name of an existing affinity group associated with this + * subscription. Required if Location is not specified. This name is a GUID + * and can be retrieved by examining the name element of the response body + * returned by the List Affinity Groups operation. Specify either Location + * or AffinityGroup, but not both. To list available affinity groups, use + * the List Affinity Groups operation. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The name of an existing affinity group associated with this + * subscription. Required if Location is not specified. This name is a GUID + * and can be retrieved by examining the name element of the response body + * returned by the List Affinity Groups operation. Specify either Location + * or AffinityGroup, but not both. To list available affinity groups, use + * the List Affinity Groups operation. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String description; + + /** + * Optional. A description for the cloud service. The description can be up + * to 1024 characters in length. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. A description for the cloud service. The description can be up + * to 1024 characters in length. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum length + * of the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and it must start with a letter. + * Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum length + * of the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and it must start with a letter. + * Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private String label; + + /** + * Required. A name for the cloud service. The name can be up to 100 + * characters in length. The name can be used to identify the storage + * account for your tracking purposes. + * @return The Label value. + */ + public String getLabel() { + if (this.label == null) { + return this.getServiceName(); + } else { + return this.label; + } + } + + /** + * Required. A name for the cloud service. The name can be up to 100 + * characters in length. The name can be used to identify the storage + * account for your tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The location where the cloud service will be created. Required + * if AffinityGroup is not specified. Specify either Location or + * AffinityGroup, but not both. To list available locations, use the List + * Locations operation. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The location where the cloud service will be created. Required + * if AffinityGroup is not specified. Specify either Location or + * AffinityGroup, but not both. To list available locations, use the List + * Locations operation. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private String serviceName; + + /** + * Required. A name for the cloud service that is unique within Azure. This + * name is the DNS prefix name and can be used to access the service. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Required. A name for the cloud service that is unique within Azure. This + * name is the DNS prefix name and can be used to access the service. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + /** + * Initializes a new instance of the HostedServiceCreateParameters class. + * + */ + public HostedServiceCreateParameters() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetDetailedResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetDetailedResponse.java new file mode 100644 index 0000000000000..d2906e4904bf4 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetDetailedResponse.java @@ -0,0 +1,503 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; + +/** +* The detailed Get Hosted Service operation response. +*/ +public class HostedServiceGetDetailedResponse extends HostedServiceGetResponse { + private ArrayList deployments; + + /** + * Optional. The deployments that exist in the cloud service. + * @return The Deployments value. + */ + public ArrayList getDeployments() { + return this.deployments; + } + + /** + * Optional. The deployments that exist in the cloud service. + * @param deploymentsValue The Deployments value. + */ + public void setDeployments(final ArrayList deploymentsValue) { + this.deployments = deploymentsValue; + } + + /** + * Initializes a new instance of the HostedServiceGetDetailedResponse class. + * + */ + public HostedServiceGetDetailedResponse() { + super(); + this.deployments = new ArrayList(); + } + + /** + * A deployment that exists in the cloud service. + */ + public static class Deployment { + private String configuration; + + /** + * Optional. The configuration file of the deployment. + * @return The Configuration value. + */ + public String getConfiguration() { + return this.configuration; + } + + /** + * Optional. The configuration file of the deployment. + * @param configurationValue The Configuration value. + */ + public void setConfiguration(final String configurationValue) { + this.configuration = configurationValue; + } + + private Calendar createdTime; + + /** + * Optional. The time that the deployment was created. + * @return The CreatedTime value. + */ + public Calendar getCreatedTime() { + return this.createdTime; + } + + /** + * Optional. The time that the deployment was created. + * @param createdTimeValue The CreatedTime value. + */ + public void setCreatedTime(final Calendar createdTimeValue) { + this.createdTime = createdTimeValue; + } + + private DeploymentSlot deploymentSlot; + + /** + * Optional. The deployment environment in which this deployment is + * running. + * @return The DeploymentSlot value. + */ + public DeploymentSlot getDeploymentSlot() { + return this.deploymentSlot; + } + + /** + * Optional. The deployment environment in which this deployment is + * running. + * @param deploymentSlotValue The DeploymentSlot value. + */ + public void setDeploymentSlot(final DeploymentSlot deploymentSlotValue) { + this.deploymentSlot = deploymentSlotValue; + } + + private DnsSettings dnsSettings; + + /** + * Optional. The custom DNS settings that are specified for the + * deployment. + * @return The DnsSettings value. + */ + public DnsSettings getDnsSettings() { + return this.dnsSettings; + } + + /** + * Optional. The custom DNS settings that are specified for the + * deployment. + * @param dnsSettingsValue The DnsSettings value. + */ + public void setDnsSettings(final DnsSettings dnsSettingsValue) { + this.dnsSettings = dnsSettingsValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended cloud service property. + * Each extended property must have a defined name and a value. You can + * have a maximum of 50 extended property name and value pairs. The + * maximum length of the name element is 64 characters, only + * alphanumeric characters and underscores are valid in the name, and + * it must start with a letter. Attempting to use other characters, + * starting with a non-letter character, or entering a name that is + * identical to that of another extended property owned by the same + * service will result in a status code 400 (Bad Request) error. Each + * extended property value has a maximum length of 255 characters. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended cloud service property. + * Each extended property must have a defined name and a value. You can + * have a maximum of 50 extended property name and value pairs. The + * maximum length of the name element is 64 characters, only + * alphanumeric characters and underscores are valid in the name, and + * it must start with a letter. Attempting to use other characters, + * starting with a non-letter character, or entering a name that is + * identical to that of another extended property owned by the same + * service will result in a status code 400 (Bad Request) error. Each + * extended property value has a maximum length of 255 characters. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private String label; + + /** + * Optional. The user-supplied name of the deployment. This name can be + * used identify the deployment for your tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The user-supplied name of the deployment. This name can be + * used identify the deployment for your tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String lastModifiedTime; + + /** + * Optional. The last time that the deployment was modified. + * @return The LastModifiedTime value. + */ + public String getLastModifiedTime() { + return this.lastModifiedTime; + } + + /** + * Optional. The last time that the deployment was modified. + * @param lastModifiedTimeValue The LastModifiedTime value. + */ + public void setLastModifiedTime(final String lastModifiedTimeValue) { + this.lastModifiedTime = lastModifiedTimeValue; + } + + private boolean locked; + + /** + * Optional. Indicates whether the deployment is locked for new write + * operations because an existing operation is updating the deployment. + * @return The Locked value. + */ + public boolean isLocked() { + return this.locked; + } + + /** + * Optional. Indicates whether the deployment is locked for new write + * operations because an existing operation is updating the deployment. + * @param lockedValue The Locked value. + */ + public void setLocked(final boolean lockedValue) { + this.locked = lockedValue; + } + + private String name; + + /** + * Optional. The name of the deployment. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the deployment. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private PersistentVMDowntime persistentVMDowntime; + + /** + * Optional. Specifies information about when the virtual machine has + * been started and stopped. + * @return The PersistentVMDowntime value. + */ + public PersistentVMDowntime getPersistentVMDowntime() { + return this.persistentVMDowntime; + } + + /** + * Optional. Specifies information about when the virtual machine has + * been started and stopped. + * @param persistentVMDowntimeValue The PersistentVMDowntime value. + */ + public void setPersistentVMDowntime(final PersistentVMDowntime persistentVMDowntimeValue) { + this.persistentVMDowntime = persistentVMDowntimeValue; + } + + private String privateId; + + /** + * Optional. The unique identifier for this deployment. + * @return The PrivateId value. + */ + public String getPrivateId() { + return this.privateId; + } + + /** + * Optional. The unique identifier for this deployment. + * @param privateIdValue The PrivateId value. + */ + public void setPrivateId(final String privateIdValue) { + this.privateId = privateIdValue; + } + + private ArrayList roleInstances; + + /** + * Optional. The list of role instances in the deployment. + * @return The RoleInstances value. + */ + public ArrayList getRoleInstances() { + return this.roleInstances; + } + + /** + * Optional. The list of role instances in the deployment. + * @param roleInstancesValue The RoleInstances value. + */ + public void setRoleInstances(final ArrayList roleInstancesValue) { + this.roleInstances = roleInstancesValue; + } + + private ArrayList roles; + + /** + * Optional. The list of roles in the deployment. + * @return The Roles value. + */ + public ArrayList getRoles() { + return this.roles; + } + + /** + * Optional. The list of roles in the deployment. + * @param rolesValue The Roles value. + */ + public void setRoles(final ArrayList rolesValue) { + this.roles = rolesValue; + } + + private boolean rollbackAllowed; + + /** + * Optional. Indicates whether the Rollback Update Or Upgrade operation + * is allowed at this time. + * @return The RollbackAllowed value. + */ + public boolean isRollbackAllowed() { + return this.rollbackAllowed; + } + + /** + * Optional. Indicates whether the Rollback Update Or Upgrade operation + * is allowed at this time. + * @param rollbackAllowedValue The RollbackAllowed value. + */ + public void setRollbackAllowed(final boolean rollbackAllowedValue) { + this.rollbackAllowed = rollbackAllowedValue; + } + + private String sdkVersion; + + /** + * Optional. The version of the Azure SDK that was used to generate the + * .cspkg that created this deployment. The first two numerical + * components of the returned version represent the version of the SDK + * used to create the package. + * @return The SdkVersion value. + */ + public String getSdkVersion() { + return this.sdkVersion; + } + + /** + * Optional. The version of the Azure SDK that was used to generate the + * .cspkg that created this deployment. The first two numerical + * components of the returned version represent the version of the SDK + * used to create the package. + * @param sdkVersionValue The SdkVersion value. + */ + public void setSdkVersion(final String sdkVersionValue) { + this.sdkVersion = sdkVersionValue; + } + + private DeploymentStatus status; + + /** + * Optional. The status of the deployment. + * @return The Status value. + */ + public DeploymentStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the deployment. + * @param statusValue The Status value. + */ + public void setStatus(final DeploymentStatus statusValue) { + this.status = statusValue; + } + + private int upgradeDomainCount; + + /** + * Optional. The number of upgrade domains available to this cloud + * service. + * @return The UpgradeDomainCount value. + */ + public int getUpgradeDomainCount() { + return this.upgradeDomainCount; + } + + /** + * Optional. The number of upgrade domains available to this cloud + * service. + * @param upgradeDomainCountValue The UpgradeDomainCount value. + */ + public void setUpgradeDomainCount(final int upgradeDomainCountValue) { + this.upgradeDomainCount = upgradeDomainCountValue; + } + + private UpgradeStatus upgradeStatus; + + /** + * Optional. Specifies information about an update occurring on the + * deployment. + * @return The UpgradeStatus value. + */ + public UpgradeStatus getUpgradeStatus() { + return this.upgradeStatus; + } + + /** + * Optional. Specifies information about an update occurring on the + * deployment. + * @param upgradeStatusValue The UpgradeStatus value. + */ + public void setUpgradeStatus(final UpgradeStatus upgradeStatusValue) { + this.upgradeStatus = upgradeStatusValue; + } + + private URI uri; + + /** + * Optional. The URL used to access the hosted service. For example, if + * the service name is MyService you could access the access the + * service by calling: http://MyService.cloudapp.net. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The URL used to access the hosted service. For example, if + * the service name is MyService you could access the access the + * service by calling: http://MyService.cloudapp.net. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + + private ArrayList virtualIPAddresses; + + /** + * Optional. The virtual IP addresses that are specified for + * thedeployment. + * @return The VirtualIPAddresses value. + */ + public ArrayList getVirtualIPAddresses() { + return this.virtualIPAddresses; + } + + /** + * Optional. The virtual IP addresses that are specified for + * thedeployment. + * @param virtualIPAddressesValue The VirtualIPAddresses value. + */ + public void setVirtualIPAddresses(final ArrayList virtualIPAddressesValue) { + this.virtualIPAddresses = virtualIPAddressesValue; + } + + private String virtualNetworkName; + + /** + * Optional. The name of the Virtual Network that the virtual machine + * connects to. + * @return The VirtualNetworkName value. + */ + public String getVirtualNetworkName() { + return this.virtualNetworkName; + } + + /** + * Optional. The name of the Virtual Network that the virtual machine + * connects to. + * @param virtualNetworkNameValue The VirtualNetworkName value. + */ + public void setVirtualNetworkName(final String virtualNetworkNameValue) { + this.virtualNetworkName = virtualNetworkNameValue; + } + + /** + * Initializes a new instance of the Deployment class. + * + */ + public Deployment() { + this.extendedProperties = new HashMap(); + this.roleInstances = new ArrayList(); + this.roles = new ArrayList(); + this.virtualIPAddresses = new ArrayList(); + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetExtensionResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetExtensionResponse.java new file mode 100644 index 0000000000000..f2e1108fb36ac --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetExtensionResponse.java @@ -0,0 +1,169 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Extension operation response. +*/ +public class HostedServiceGetExtensionResponse extends OperationResponse { + private String id; + + /** + * Optional. The identifier of the extension. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. The identifier of the extension. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private String providerNamespace; + + /** + * Optional. The provider namespace of the extension. The provider namespace + * for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @return The ProviderNamespace value. + */ + public String getProviderNamespace() { + return this.providerNamespace; + } + + /** + * Optional. The provider namespace of the extension. The provider namespace + * for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @param providerNamespaceValue The ProviderNamespace value. + */ + public void setProviderNamespace(final String providerNamespaceValue) { + this.providerNamespace = providerNamespaceValue; + } + + private String publicConfiguration; + + /** + * Optional. The public configuration that is defined using the schema + * returned by the List Available Extensions operation. + * @return The PublicConfiguration value. + */ + public String getPublicConfiguration() { + return this.publicConfiguration; + } + + /** + * Optional. The public configuration that is defined using the schema + * returned by the List Available Extensions operation. + * @param publicConfigurationValue The PublicConfiguration value. + */ + public void setPublicConfiguration(final String publicConfigurationValue) { + this.publicConfiguration = publicConfigurationValue; + } + + private String thumbprint; + + /** + * Optional. The thumbprint of the certificate that is used to encrypt the + * configuration specified in PrivateConfiguration. If this element is not + * specified, a certificate may be automatically generated and added to the + * cloud service. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. The thumbprint of the certificate that is used to encrypt the + * configuration specified in PrivateConfiguration. If this element is not + * specified, a certificate may be automatically generated and added to the + * cloud service. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private String thumbprintAlgorithm; + + /** + * Optional. The thumbprint algorithm of the certificate that is used + * toencrypt the configuration specified in PrivateConfiguration. + * @return The ThumbprintAlgorithm value. + */ + public String getThumbprintAlgorithm() { + return this.thumbprintAlgorithm; + } + + /** + * Optional. The thumbprint algorithm of the certificate that is used + * toencrypt the configuration specified in PrivateConfiguration. + * @param thumbprintAlgorithmValue The ThumbprintAlgorithm value. + */ + public void setThumbprintAlgorithm(final String thumbprintAlgorithmValue) { + this.thumbprintAlgorithm = thumbprintAlgorithmValue; + } + + private String type; + + /** + * Required. The type of the extension. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Required. The type of the extension. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + + private String version; + + /** + * Optional. The version of the extension. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. The version of the extension. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetResponse.java new file mode 100644 index 0000000000000..c5b6269ab9b74 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceGetResponse.java @@ -0,0 +1,94 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* The Get Hosted Service operation response. +*/ +public class HostedServiceGetResponse extends OperationResponse { + private HostedServiceProperties properties; + + /** + * Optional. The properties that are assigned to the cloud service. + * @return The Properties value. + */ + public HostedServiceProperties getProperties() { + return this.properties; + } + + /** + * Optional. The properties that are assigned to the cloud service. + * @param propertiesValue The Properties value. + */ + public void setProperties(final HostedServiceProperties propertiesValue) { + this.properties = propertiesValue; + } + + private String serviceName; + + /** + * Optional. The name of the cloud service. This name is the DNS prefix name + * and can be used to access the cloud service. For example, if the cloud + * service name is MyService you could access the access the cloud service + * by calling: http://MyService.cloudapp.net. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The name of the cloud service. This name is the DNS prefix name + * and can be used to access the cloud service. For example, if the cloud + * service name is MyService you could access the access the cloud service + * by calling: http://MyService.cloudapp.net. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private URI uri; + + /** + * Optional. The Service Management API request URI used to perform Get + * Hosted Service Properties requests against the cloud service. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The Service Management API request URI used to perform Get + * Hosted Service Properties requests against the cloud service. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListAvailableExtensionsResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListAvailableExtensionsResponse.java new file mode 100644 index 0000000000000..a63ab7a6b39fa --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListAvailableExtensionsResponse.java @@ -0,0 +1,409 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Available Extensions operation response. +*/ +public class HostedServiceListAvailableExtensionsResponse extends OperationResponse implements Iterable { + private ArrayList extensionImages; + + /** + * Optional. The extensions that are available to add to your cloud service. + * @return The ExtensionImages value. + */ + public ArrayList getExtensionImages() { + return this.extensionImages; + } + + /** + * Optional. The extensions that are available to add to your cloud service. + * @param extensionImagesValue The ExtensionImages value. + */ + public void setExtensionImages(final ArrayList extensionImagesValue) { + this.extensionImages = extensionImagesValue; + } + + /** + * Initializes a new instance of the + * HostedServiceListAvailableExtensionsResponse class. + * + */ + public HostedServiceListAvailableExtensionsResponse() { + super(); + this.extensionImages = new ArrayList(); + } + + /** + * Gets the sequence of ExtensionImages. + * + */ + public Iterator iterator() { + return this.getExtensionImages().iterator(); + } + + /** + * An extension available to add to your cloud service. + */ + public static class ExtensionImage { + private Boolean blockRoleUponFailure; + + /** + * Optional. Indicates whether this version of extension blocks the role + * upon failure. + * @return The BlockRoleUponFailure value. + */ + public Boolean isBlockRoleUponFailure() { + return this.blockRoleUponFailure; + } + + /** + * Optional. Indicates whether this version of extension blocks the role + * upon failure. + * @param blockRoleUponFailureValue The BlockRoleUponFailure value. + */ + public void setBlockRoleUponFailure(final Boolean blockRoleUponFailureValue) { + this.blockRoleUponFailure = blockRoleUponFailureValue; + } + + private String description; + + /** + * Optional. The description of the extension. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. The description of the extension. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private URI eula; + + /** + * Optional. URI string pointing to the EULA (End User License + * Agreement) of this version of extension. This is optionally + * specified by the third-party publishing the extension instead of + * Azure, at the time of extension creation or update. + * @return The Eula value. + */ + public URI getEula() { + return this.eula; + } + + /** + * Optional. URI string pointing to the EULA (End User License + * Agreement) of this version of extension. This is optionally + * specified by the third-party publishing the extension instead of + * Azure, at the time of extension creation or update. + * @param eulaValue The Eula value. + */ + public void setEula(final URI eulaValue) { + this.eula = eulaValue; + } + + private URI homepageUri; + + /** + * Optional. URI string pointing to the homepage of this version of + * extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @return The HomepageUri value. + */ + public URI getHomepageUri() { + return this.homepageUri; + } + + /** + * Optional. URI string pointing to the homepage of this version of + * extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @param homepageUriValue The HomepageUri value. + */ + public void setHomepageUri(final URI homepageUriValue) { + this.homepageUri = homepageUriValue; + } + + private String hostingResources; + + /** + * Optional. The type of resource that supports the extension. This + * value can be WebRole, WorkerRole, or WebRole|WorkerRole. + * @return The HostingResources value. + */ + public String getHostingResources() { + return this.hostingResources; + } + + /** + * Optional. The type of resource that supports the extension. This + * value can be WebRole, WorkerRole, or WebRole|WorkerRole. + * @param hostingResourcesValue The HostingResources value. + */ + public void setHostingResources(final String hostingResourcesValue) { + this.hostingResources = hostingResourcesValue; + } + + private Boolean isJsonExtension; + + /** + * Optional. Boolean property indicating whether the extension accepts + * JSON or XML based configuration. If this property is 'true' then the + * extension accepts JSON based configuration. If this property is + * 'false' the extension accepts XML based configuration. + * @return The IsJsonExtension value. + */ + public Boolean isJsonExtension() { + return this.isJsonExtension; + } + + /** + * Optional. Boolean property indicating whether the extension accepts + * JSON or XML based configuration. If this property is 'true' then the + * extension accepts JSON based configuration. If this property is + * 'false' the extension accepts XML based configuration. + * @param isJsonExtensionValue The IsJsonExtension value. + */ + public void setIsJsonExtension(final Boolean isJsonExtensionValue) { + this.isJsonExtension = isJsonExtensionValue; + } + + private String label; + + /** + * Optional. The label that is used to identify the extension. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The label that is used to identify the extension. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private URI privacyUri; + + /** + * Optional. URI string pointing to the privacy document of this version + * of extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. URI string pointing to the privacy document of this version + * of extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private String privateConfigurationSchema; + + /** + * Optional. The schema of the private configuration. + * @return The PrivateConfigurationSchema value. + */ + public String getPrivateConfigurationSchema() { + return this.privateConfigurationSchema; + } + + /** + * Optional. The schema of the private configuration. + * @param privateConfigurationSchemaValue The PrivateConfigurationSchema + * value. + */ + public void setPrivateConfigurationSchema(final String privateConfigurationSchemaValue) { + this.privateConfigurationSchema = privateConfigurationSchemaValue; + } + + private String providerNamespace; + + /** + * Optional. The provider namespace of the extension. The provider + * namespace for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @return The ProviderNamespace value. + */ + public String getProviderNamespace() { + return this.providerNamespace; + } + + /** + * Optional. The provider namespace of the extension. The provider + * namespace for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @param providerNamespaceValue The ProviderNamespace value. + */ + public void setProviderNamespace(final String providerNamespaceValue) { + this.providerNamespace = providerNamespaceValue; + } + + private String publicConfigurationSchema; + + /** + * Optional. The schema of the public configuration. + * @return The PublicConfigurationSchema value. + */ + public String getPublicConfigurationSchema() { + return this.publicConfigurationSchema; + } + + /** + * Optional. The schema of the public configuration. + * @param publicConfigurationSchemaValue The PublicConfigurationSchema + * value. + */ + public void setPublicConfigurationSchema(final String publicConfigurationSchemaValue) { + this.publicConfigurationSchema = publicConfigurationSchemaValue; + } + + private Boolean replicationCompleted; + + /** + * Optional. Indicates whether this version of extension has been + * replicated to all regions or not. If true, then the given extension + * version can be used in creating or updating deployments. Otherwise, + * the given extension version might cause failure in creating or + * updating deployments. The typical time is 20 minutes for a + * newly-registered or newly-updated extension to replicate completely + * by Azure. + * @return The ReplicationCompleted value. + */ + public Boolean isReplicationCompleted() { + return this.replicationCompleted; + } + + /** + * Optional. Indicates whether this version of extension has been + * replicated to all regions or not. If true, then the given extension + * version can be used in creating or updating deployments. Otherwise, + * the given extension version might cause failure in creating or + * updating deployments. The typical time is 20 minutes for a + * newly-registered or newly-updated extension to replicate completely + * by Azure. + * @param replicationCompletedValue The ReplicationCompleted value. + */ + public void setReplicationCompleted(final Boolean replicationCompletedValue) { + this.replicationCompleted = replicationCompletedValue; + } + + private String sampleConfig; + + /** + * Optional. A sample configuration file for the resource extension. + * @return The SampleConfig value. + */ + public String getSampleConfig() { + return this.sampleConfig; + } + + /** + * Optional. A sample configuration file for the resource extension. + * @param sampleConfigValue The SampleConfig value. + */ + public void setSampleConfig(final String sampleConfigValue) { + this.sampleConfig = sampleConfigValue; + } + + private String thumbprintAlgorithm; + + /** + * Optional. The thumbprint algorithm of the certificate that is used + * for encryption. + * @return The ThumbprintAlgorithm value. + */ + public String getThumbprintAlgorithm() { + return this.thumbprintAlgorithm; + } + + /** + * Optional. The thumbprint algorithm of the certificate that is used + * for encryption. + * @param thumbprintAlgorithmValue The ThumbprintAlgorithm value. + */ + public void setThumbprintAlgorithm(final String thumbprintAlgorithmValue) { + this.thumbprintAlgorithm = thumbprintAlgorithmValue; + } + + private String type; + + /** + * Required. The type of the extension. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Required. The type of the extension. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + + private String version; + + /** + * Optional. The version of the extension. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. The version of the extension. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListExtensionsResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListExtensionsResponse.java new file mode 100644 index 0000000000000..99080b2bf17c7 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListExtensionsResponse.java @@ -0,0 +1,212 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Extensions operation response. +*/ +public class HostedServiceListExtensionsResponse extends OperationResponse implements Iterable { + private ArrayList extensions; + + /** + * Optional. The extensions that were added to a cloud service. + * @return The Extensions value. + */ + public ArrayList getExtensions() { + return this.extensions; + } + + /** + * Optional. The extensions that were added to a cloud service. + * @param extensionsValue The Extensions value. + */ + public void setExtensions(final ArrayList extensionsValue) { + this.extensions = extensionsValue; + } + + /** + * Initializes a new instance of the HostedServiceListExtensionsResponse + * class. + * + */ + public HostedServiceListExtensionsResponse() { + super(); + this.extensions = new ArrayList(); + } + + /** + * Gets the sequence of Extensions. + * + */ + public Iterator iterator() { + return this.getExtensions().iterator(); + } + + /** + * An extension that was added to a cloud service. + */ + public static class Extension { + private String id; + + /** + * Optional. The identifier of the extension. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. The identifier of the extension. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private String providerNamespace; + + /** + * Optional. The provider namespace of the extension. The provider + * namespace for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @return The ProviderNamespace value. + */ + public String getProviderNamespace() { + return this.providerNamespace; + } + + /** + * Optional. The provider namespace of the extension. The provider + * namespace for Azure extensions is Microsoft.Windows.Azure.Extensions. + * @param providerNamespaceValue The ProviderNamespace value. + */ + public void setProviderNamespace(final String providerNamespaceValue) { + this.providerNamespace = providerNamespaceValue; + } + + private String publicConfiguration; + + /** + * Optional. The public configuration that is defined using the schema + * returned by the List Extensions operation. + * @return The PublicConfiguration value. + */ + public String getPublicConfiguration() { + return this.publicConfiguration; + } + + /** + * Optional. The public configuration that is defined using the schema + * returned by the List Extensions operation. + * @param publicConfigurationValue The PublicConfiguration value. + */ + public void setPublicConfiguration(final String publicConfigurationValue) { + this.publicConfiguration = publicConfigurationValue; + } + + private String thumbprint; + + /** + * Optional. The thumbprint of the certificate that is used to encrypt + * the configuration specified in PrivateConfiguration. If this element + * is not specified, a certificate may be automatically generated and + * added to the cloud service. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. The thumbprint of the certificate that is used to encrypt + * the configuration specified in PrivateConfiguration. If this element + * is not specified, a certificate may be automatically generated and + * added to the cloud service. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private String thumbprintAlgorithm; + + /** + * Optional. The thumbprint algorithm of the certificate that is used to + * encrypt the configuration specified in PrivateConfiguration. + * @return The ThumbprintAlgorithm value. + */ + public String getThumbprintAlgorithm() { + return this.thumbprintAlgorithm; + } + + /** + * Optional. The thumbprint algorithm of the certificate that is used to + * encrypt the configuration specified in PrivateConfiguration. + * @param thumbprintAlgorithmValue The ThumbprintAlgorithm value. + */ + public void setThumbprintAlgorithm(final String thumbprintAlgorithmValue) { + this.thumbprintAlgorithm = thumbprintAlgorithmValue; + } + + private String type; + + /** + * Required. The type of the extension. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Required. The type of the extension. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + + private String version; + + /** + * Optional. The version of the extension. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. The version of the extension. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListResponse.java new file mode 100644 index 0000000000000..6ff65545f0a59 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceListResponse.java @@ -0,0 +1,136 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Hosted Service operation response. +*/ +public class HostedServiceListResponse extends OperationResponse implements Iterable { + private ArrayList hostedServices; + + /** + * Optional. The hosted services associated with your subscription. + * @return The HostedServices value. + */ + public ArrayList getHostedServices() { + return this.hostedServices; + } + + /** + * Optional. The hosted services associated with your subscription. + * @param hostedServicesValue The HostedServices value. + */ + public void setHostedServices(final ArrayList hostedServicesValue) { + this.hostedServices = hostedServicesValue; + } + + /** + * Initializes a new instance of the HostedServiceListResponse class. + * + */ + public HostedServiceListResponse() { + super(); + this.hostedServices = new ArrayList(); + } + + /** + * Gets the sequence of HostedServices. + * + */ + public Iterator iterator() { + return this.getHostedServices().iterator(); + } + + /** + * A hosted service associated with your subscription. + */ + public static class HostedService { + private HostedServiceProperties properties; + + /** + * Optional. The properties that are assigned to the cloud service. + * @return The Properties value. + */ + public HostedServiceProperties getProperties() { + return this.properties; + } + + /** + * Optional. The properties that are assigned to the cloud service. + * @param propertiesValue The Properties value. + */ + public void setProperties(final HostedServiceProperties propertiesValue) { + this.properties = propertiesValue; + } + + private String serviceName; + + /** + * Optional. The name of the cloud service. This name is the DNS prefix + * name and can be used to access the cloud service. For example, if + * the cloud service name is MyService you could access the cloud + * service by calling: http://MyService.cloudapp.net. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The name of the cloud service. This name is the DNS prefix + * name and can be used to access the cloud service. For example, if + * the cloud service name is MyService you could access the cloud + * service by calling: http://MyService.cloudapp.net. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private URI uri; + + /** + * Optional. The Service Management API request URI used to perform List + * Hosted Service Properties requests against the cloud service. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The Service Management API request URI used to perform List + * Hosted Service Properties requests against the cloud service. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceProperties.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceProperties.java new file mode 100644 index 0000000000000..56a7dffc55f9f --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceProperties.java @@ -0,0 +1,224 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.Calendar; +import java.util.HashMap; + +/** +* The properties that are assigned to the cloud service. +*/ +public class HostedServiceProperties { + private String affinityGroup; + + /** + * Optional. The affinity group with which this cloud service is associated, + * if any. If the service is associated with an affinity group, the + * Location element is not returned. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity group with which this cloud service is associated, + * if any. If the service is associated with an affinity group, the + * Location element is not returned. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private Calendar dateCreated; + + /** + * Optional. The date that the cloud service was created, in + * [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitHour]:[2DigitMinute]:[2DigitSecond]Z + * format. The date 2011-05-11T16:15:26Z is an example that could be + * returned by the DateCreated or DateLastModified elements. + * @return The DateCreated value. + */ + public Calendar getDateCreated() { + return this.dateCreated; + } + + /** + * Optional. The date that the cloud service was created, in + * [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitHour]:[2DigitMinute]:[2DigitSecond]Z + * format. The date 2011-05-11T16:15:26Z is an example that could be + * returned by the DateCreated or DateLastModified elements. + * @param dateCreatedValue The DateCreated value. + */ + public void setDateCreated(final Calendar dateCreatedValue) { + this.dateCreated = dateCreatedValue; + } + + private Calendar dateLastModified; + + /** + * Optional. The date that the cloud service was last updated, in + * [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitHour]:[2DigitMinute]:[2DigitSecond]Z + * format. The date 2011-05-11T16:15:26Z is an example that could be + * returned by the DateCreated or DateLastModified elements. + * @return The DateLastModified value. + */ + public Calendar getDateLastModified() { + return this.dateLastModified; + } + + /** + * Optional. The date that the cloud service was last updated, in + * [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitHour]:[2DigitMinute]:[2DigitSecond]Z + * format. The date 2011-05-11T16:15:26Z is an example that could be + * returned by the DateCreated or DateLastModified elements. + * @param dateLastModifiedValue The DateLastModified value. + */ + public void setDateLastModified(final Calendar dateLastModifiedValue) { + this.dateLastModified = dateLastModifiedValue; + } + + private String description; + + /** + * Optional. The description for the cloud service. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. The description for the cloud service. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum length + * of the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and it must start with a letter. + * Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum length + * of the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and it must start with a letter. + * Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private String label; + + /** + * Optional. The user-supplied name of the cloud service. This name can be + * used identify the service for your tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The user-supplied name of the cloud service. This name can be + * used identify the service for your tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The geo-location of the cloud service in Windows Azure, if the + * service is not associated with an affinity group. If a location has been + * specified, the AffinityGroup element is not returned. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location of the cloud service in Windows Azure, if the + * service is not associated with an affinity group. If a location has been + * specified, the AffinityGroup element is not returned. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private HostedServiceStatus status; + + /** + * Optional. The status of the cloud service. + * @return The Status value. + */ + public HostedServiceStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the cloud service. + * @param statusValue The Status value. + */ + public void setStatus(final HostedServiceStatus statusValue) { + this.status = statusValue; + } + + /** + * Initializes a new instance of the HostedServiceProperties class. + * + */ + public HostedServiceProperties() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceStatus.java new file mode 100644 index 0000000000000..2ed23cdcc9719 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceStatus.java @@ -0,0 +1,41 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The status of the cloud service. +*/ +public enum HostedServiceStatus { + Created, + + Creating, + + Deleting, + + Deleted, + + Changing, + + ResolvingDns, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceUpdateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceUpdateParameters.java new file mode 100644 index 0000000000000..2a36d3d356e28 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/HostedServiceUpdateParameters.java @@ -0,0 +1,123 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.HashMap; + +/** +* Parameters supplied to the Update Hosted Service operation. +*/ +public class HostedServiceUpdateParameters { + private String description; + + /** + * Optional. A description for the cloud service. The description may be up + * to 1024 characters in length. You must specify a value for at least one + * of Label or Description. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. A description for the cloud service. The description may be up + * to 1024 characters in length. You must specify a value for at least one + * of Label or Description. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum length + * of the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and it must start with a letter. + * Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended cloud service property. Each + * extended property must have a defined name and a value. You can have a + * maximum of 50 extended property name and value pairs. The maximum length + * of the name element is 64 characters, only alphanumeric characters and + * underscores are valid in the name, and it must start with a letter. + * Attempting to use other characters, starting with a non-letter + * character, or entering a name that is identical to that of another + * extended property owned by the same service will result in a status code + * 400 (Bad Request) error. Each extended property value has a maximum + * length of 255 characters. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private String label; + + /** + * Optional. A name for the cloud service. The name may be up to 100 + * characters in length. You must specify a value for at least one of Label + * or Description. It is recommended that the label be unique within the + * subscription. The name can be used identify the service for your + * tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. A name for the cloud service. The name may be up to 100 + * characters in length. You must specify a value for at least one of Label + * or Description. It is recommended that the label be unique within the + * subscription. The name can be used identify the service for your + * tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + /** + * Initializes a new instance of the HostedServiceUpdateParameters class. + * + */ + public HostedServiceUpdateParameters() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InputEndpoint.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InputEndpoint.java new file mode 100644 index 0000000000000..385230b219834 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InputEndpoint.java @@ -0,0 +1,210 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.InetAddress; + +/** +* Objects that provide input endpoint details. +*/ +public class InputEndpoint { + private Boolean enableDirectServerReturn; + + /** + * Optional. Specifies whether direct server return is enabled for the + * endpoint. + * @return The EnableDirectServerReturn value. + */ + public Boolean isEnableDirectServerReturn() { + return this.enableDirectServerReturn; + } + + /** + * Optional. Specifies whether direct server return is enabled for the + * endpoint. + * @param enableDirectServerReturnValue The EnableDirectServerReturn value. + */ + public void setEnableDirectServerReturn(final Boolean enableDirectServerReturnValue) { + this.enableDirectServerReturn = enableDirectServerReturnValue; + } + + private EndpointAcl endpointAcl; + + /** + * Optional. Specifies the list of access control rules for the endpoint. + * @return The EndpointAcl value. + */ + public EndpointAcl getEndpointAcl() { + return this.endpointAcl; + } + + /** + * Optional. Specifies the list of access control rules for the endpoint. + * @param endpointAclValue The EndpointAcl value. + */ + public void setEndpointAcl(final EndpointAcl endpointAclValue) { + this.endpointAcl = endpointAclValue; + } + + private String loadBalancedEndpointSetName; + + /** + * Optional. Specifies a name for a set of load-balanced endpoints. + * Specifying this name in multiple endpoints adds them all to the set. + * This element is only listed for Virtual Machine deployments. + * @return The LoadBalancedEndpointSetName value. + */ + public String getLoadBalancedEndpointSetName() { + return this.loadBalancedEndpointSetName; + } + + /** + * Optional. Specifies a name for a set of load-balanced endpoints. + * Specifying this name in multiple endpoints adds them all to the set. + * This element is only listed for Virtual Machine deployments. + * @param loadBalancedEndpointSetNameValue The LoadBalancedEndpointSetName + * value. + */ + public void setLoadBalancedEndpointSetName(final String loadBalancedEndpointSetNameValue) { + this.loadBalancedEndpointSetName = loadBalancedEndpointSetNameValue; + } + + private LoadBalancerProbe loadBalancerProbe; + + /** + * Optional. Contains properties that specify the endpoint settings which + * the Azure load balancer uses to monitor the availability of this virtual + * machine before forwarding traffic to the endpoint. + * @return The LoadBalancerProbe value. + */ + public LoadBalancerProbe getLoadBalancerProbe() { + return this.loadBalancerProbe; + } + + /** + * Optional. Contains properties that specify the endpoint settings which + * the Azure load balancer uses to monitor the availability of this virtual + * machine before forwarding traffic to the endpoint. + * @param loadBalancerProbeValue The LoadBalancerProbe value. + */ + public void setLoadBalancerProbe(final LoadBalancerProbe loadBalancerProbeValue) { + this.loadBalancerProbe = loadBalancerProbeValue; + } + + private Integer localPort; + + /** + * Optional. Specifies the internal port on which the virtual machine is + * listening to serve the endpoint. This element is only listed for Virtual + * Machine deployments. + * @return The LocalPort value. + */ + public Integer getLocalPort() { + return this.localPort; + } + + /** + * Optional. Specifies the internal port on which the virtual machine is + * listening to serve the endpoint. This element is only listed for Virtual + * Machine deployments. + * @param localPortValue The LocalPort value. + */ + public void setLocalPort(final Integer localPortValue) { + this.localPort = localPortValue; + } + + private String name; + + /** + * Optional. Specifies the name for the external endpoint. This element is + * only listed for Virtual Machine deployments. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name for the external endpoint. This element is + * only listed for Virtual Machine deployments. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private Integer port; + + /** + * Optional. The size of the role instance. + * @return The Port value. + */ + public Integer getPort() { + return this.port; + } + + /** + * Optional. The size of the role instance. + * @param portValue The Port value. + */ + public void setPort(final Integer portValue) { + this.port = portValue; + } + + private String protocol; + + /** + * Optional. Specifies the transport protocol for the endpoint. + * @return The Protocol value. + */ + public String getProtocol() { + return this.protocol; + } + + /** + * Optional. Specifies the transport protocol for the endpoint. + * @param protocolValue The Protocol value. + */ + public void setProtocol(final String protocolValue) { + this.protocol = protocolValue; + } + + private InetAddress virtualIPAddress; + + /** + * Optional. The virtual IP address of the role instance. + * @return The VirtualIPAddress value. + */ + public InetAddress getVirtualIPAddress() { + return this.virtualIPAddress; + } + + /** + * Optional. The virtual IP address of the role instance. + * @param virtualIPAddressValue The VirtualIPAddress value. + */ + public void setVirtualIPAddress(final InetAddress virtualIPAddressValue) { + this.virtualIPAddress = virtualIPAddressValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InputEndpointTransportProtocol.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InputEndpointTransportProtocol.java new file mode 100644 index 0000000000000..85d0558c2e567 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InputEndpointTransportProtocol.java @@ -0,0 +1,35 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the transport protocol for an endpoint. +*/ +public abstract class InputEndpointTransportProtocol { + public static final String TCP = "tcp"; + + public static final String UDP = "udp"; + + public static final String HTTP = "http"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InstanceEndpoint.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InstanceEndpoint.java new file mode 100644 index 0000000000000..6ab9197e30429 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/InstanceEndpoint.java @@ -0,0 +1,127 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.InetAddress; + +/** +* Objects that provide instance endpoint details. +*/ +public class InstanceEndpoint { + private Integer localPort; + + /** + * Optional. Specifies the internal port on which the virtual machine is + * listening to serve the endpoint. This element is only listed for Virtual + * Machine deployments. + * @return The LocalPort value. + */ + public Integer getLocalPort() { + return this.localPort; + } + + /** + * Optional. Specifies the internal port on which the virtual machine is + * listening to serve the endpoint. This element is only listed for Virtual + * Machine deployments. + * @param localPortValue The LocalPort value. + */ + public void setLocalPort(final Integer localPortValue) { + this.localPort = localPortValue; + } + + private String name; + + /** + * Optional. Specifies the name for the external endpoint. This element is + * only listed for Virtual Machine deployments. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name for the external endpoint. This element is + * only listed for Virtual Machine deployments. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private int port; + + /** + * Optional. The external port of the role instance endpoint. + * @return The Port value. + */ + public int getPort() { + return this.port; + } + + /** + * Optional. The external port of the role instance endpoint. + * @param portValue The Port value. + */ + public void setPort(final int portValue) { + this.port = portValue; + } + + private String protocol; + + /** + * Optional. Specifies the transport protocol for the endpoint. + * @return The Protocol value. + */ + public String getProtocol() { + return this.protocol; + } + + /** + * Optional. Specifies the transport protocol for the endpoint. + * @param protocolValue The Protocol value. + */ + public void setProtocol(final String protocolValue) { + this.protocol = protocolValue; + } + + private InetAddress virtualIPAddress; + + /** + * Optional. The Virtual IP of the role endpoint. + * @return The VirtualIPAddress value. + */ + public InetAddress getVirtualIPAddress() { + return this.virtualIPAddress; + } + + /** + * Optional. The Virtual IP of the role endpoint. + * @param virtualIPAddressValue The VirtualIPAddress value. + */ + public void setVirtualIPAddress(final InetAddress virtualIPAddressValue) { + this.virtualIPAddress = virtualIPAddressValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/LoadBalancerProbe.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/LoadBalancerProbe.java new file mode 100644 index 0000000000000..20e9fd5c39b59 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/LoadBalancerProbe.java @@ -0,0 +1,137 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Contains properties that specify the endpoint settings which the Azure load +* balancer uses to monitor the availability of this virtual machine before +* forwarding traffic to the endpoint. +*/ +public class LoadBalancerProbe { + private Integer intervalInSeconds; + + /** + * Optional. Specifies the interval for the load balancer probe in seconds. + * The minimum value is 5 seconds. If not specified, the default is 15 + * seconds. + * @return The IntervalInSeconds value. + */ + public Integer getIntervalInSeconds() { + return this.intervalInSeconds; + } + + /** + * Optional. Specifies the interval for the load balancer probe in seconds. + * The minimum value is 5 seconds. If not specified, the default is 15 + * seconds. + * @param intervalInSecondsValue The IntervalInSeconds value. + */ + public void setIntervalInSeconds(final Integer intervalInSecondsValue) { + this.intervalInSeconds = intervalInSecondsValue; + } + + private String path; + + /** + * Optional. Specifies the relative path name to inspect to determine the + * virtual machine availability status. If Protocol is set to TCP, this + * value must be NULL. + * @return The Path value. + */ + public String getPath() { + return this.path; + } + + /** + * Optional. Specifies the relative path name to inspect to determine the + * virtual machine availability status. If Protocol is set to TCP, this + * value must be NULL. + * @param pathValue The Path value. + */ + public void setPath(final String pathValue) { + this.path = pathValue; + } + + private int port; + + /** + * Optional. Specifies the port to use to inspect the virtual machine + * availability status. + * @return The Port value. + */ + public int getPort() { + return this.port; + } + + /** + * Optional. Specifies the port to use to inspect the virtual machine + * availability status. + * @param portValue The Port value. + */ + public void setPort(final int portValue) { + this.port = portValue; + } + + private LoadBalancerProbeTransportProtocol protocol; + + /** + * Optional. Specifies the protocol to use to inspect the virtual machine + * availability status. + * @return The Protocol value. + */ + public LoadBalancerProbeTransportProtocol getProtocol() { + return this.protocol; + } + + /** + * Optional. Specifies the protocol to use to inspect the virtual machine + * availability status. + * @param protocolValue The Protocol value. + */ + public void setProtocol(final LoadBalancerProbeTransportProtocol protocolValue) { + this.protocol = protocolValue; + } + + private Integer timeoutInSeconds; + + /** + * Optional. Specifies the timeout for the load balancer probe in seconds. + * The minimum value is 11 seconds. If not specified, the default is 31 + * seconds. + * @return The TimeoutInSeconds value. + */ + public Integer getTimeoutInSeconds() { + return this.timeoutInSeconds; + } + + /** + * Optional. Specifies the timeout for the load balancer probe in seconds. + * The minimum value is 11 seconds. If not specified, the default is 31 + * seconds. + * @param timeoutInSecondsValue The TimeoutInSeconds value. + */ + public void setTimeoutInSeconds(final Integer timeoutInSecondsValue) { + this.timeoutInSeconds = timeoutInSecondsValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/LoadBalancerProbeTransportProtocol.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/LoadBalancerProbeTransportProtocol.java new file mode 100644 index 0000000000000..291695251c5d0 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/LoadBalancerProbeTransportProtocol.java @@ -0,0 +1,34 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the protocol to use when inspecting the virtual machine +* availability status. +*/ +public enum LoadBalancerProbeTransportProtocol { + Tcp, + + Http, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OSVirtualHardDisk.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OSVirtualHardDisk.java new file mode 100644 index 0000000000000..b022f153c9b34 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OSVirtualHardDisk.java @@ -0,0 +1,150 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; + +/** +* The parameters Azure uses to create the operating system disk for the virtual +* machine. +*/ +public class OSVirtualHardDisk { + private VirtualHardDiskHostCaching hostCaching; + + /** + * Optional. Specifies the platform caching behavior of the operating system + * disk blob for read/write efficiency. + * @return The HostCaching value. + */ + public VirtualHardDiskHostCaching getHostCaching() { + return this.hostCaching; + } + + /** + * Optional. Specifies the platform caching behavior of the operating system + * disk blob for read/write efficiency. + * @param hostCachingValue The HostCaching value. + */ + public void setHostCaching(final VirtualHardDiskHostCaching hostCachingValue) { + this.hostCaching = hostCachingValue; + } + + private String label; + + /** + * Optional. Specifies the friendly name of an operating system image in the + * image repository. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Specifies the friendly name of an operating system image in the + * image repository. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private URI mediaLink; + + /** + * Optional. Specifies the location of the operating system disk in Azure + * storage. + * @return The MediaLink value. + */ + public URI getMediaLink() { + return this.mediaLink; + } + + /** + * Optional. Specifies the location of the operating system disk in Azure + * storage. + * @param mediaLinkValue The MediaLink value. + */ + public void setMediaLink(final URI mediaLinkValue) { + this.mediaLink = mediaLinkValue; + } + + private String name; + + /** + * Optional. Specifies the name of an operating system image in the image + * repository. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name of an operating system image in the image + * repository. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystem; + + /** + * Optional. The operating system running in the virtual machine. + * @return The OperatingSystem value. + */ + public String getOperatingSystem() { + return this.operatingSystem; + } + + /** + * Optional. The operating system running in the virtual machine. + * @param operatingSystemValue The OperatingSystem value. + */ + public void setOperatingSystem(final String operatingSystemValue) { + this.operatingSystem = operatingSystemValue; + } + + private String sourceImageName; + + /** + * Optional. Specifies the name of the source image that was used to + * provision the virtual machine. + * @return The SourceImageName value. + */ + public String getSourceImageName() { + return this.sourceImageName; + } + + /** + * Optional. Specifies the name of the source image that was used to + * provision the virtual machine. + * @param sourceImageNameValue The SourceImageName value. + */ + public void setSourceImageName(final String sourceImageNameValue) { + this.sourceImageName = sourceImageNameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemFamilies.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemFamilies.java new file mode 100644 index 0000000000000..a61e7c2adc884 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemFamilies.java @@ -0,0 +1,35 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Describes an operating system family. +*/ +public abstract class OperatingSystemFamilies { + public static final int WINDOWSSERVER2008SP2 = 1; + + public static final int WINDOWSSERVER2008R2 = 2; + + public static final int WINDOWSSERVER2012 = 3; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemListFamiliesResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemListFamiliesResponse.java new file mode 100644 index 0000000000000..e108b48992b6a --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemListFamiliesResponse.java @@ -0,0 +1,269 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Operating System Families operation response. +*/ +public class OperatingSystemListFamiliesResponse extends OperationResponse implements Iterable { + private ArrayList operatingSystemFamilies; + + /** + * Optional. The operating system families that are valid for your + * subscription. + * @return The OperatingSystemFamilies value. + */ + public ArrayList getOperatingSystemFamilies() { + return this.operatingSystemFamilies; + } + + /** + * Optional. The operating system families that are valid for your + * subscription. + * @param operatingSystemFamiliesValue The OperatingSystemFamilies value. + */ + public void setOperatingSystemFamilies(final ArrayList operatingSystemFamiliesValue) { + this.operatingSystemFamilies = operatingSystemFamiliesValue; + } + + /** + * Initializes a new instance of the OperatingSystemListFamiliesResponse + * class. + * + */ + public OperatingSystemListFamiliesResponse() { + super(); + this.operatingSystemFamilies = new ArrayList(); + } + + /** + * Gets the sequence of OperatingSystemFamilies. + * + */ + public Iterator iterator() { + return this.getOperatingSystemFamilies().iterator(); + } + + /** + * An operating system that is valid for your subscription. + */ + public static class OperatingSystem { + private boolean isActive; + + /** + * Optional. Indicates whether this operating system version is + * currently active for running a service. If an operating system + * version is active, you can manually configure your service to run on + * that version. An operating system version may be inactive for one of + * two reasons: 1. It is not yet active as it is in the process of + * being rolled out to Azure data centers. If your service is + * configured to use auto-upgrade, it will be upgraded to the new + * operating system version during the rollout. If you are manually + * configuring your operating system version, you can upgrade to the + * latest version once it becomes active. 2. It is no longer supported + * for running a service. In this case you will either need to manually + * configure your service to run on a newer version, or configure your + * service to use auto-upgrade to manage operating system upgrades. + * @return The IsActive value. + */ + public boolean isActive() { + return this.isActive; + } + + /** + * Optional. Indicates whether this operating system version is + * currently active for running a service. If an operating system + * version is active, you can manually configure your service to run on + * that version. An operating system version may be inactive for one of + * two reasons: 1. It is not yet active as it is in the process of + * being rolled out to Azure data centers. If your service is + * configured to use auto-upgrade, it will be upgraded to the new + * operating system version during the rollout. If you are manually + * configuring your operating system version, you can upgrade to the + * latest version once it becomes active. 2. It is no longer supported + * for running a service. In this case you will either need to manually + * configure your service to run on a newer version, or configure your + * service to use auto-upgrade to manage operating system upgrades. + * @param isActiveValue The IsActive value. + */ + public void setIsActive(final boolean isActiveValue) { + this.isActive = isActiveValue; + } + + private boolean isDefault; + + /** + * Optional. Indicates whether this operating system version is the + * default version for a service that has not otherwise specified a + * particular version. The default operating system version is applied + * to services that are configured for auto-upgrade. An operating + * system family has exactly one default operating system version at + * any given time, for which the IsDefault element is set to true; for + * all other versions, IsDefault is set to false. + * @return The IsDefault value. + */ + public boolean isDefault() { + return this.isDefault; + } + + /** + * Optional. Indicates whether this operating system version is the + * default version for a service that has not otherwise specified a + * particular version. The default operating system version is applied + * to services that are configured for auto-upgrade. An operating + * system family has exactly one default operating system version at + * any given time, for which the IsDefault element is set to true; for + * all other versions, IsDefault is set to false. + * @param isDefaultValue The IsDefault value. + */ + public void setIsDefault(final boolean isDefaultValue) { + this.isDefault = isDefaultValue; + } + + private String label; + + /** + * Optional. The label of the operating system version. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The label of the operating system version. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String version; + + /** + * Optional. The operating system version. This value corresponds to the + * configuration value for specifying that your service is to run on a + * particular version of the Azure guest operating system. See + * Configuring Settings for the Windows Azure Guest OS for additional + * details. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. The operating system version. This value corresponds to the + * configuration value for specifying that your service is to run on a + * particular version of the Azure guest operating system. See + * Configuring Settings for the Windows Azure Guest OS for additional + * details. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } + } + + /** + * An operating system family that is valid for your subscription. + */ + public static class OperatingSystemFamily { + private String label; + + /** + * Optional. The label of the operating system family. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The label of the operating system family. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private int name; + + /** + * Optional. Indicates which operating system family this version + * belongs to. A value of 1 corresponds to the Azure guest operating + * system that is substantially compatible with Windows Server 2008 + * SP2. A value of 2 corresponds to the Azure guest operating system + * that is substantially compatible with Windows Server 2008 R2. + * @return The Name value. + */ + public int getName() { + return this.name; + } + + /** + * Optional. Indicates which operating system family this version + * belongs to. A value of 1 corresponds to the Azure guest operating + * system that is substantially compatible with Windows Server 2008 + * SP2. A value of 2 corresponds to the Azure guest operating system + * that is substantially compatible with Windows Server 2008 R2. + * @param nameValue The Name value. + */ + public void setName(final int nameValue) { + this.name = nameValue; + } + + private ArrayList operatingSystems; + + /** + * Optional. The available operating systems in your subscription + * belonging to this family. + * @return The OperatingSystems value. + */ + public ArrayList getOperatingSystems() { + return this.operatingSystems; + } + + /** + * Optional. The available operating systems in your subscription + * belonging to this family. + * @param operatingSystemsValue The OperatingSystems value. + */ + public void setOperatingSystems(final ArrayList operatingSystemsValue) { + this.operatingSystems = operatingSystemsValue; + } + + /** + * Initializes a new instance of the OperatingSystemFamily class. + * + */ + public OperatingSystemFamily() { + this.operatingSystems = new ArrayList(); + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemListResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemListResponse.java new file mode 100644 index 0000000000000..bc46a3326873f --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/OperatingSystemListResponse.java @@ -0,0 +1,233 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Operating Systems operation response. +*/ +public class OperatingSystemListResponse extends OperationResponse implements Iterable { + private ArrayList operatingSystems; + + /** + * Optional. The operating systems that are valid for your subscription. + * @return The OperatingSystems value. + */ + public ArrayList getOperatingSystems() { + return this.operatingSystems; + } + + /** + * Optional. The operating systems that are valid for your subscription. + * @param operatingSystemsValue The OperatingSystems value. + */ + public void setOperatingSystems(final ArrayList operatingSystemsValue) { + this.operatingSystems = operatingSystemsValue; + } + + /** + * Initializes a new instance of the OperatingSystemListResponse class. + * + */ + public OperatingSystemListResponse() { + super(); + this.operatingSystems = new ArrayList(); + } + + /** + * Gets the sequence of OperatingSystems. + * + */ + public Iterator iterator() { + return this.getOperatingSystems().iterator(); + } + + /** + * An operating system that is valid for your subscription. + */ + public static class OperatingSystem { + private int family; + + /** + * Optional. Indicates which operating system family this version + * belongs to. A value of 1 corresponds to the Azure guest operating + * system that is substantially compatible with Windows Server 2008 + * SP2. A value of 2 corresponds to the Azure guest operating system + * that is substantially compatible with Windows Server 2008 R2. + * @return The Family value. + */ + public int getFamily() { + return this.family; + } + + /** + * Optional. Indicates which operating system family this version + * belongs to. A value of 1 corresponds to the Azure guest operating + * system that is substantially compatible with Windows Server 2008 + * SP2. A value of 2 corresponds to the Azure guest operating system + * that is substantially compatible with Windows Server 2008 R2. + * @param familyValue The Family value. + */ + public void setFamily(final int familyValue) { + this.family = familyValue; + } + + private String familyLabel; + + /** + * Optional. The label of the operating system family. + * @return The FamilyLabel value. + */ + public String getFamilyLabel() { + return this.familyLabel; + } + + /** + * Optional. The label of the operating system family. + * @param familyLabelValue The FamilyLabel value. + */ + public void setFamilyLabel(final String familyLabelValue) { + this.familyLabel = familyLabelValue; + } + + private boolean isActive; + + /** + * Optional. Indicates whether this operating system version is + * currently active for running a service. If an operating system + * version is active, you can manually configure your service to run on + * that version. An operating system version may be inactive for one of + * two reasons: 1. It is not yet active as it is in the process of + * being rolled out to Azure data centers. If your service is + * configured to use auto-upgrade, it will be upgraded to the new + * operating system version during the rollout. If you are manually + * configuring your operating system version, you can upgrade to the + * latest version once it becomes active. 2. It is no longer supported + * for running a service. In this case you will either need to manually + * configure your service to run on a newer version, or configure your + * service to use auto-upgrade to manage operating system upgrades. + * @return The IsActive value. + */ + public boolean isActive() { + return this.isActive; + } + + /** + * Optional. Indicates whether this operating system version is + * currently active for running a service. If an operating system + * version is active, you can manually configure your service to run on + * that version. An operating system version may be inactive for one of + * two reasons: 1. It is not yet active as it is in the process of + * being rolled out to Azure data centers. If your service is + * configured to use auto-upgrade, it will be upgraded to the new + * operating system version during the rollout. If you are manually + * configuring your operating system version, you can upgrade to the + * latest version once it becomes active. 2. It is no longer supported + * for running a service. In this case you will either need to manually + * configure your service to run on a newer version, or configure your + * service to use auto-upgrade to manage operating system upgrades. + * @param isActiveValue The IsActive value. + */ + public void setIsActive(final boolean isActiveValue) { + this.isActive = isActiveValue; + } + + private boolean isDefault; + + /** + * Optional. Indicates whether this operating system version is the + * default version for a service that has not otherwise specified a + * particular version. The default operating system version is applied + * to services that are configured for auto-upgrade. An operating + * system family has exactly one default operating system version at + * any given time, for which the IsDefault element is set to true; for + * all other versions, IsDefault is set to false. + * @return The IsDefault value. + */ + public boolean isDefault() { + return this.isDefault; + } + + /** + * Optional. Indicates whether this operating system version is the + * default version for a service that has not otherwise specified a + * particular version. The default operating system version is applied + * to services that are configured for auto-upgrade. An operating + * system family has exactly one default operating system version at + * any given time, for which the IsDefault element is set to true; for + * all other versions, IsDefault is set to false. + * @param isDefaultValue The IsDefault value. + */ + public void setIsDefault(final boolean isDefaultValue) { + this.isDefault = isDefaultValue; + } + + private String label; + + /** + * Optional. The label of the operating system version. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The label of the operating system version. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String version; + + /** + * Optional. The operating system version. This value corresponds to the + * configuration value for specifying that your service is to run on a + * particular version of the Azure guest operating system. See + * Configuring Settings for the Windows Azure Guest OS for additional + * details. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. The operating system version. This value corresponds to the + * configuration value for specifying that your service is to run on a + * particular version of the Azure guest operating system. See + * Configuring Settings for the Windows Azure Guest OS for additional + * details. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PersistentVMDowntime.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PersistentVMDowntime.java new file mode 100644 index 0000000000000..a14a973a0339e --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PersistentVMDowntime.java @@ -0,0 +1,86 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.Calendar; + +/** +* Contains information about when the virtual machine has been started and +* stopped. +*/ +public class PersistentVMDowntime { + private Calendar endTime; + + /** + * Optional. The time that the virtual machine was stopped. + * @return The EndTime value. + */ + public Calendar getEndTime() { + return this.endTime; + } + + /** + * Optional. The time that the virtual machine was stopped. + * @param endTimeValue The EndTime value. + */ + public void setEndTime(final Calendar endTimeValue) { + this.endTime = endTimeValue; + } + + private Calendar startTime; + + /** + * Optional. The time that the virtual machine was started. + * @return The StartTime value. + */ + public Calendar getStartTime() { + return this.startTime; + } + + /** + * Optional. The time that the virtual machine was started. + * @param startTimeValue The StartTime value. + */ + public void setStartTime(final Calendar startTimeValue) { + this.startTime = startTimeValue; + } + + private String status; + + /** + * Optional. The status of the virtual machine. + * @return The Status value. + */ + public String getStatus() { + return this.status; + } + + /** + * Optional. The status of the virtual machine. + * @param statusValue The Status value. + */ + public void setStatus(final String statusValue) { + this.status = statusValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PostCaptureAction.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PostCaptureAction.java new file mode 100644 index 0000000000000..a0aa364b460d4 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PostCaptureAction.java @@ -0,0 +1,40 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the action that is performed after the capture operation finishes. +*/ +public enum PostCaptureAction { + /** + * Causes the virtual machine to be deleted after the image has been captured + */ + Delete, + + /** + * Causes the virtual machine to be redeployed after the image is captured + * by using the specified information in ProvisioningConfiguration. + */ + Reprovision, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PostShutdownAction.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PostShutdownAction.java new file mode 100644 index 0000000000000..a69476c9bb077 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/PostShutdownAction.java @@ -0,0 +1,30 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +public enum PostShutdownAction { + Stopped, + + StoppedDeallocated, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionConfigurationStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionConfigurationStatus.java new file mode 100644 index 0000000000000..752bbde33a7cd --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionConfigurationStatus.java @@ -0,0 +1,211 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; +import java.util.Calendar; + +/** +* The status information of the settings passed to the Resource Extension. +*/ +public class ResourceExtensionConfigurationStatus { + private Integer code; + + /** + * Optional. Integer status code from the result of applying the + * configuration settings. + * @return The Code value. + */ + public Integer getCode() { + return this.code; + } + + /** + * Optional. Integer status code from the result of applying the + * configuration settings. + * @param codeValue The Code value. + */ + public void setCode(final Integer codeValue) { + this.code = codeValue; + } + + private Calendar configurationAppliedTime; + + /** + * Optional. UTC time at which the configuration was applied. + * @return The ConfigurationAppliedTime value. + */ + public Calendar getConfigurationAppliedTime() { + return this.configurationAppliedTime; + } + + /** + * Optional. UTC time at which the configuration was applied. + * @param configurationAppliedTimeValue The ConfigurationAppliedTime value. + */ + public void setConfigurationAppliedTime(final Calendar configurationAppliedTimeValue) { + this.configurationAppliedTime = configurationAppliedTimeValue; + } + + private GuestAgentFormattedMessage formattedMessage; + + /** + * Optional. This object encapsulates a formatted localized status message. + * @return The FormattedMessage value. + */ + public GuestAgentFormattedMessage getFormattedMessage() { + return this.formattedMessage; + } + + /** + * Optional. This object encapsulates a formatted localized status message. + * @param formattedMessageValue The FormattedMessage value. + */ + public void setFormattedMessage(final GuestAgentFormattedMessage formattedMessageValue) { + this.formattedMessage = formattedMessageValue; + } + + private GuestAgentMessage message; + + /** + * Optional. This object encapsulates a localized status message. + * @return The Message value. + */ + public GuestAgentMessage getMessage() { + return this.message; + } + + /** + * Optional. This object encapsulates a localized status message. + * @param messageValue The Message value. + */ + public void setMessage(final GuestAgentMessage messageValue) { + this.message = messageValue; + } + + private String name; + + /** + * Optional. Name of the settings passed to the Resource Extension. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Name of the settings passed to the Resource Extension. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operation; + + /** + * Optional. Operation executed by the Resource Extension for the settings + * passed to it. + * @return The Operation value. + */ + public String getOperation() { + return this.operation; + } + + /** + * Optional. Operation executed by the Resource Extension for the settings + * passed to it. + * @param operationValue The Operation value. + */ + public void setOperation(final String operationValue) { + this.operation = operationValue; + } + + private String status; + + /** + * Optional. The status of the resourse extension, containing values like + * Transitioning, Error, Success, or Warning. + * @return The Status value. + */ + public String getStatus() { + return this.status; + } + + /** + * Optional. The status of the resourse extension, containing values like + * Transitioning, Error, Success, or Warning. + * @param statusValue The Status value. + */ + public void setStatus(final String statusValue) { + this.status = statusValue; + } + + private ArrayList subStatusList; + + /** + * Optional. List of substatus objects which contain additional status + * information reported by the Resource Extension. + * @return The SubStatusList value. + */ + public ArrayList getSubStatusList() { + return this.subStatusList; + } + + /** + * Optional. List of substatus objects which contain additional status + * information reported by the Resource Extension. + * @param subStatusListValue The SubStatusList value. + */ + public void setSubStatusList(final ArrayList subStatusListValue) { + this.subStatusList = subStatusListValue; + } + + private Calendar timestamp; + + /** + * Optional. UTC time at which the status was reported. + * @return The Timestamp value. + */ + public Calendar getTimestamp() { + return this.timestamp; + } + + /** + * Optional. UTC time at which the status was reported. + * @param timestampValue The Timestamp value. + */ + public void setTimestamp(final Calendar timestampValue) { + this.timestamp = timestampValue; + } + + /** + * Initializes a new instance of the ResourceExtensionConfigurationStatus + * class. + * + */ + public ResourceExtensionConfigurationStatus() { + this.subStatusList = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionConfigurationStatusTypes.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionConfigurationStatusTypes.java new file mode 100644 index 0000000000000..c961b80453f8e --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionConfigurationStatusTypes.java @@ -0,0 +1,38 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The status of the resource extension configuration, containing values like +* Transitioning, Error, Success, or Warning. +*/ +public abstract class ResourceExtensionConfigurationStatusTypes { + public static final String TRANSITIONING = "Transitioning"; + + public static final String ERROR = "Error"; + + public static final String SUCCESS = "Success"; + + public static final String WARNING = "Warning"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionParameterValue.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionParameterValue.java new file mode 100644 index 0000000000000..f3c9affc0bedf --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionParameterValue.java @@ -0,0 +1,89 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the key, value, and type of the parameter. +*/ +public class ResourceExtensionParameterValue { + private String key; + + /** + * Optional. The key of the parameter. + * @return The Key value. + */ + public String getKey() { + return this.key; + } + + /** + * Optional. The key of the parameter. + * @param keyValue The Key value. + */ + public void setKey(final String keyValue) { + this.key = keyValue; + } + + private String type; + + /** + * Optional. Optional. Public | Private. If this value is set to Private, + * the parameter will not be returned by Get Deployment. You can only + * specify one public parameter and one private parameter for a maximum of + * two parameters. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. Optional. Public | Private. If this value is set to Private, + * the parameter will not be returned by Get Deployment. You can only + * specify one public parameter and one private parameter for a maximum of + * two parameters. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + + private String value; + + /** + * Optional. The value of the parameter. + * @return The Value value. + */ + public String getValue() { + return this.value; + } + + /** + * Optional. The value of the parameter. + * @param valueValue The Value value. + */ + public void setValue(final String valueValue) { + this.value = valueValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionReference.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionReference.java new file mode 100644 index 0000000000000..dc0c97a5323a4 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionReference.java @@ -0,0 +1,163 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Specifies the properties of a resource extension that should be installed on +* the Virtual Machine. +*/ +public class ResourceExtensionReference { + private String name; + + /** + * Optional. Specifies the name of the resource extension. You can use List + * Resource Extensions to find the names of available resource extensions. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name of the resource extension. You can use List + * Resource Extensions to find the names of available resource extensions. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String publisher; + + /** + * Optional. Specifies the name of the publisher who created the resource + * extension. You can use List Resource Extensions to find the publisher + * name of a resource extension. + * @return The Publisher value. + */ + public String getPublisher() { + return this.publisher; + } + + /** + * Optional. Specifies the name of the publisher who created the resource + * extension. You can use List Resource Extensions to find the publisher + * name of a resource extension. + * @param publisherValue The Publisher value. + */ + public void setPublisher(final String publisherValue) { + this.publisher = publisherValue; + } + + private String referenceName; + + /** + * Optional. Specifies the reference name of the resource extension. + * @return The ReferenceName value. + */ + public String getReferenceName() { + return this.referenceName; + } + + /** + * Optional. Specifies the reference name of the resource extension. + * @param referenceNameValue The ReferenceName value. + */ + public void setReferenceName(final String referenceNameValue) { + this.referenceName = referenceNameValue; + } + + private ArrayList resourceExtensionParameterValues; + + /** + * Optional. Contains a collection of parameters that are passed to the + * resource extension when it is installed. + * @return The ResourceExtensionParameterValues value. + */ + public ArrayList getResourceExtensionParameterValues() { + return this.resourceExtensionParameterValues; + } + + /** + * Optional. Contains a collection of parameters that are passed to the + * resource extension when it is installed. + * @param resourceExtensionParameterValuesValue The + * ResourceExtensionParameterValues value. + */ + public void setResourceExtensionParameterValues(final ArrayList resourceExtensionParameterValuesValue) { + this.resourceExtensionParameterValues = resourceExtensionParameterValuesValue; + } + + private String state; + + /** + * Optional. Specifies the state of the resource extension.Possible values + * are: Enable | Disable. The default value is Enable. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Specifies the state of the resource extension.Possible values + * are: Enable | Disable. The default value is Enable. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private String version; + + /** + * Optional. Specifies the version of the resource extension. You can use + * List Resource Extension Versions to find the version of the resource + * extension. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. Specifies the version of the resource extension. You can use + * List Resource Extension Versions to find the version of the resource + * extension. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } + + /** + * Initializes a new instance of the ResourceExtensionReference class. + * + */ + public ResourceExtensionReference() { + this.resourceExtensionParameterValues = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionStatus.java new file mode 100644 index 0000000000000..825e52fce03b0 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionStatus.java @@ -0,0 +1,163 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Optional. The status information of a specific Resource Extension. +*/ +public class ResourceExtensionStatus { + private Integer code; + + /** + * Optional. Status code sent by the Resource Extension. + * @return The Code value. + */ + public Integer getCode() { + return this.code; + } + + /** + * Optional. Status code sent by the Resource Extension. + * @param codeValue The Code value. + */ + public void setCode(final Integer codeValue) { + this.code = codeValue; + } + + private ResourceExtensionConfigurationStatus extensionSettingStatus; + + /** + * Optional. This object encapsulates the extension setting status for the + * Resource Extension. + * @return The ExtensionSettingStatus value. + */ + public ResourceExtensionConfigurationStatus getExtensionSettingStatus() { + return this.extensionSettingStatus; + } + + /** + * Optional. This object encapsulates the extension setting status for the + * Resource Extension. + * @param extensionSettingStatusValue The ExtensionSettingStatus value. + */ + public void setExtensionSettingStatus(final ResourceExtensionConfigurationStatus extensionSettingStatusValue) { + this.extensionSettingStatus = extensionSettingStatusValue; + } + + private GuestAgentFormattedMessage formattedMessage; + + /** + * Optional. This object encapsulates a formatted localized status message + * from the Resource Extension. + * @return The FormattedMessage value. + */ + public GuestAgentFormattedMessage getFormattedMessage() { + return this.formattedMessage; + } + + /** + * Optional. This object encapsulates a formatted localized status message + * from the Resource Extension. + * @param formattedMessageValue The FormattedMessage value. + */ + public void setFormattedMessage(final GuestAgentFormattedMessage formattedMessageValue) { + this.formattedMessage = formattedMessageValue; + } + + private String handlerName; + + /** + * Optional. Name of the Resource Extension. + * @return The HandlerName value. + */ + public String getHandlerName() { + return this.handlerName; + } + + /** + * Optional. Name of the Resource Extension. + * @param handlerNameValue The HandlerName value. + */ + public void setHandlerName(final String handlerNameValue) { + this.handlerName = handlerNameValue; + } + + private GuestAgentMessage message; + + /** + * Optional. This object encapsulates a localized status message from the + * Guest Agent. + * @return The Message value. + */ + public GuestAgentMessage getMessage() { + return this.message; + } + + /** + * Optional. This object encapsulates a localized status message from the + * Guest Agent. + * @param messageValue The Message value. + */ + public void setMessage(final GuestAgentMessage messageValue) { + this.message = messageValue; + } + + private String status; + + /** + * Optional. The resource extension status, which can be "Installing", + * "Ready", "NotReady", or "Unresponsive". + * @return The Status value. + */ + public String getStatus() { + return this.status; + } + + /** + * Optional. The resource extension status, which can be "Installing", + * "Ready", "NotReady", or "Unresponsive". + * @param statusValue The Status value. + */ + public void setStatus(final String statusValue) { + this.status = statusValue; + } + + private String version; + + /** + * Optional. Version of the Resource Extension. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. Version of the Resource Extension. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionStatusTypes.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionStatusTypes.java new file mode 100644 index 0000000000000..23d6a7b22e0dd --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionStatusTypes.java @@ -0,0 +1,38 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The resource extension status, which can be "Installing", "Ready", +* "NotReady", or "Unresponsive". +*/ +public abstract class ResourceExtensionStatusTypes { + public static final String INSTALLING = "Installing"; + + public static final String READY = "Ready"; + + public static final String NORREADY = "NorReady"; + + public static final String UNRESPONSIVE = "Unresponsive"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionSubStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionSubStatus.java new file mode 100644 index 0000000000000..1c606ff100542 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionSubStatus.java @@ -0,0 +1,124 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* A substatus object containing additional status information reported by the +* Resource Extension. +*/ +public class ResourceExtensionSubStatus { + private Integer code; + + /** + * Optional. Integer status code from the result of applying the substatus + * settings. + * @return The Code value. + */ + public Integer getCode() { + return this.code; + } + + /** + * Optional. Integer status code from the result of applying the substatus + * settings. + * @param codeValue The Code value. + */ + public void setCode(final Integer codeValue) { + this.code = codeValue; + } + + private GuestAgentFormattedMessage formattedMessage; + + /** + * Optional. This object encapsulates a formatted localized status message. + * @return The FormattedMessage value. + */ + public GuestAgentFormattedMessage getFormattedMessage() { + return this.formattedMessage; + } + + /** + * Optional. This object encapsulates a formatted localized status message. + * @param formattedMessageValue The FormattedMessage value. + */ + public void setFormattedMessage(final GuestAgentFormattedMessage formattedMessageValue) { + this.formattedMessage = formattedMessageValue; + } + + private GuestAgentMessage message; + + /** + * Optional. This object encapsulates a localized status message. + * @return The Message value. + */ + public GuestAgentMessage getMessage() { + return this.message; + } + + /** + * Optional. This object encapsulates a localized status message. + * @param messageValue The Message value. + */ + public void setMessage(final GuestAgentMessage messageValue) { + this.message = messageValue; + } + + private String name; + + /** + * Optional. A name for the substatus. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. A name for the substatus. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String status; + + /** + * Optional. The resource extension substatus, containing values like + * Transitioning, Error, Success, or Warning. + * @return The Status value. + */ + public String getStatus() { + return this.status; + } + + /** + * Optional. The resource extension substatus, containing values like + * Transitioning, Error, Success, or Warning. + * @param statusValue The Status value. + */ + public void setStatus(final String statusValue) { + this.status = statusValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionSubStatusTypes.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionSubStatusTypes.java new file mode 100644 index 0000000000000..40500b80ed523 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ResourceExtensionSubStatusTypes.java @@ -0,0 +1,38 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The resource extension substatus, containing values like Transitioning, +* Error, Success, or Warning. +*/ +public abstract class ResourceExtensionSubStatusTypes { + public static final String TRANSITIONING = "Transitioning"; + + public static final String ERROR = "Error"; + + public static final String SUCCESS = "Success"; + + public static final String WARNING = "Warning"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/Role.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/Role.java new file mode 100644 index 0000000000000..149aac78dd8dd --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/Role.java @@ -0,0 +1,305 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Details of a role in a deployment. +*/ +public class Role { + private String availabilitySetName; + + /** + * Optional. The name of the role. + * @return The AvailabilitySetName value. + */ + public String getAvailabilitySetName() { + return this.availabilitySetName; + } + + /** + * Optional. The name of the role. + * @param availabilitySetNameValue The AvailabilitySetName value. + */ + public void setAvailabilitySetName(final String availabilitySetNameValue) { + this.availabilitySetName = availabilitySetNameValue; + } + + private ArrayList configurationSets; + + /** + * Optional. A collection of values that represents system or application + * configuration settings. + * @return The ConfigurationSets value. + */ + public ArrayList getConfigurationSets() { + return this.configurationSets; + } + + /** + * Optional. A collection of values that represents system or application + * configuration settings. + * @param configurationSetsValue The ConfigurationSets value. + */ + public void setConfigurationSets(final ArrayList configurationSetsValue) { + this.configurationSets = configurationSetsValue; + } + + private ArrayList dataVirtualHardDisks; + + /** + * Optional. Contains the parameters Azure uses to create a data disk for a + * virtual machine. + * @return The DataVirtualHardDisks value. + */ + public ArrayList getDataVirtualHardDisks() { + return this.dataVirtualHardDisks; + } + + /** + * Optional. Contains the parameters Azure uses to create a data disk for a + * virtual machine. + * @param dataVirtualHardDisksValue The DataVirtualHardDisks value. + */ + public void setDataVirtualHardDisks(final ArrayList dataVirtualHardDisksValue) { + this.dataVirtualHardDisks = dataVirtualHardDisksValue; + } + + private String defaultWinRmCertificateThumbprint; + + /** + * Optional. The read-only thumbprint of the certificate that is used with + * the HTTPS listener for WinRM. + * @return The DefaultWinRmCertificateThumbprint value. + */ + public String getDefaultWinRmCertificateThumbprint() { + return this.defaultWinRmCertificateThumbprint; + } + + /** + * Optional. The read-only thumbprint of the certificate that is used with + * the HTTPS listener for WinRM. + * @param defaultWinRmCertificateThumbprintValue The + * DefaultWinRmCertificateThumbprint value. + */ + public void setDefaultWinRmCertificateThumbprint(final String defaultWinRmCertificateThumbprintValue) { + this.defaultWinRmCertificateThumbprint = defaultWinRmCertificateThumbprintValue; + } + + private String label; + + /** + * Optional. The friendly name for the role. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly name for the role. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String oSVersion; + + /** + * Optional. The version of the operating system on which the role instances + * are running. + * @return The OSVersion value. + */ + public String getOSVersion() { + return this.oSVersion; + } + + /** + * Optional. The version of the operating system on which the role instances + * are running. + * @param oSVersionValue The OSVersion value. + */ + public void setOSVersion(final String oSVersionValue) { + this.oSVersion = oSVersionValue; + } + + private OSVirtualHardDisk oSVirtualHardDisk; + + /** + * Optional. Contains the parameters Azure uses to create the operating + * system disk for the virtual machine. + * @return The OSVirtualHardDisk value. + */ + public OSVirtualHardDisk getOSVirtualHardDisk() { + return this.oSVirtualHardDisk; + } + + /** + * Optional. Contains the parameters Azure uses to create the operating + * system disk for the virtual machine. + * @param oSVirtualHardDiskValue The OSVirtualHardDisk value. + */ + public void setOSVirtualHardDisk(final OSVirtualHardDisk oSVirtualHardDiskValue) { + this.oSVirtualHardDisk = oSVirtualHardDiskValue; + } + + private Boolean provisionGuestAgent; + + /** + * Optional. Indicates whether the WindowsAzureGuestAgent service is + * installed on the Virtual Machine. To run a resource extension in a + * Virtual Machine, this service must be installed. + * @return The ProvisionGuestAgent value. + */ + public Boolean isProvisionGuestAgent() { + return this.provisionGuestAgent; + } + + /** + * Optional. Indicates whether the WindowsAzureGuestAgent service is + * installed on the Virtual Machine. To run a resource extension in a + * Virtual Machine, this service must be installed. + * @param provisionGuestAgentValue The ProvisionGuestAgent value. + */ + public void setProvisionGuestAgent(final Boolean provisionGuestAgentValue) { + this.provisionGuestAgent = provisionGuestAgentValue; + } + + private ArrayList resourceExtensionReferences; + + /** + * Optional. Contains a collection of resource extensions that are to be + * installed on the Virtual Machine. This element is used if + * ProvisionGuestAgent is set to true. + * @return The ResourceExtensionReferences value. + */ + public ArrayList getResourceExtensionReferences() { + return this.resourceExtensionReferences; + } + + /** + * Optional. Contains a collection of resource extensions that are to be + * installed on the Virtual Machine. This element is used if + * ProvisionGuestAgent is set to true. + * @param resourceExtensionReferencesValue The ResourceExtensionReferences + * value. + */ + public void setResourceExtensionReferences(final ArrayList resourceExtensionReferencesValue) { + this.resourceExtensionReferences = resourceExtensionReferencesValue; + } + + private String roleName; + + /** + * Optional. The name of the role. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Optional. The name of the role. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + + private String roleSize; + + /** + * Optional. The size of the role instance. + * @return The RoleSize value. + */ + public String getRoleSize() { + return this.roleSize; + } + + /** + * Optional. The size of the role instance. + * @param roleSizeValue The RoleSize value. + */ + public void setRoleSize(final String roleSizeValue) { + this.roleSize = roleSizeValue; + } + + private String roleType; + + /** + * Optional. Specifies the type of the role. This element is only listed for + * Virtual Machine deployments, and by default is PersistentVMRole. + * @return The RoleType value. + */ + public String getRoleType() { + return this.roleType; + } + + /** + * Optional. Specifies the type of the role. This element is only listed for + * Virtual Machine deployments, and by default is PersistentVMRole. + * @param roleTypeValue The RoleType value. + */ + public void setRoleType(final String roleTypeValue) { + this.roleType = roleTypeValue; + } + + private String vMImageName; + + /** + * Optional. Optional. The name of the VMImage from which this Role is to be + * created. If the OSDisk in the VMImage was Specialized, then no + * WindowsProvisioningConfigurationSet or LinuxProvisioningConfigurationSet + * should be provided. No OSVirtualHardDisk or DataVirtualHardDisk should + * be specified when using this argument. + * @return The VMImageName value. + */ + public String getVMImageName() { + return this.vMImageName; + } + + /** + * Optional. Optional. The name of the VMImage from which this Role is to be + * created. If the OSDisk in the VMImage was Specialized, then no + * WindowsProvisioningConfigurationSet or LinuxProvisioningConfigurationSet + * should be provided. No OSVirtualHardDisk or DataVirtualHardDisk should + * be specified when using this argument. + * @param vMImageNameValue The VMImageName value. + */ + public void setVMImageName(final String vMImageNameValue) { + this.vMImageName = vMImageNameValue; + } + + /** + * Initializes a new instance of the Role class. + * + */ + public Role() { + this.configurationSets = new ArrayList(); + this.dataVirtualHardDisks = new ArrayList(); + this.resourceExtensionReferences = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstance.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstance.java new file mode 100644 index 0000000000000..6c8e25bb1a049 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstance.java @@ -0,0 +1,335 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.InetAddress; +import java.util.ArrayList; + +/** +* Details of a specific role instance. +*/ +public class RoleInstance { + private GuestAgentStatus guestAgentStatus; + + /** + * Optional. Guest Agent Status. + * @return The GuestAgentStatus value. + */ + public GuestAgentStatus getGuestAgentStatus() { + return this.guestAgentStatus; + } + + /** + * Optional. Guest Agent Status. + * @param guestAgentStatusValue The GuestAgentStatus value. + */ + public void setGuestAgentStatus(final GuestAgentStatus guestAgentStatusValue) { + this.guestAgentStatus = guestAgentStatusValue; + } + + private String hostName; + + /** + * Optional. The DNS host name of the service in which the role instance is + * running. This element is only listed for Virtual Machine deployments. + * @return The HostName value. + */ + public String getHostName() { + return this.hostName; + } + + /** + * Optional. The DNS host name of the service in which the role instance is + * running. This element is only listed for Virtual Machine deployments. + * @param hostNameValue The HostName value. + */ + public void setHostName(final String hostNameValue) { + this.hostName = hostNameValue; + } + + private ArrayList instanceEndpoints; + + /** + * Optional. The list of instance endpoints for the role. + * @return The InstanceEndpoints value. + */ + public ArrayList getInstanceEndpoints() { + return this.instanceEndpoints; + } + + /** + * Optional. The list of instance endpoints for the role. + * @param instanceEndpointsValue The InstanceEndpoints value. + */ + public void setInstanceEndpoints(final ArrayList instanceEndpointsValue) { + this.instanceEndpoints = instanceEndpointsValue; + } + + private String instanceErrorCode; + + /** + * Optional. An error code that can be provided to Windows Azure support to + * assist in resolution of errors. This field will typically be empty. + * @return The InstanceErrorCode value. + */ + public String getInstanceErrorCode() { + return this.instanceErrorCode; + } + + /** + * Optional. An error code that can be provided to Windows Azure support to + * assist in resolution of errors. This field will typically be empty. + * @param instanceErrorCodeValue The InstanceErrorCode value. + */ + public void setInstanceErrorCode(final String instanceErrorCodeValue) { + this.instanceErrorCode = instanceErrorCodeValue; + } + + private Integer instanceFaultDomain; + + /** + * Optional. The fault domain that this role instance belongs to. Role + * instances that are part of the same fault domain may all be vulnerable + * to the failure of the same piece of shared hardware. + * @return The InstanceFaultDomain value. + */ + public Integer getInstanceFaultDomain() { + return this.instanceFaultDomain; + } + + /** + * Optional. The fault domain that this role instance belongs to. Role + * instances that are part of the same fault domain may all be vulnerable + * to the failure of the same piece of shared hardware. + * @param instanceFaultDomainValue The InstanceFaultDomain value. + */ + public void setInstanceFaultDomain(final Integer instanceFaultDomainValue) { + this.instanceFaultDomain = instanceFaultDomainValue; + } + + private String instanceName; + + /** + * Optional. The name of the specific role instance, if an instance of the + * role is running. + * @return The InstanceName value. + */ + public String getInstanceName() { + return this.instanceName; + } + + /** + * Optional. The name of the specific role instance, if an instance of the + * role is running. + * @param instanceNameValue The InstanceName value. + */ + public void setInstanceName(final String instanceNameValue) { + this.instanceName = instanceNameValue; + } + + private String instanceSize; + + /** + * Optional. The size of the role instance. + * @return The InstanceSize value. + */ + public String getInstanceSize() { + return this.instanceSize; + } + + /** + * Optional. The size of the role instance. + * @param instanceSizeValue The InstanceSize value. + */ + public void setInstanceSize(final String instanceSizeValue) { + this.instanceSize = instanceSizeValue; + } + + private String instanceStateDetails; + + /** + * Optional. The instance state, returned as a string that, when present, + * provides a snapshot of the state of the virtual machine at the time the + * operation was called. + * @return The InstanceStateDetails value. + */ + public String getInstanceStateDetails() { + return this.instanceStateDetails; + } + + /** + * Optional. The instance state, returned as a string that, when present, + * provides a snapshot of the state of the virtual machine at the time the + * operation was called. + * @param instanceStateDetailsValue The InstanceStateDetails value. + */ + public void setInstanceStateDetails(final String instanceStateDetailsValue) { + this.instanceStateDetails = instanceStateDetailsValue; + } + + private String instanceStatus; + + /** + * Optional. The current status of this instance. + * @return The InstanceStatus value. + */ + public String getInstanceStatus() { + return this.instanceStatus; + } + + /** + * Optional. The current status of this instance. + * @param instanceStatusValue The InstanceStatus value. + */ + public void setInstanceStatus(final String instanceStatusValue) { + this.instanceStatus = instanceStatusValue; + } + + private Integer instanceUpgradeDomain; + + /** + * Optional. The update domain that this role instance belongs to. During an + * Upgrade Deployment, all roles in the same update domain are updated at + * the same time. + * @return The InstanceUpgradeDomain value. + */ + public Integer getInstanceUpgradeDomain() { + return this.instanceUpgradeDomain; + } + + /** + * Optional. The update domain that this role instance belongs to. During an + * Upgrade Deployment, all roles in the same update domain are updated at + * the same time. + * @param instanceUpgradeDomainValue The InstanceUpgradeDomain value. + */ + public void setInstanceUpgradeDomain(final Integer instanceUpgradeDomainValue) { + this.instanceUpgradeDomain = instanceUpgradeDomainValue; + } + + private InetAddress iPAddress; + + /** + * Optional. The IP address of the role instance (DIP). + * @return The IPAddress value. + */ + public InetAddress getIPAddress() { + return this.iPAddress; + } + + /** + * Optional. The IP address of the role instance (DIP). + * @param iPAddressValue The IPAddress value. + */ + public void setIPAddress(final InetAddress iPAddressValue) { + this.iPAddress = iPAddressValue; + } + + private RoleInstancePowerState powerState; + + /** + * Optional. The running state of the role instance. + * @return The PowerState value. + */ + public RoleInstancePowerState getPowerState() { + return this.powerState; + } + + /** + * Optional. The running state of the role instance. + * @param powerStateValue The PowerState value. + */ + public void setPowerState(final RoleInstancePowerState powerStateValue) { + this.powerState = powerStateValue; + } + + private String remoteAccessCertificateThumbprint; + + /** + * Optional. The thumbprint of the RDP server certificate (in Windows) or + * SSH server certificate (in Linux). The thumbprint is only used for + * Virtual Machines that have been created from an image. + * @return The RemoteAccessCertificateThumbprint value. + */ + public String getRemoteAccessCertificateThumbprint() { + return this.remoteAccessCertificateThumbprint; + } + + /** + * Optional. The thumbprint of the RDP server certificate (in Windows) or + * SSH server certificate (in Linux). The thumbprint is only used for + * Virtual Machines that have been created from an image. + * @param remoteAccessCertificateThumbprintValue The + * RemoteAccessCertificateThumbprint value. + */ + public void setRemoteAccessCertificateThumbprint(final String remoteAccessCertificateThumbprintValue) { + this.remoteAccessCertificateThumbprint = remoteAccessCertificateThumbprintValue; + } + + private ArrayList resourceExtensionStatusList; + + /** + * Optional. Resource Extension Status List. + * @return The ResourceExtensionStatusList value. + */ + public ArrayList getResourceExtensionStatusList() { + return this.resourceExtensionStatusList; + } + + /** + * Optional. Resource Extension Status List. + * @param resourceExtensionStatusListValue The ResourceExtensionStatusList + * value. + */ + public void setResourceExtensionStatusList(final ArrayList resourceExtensionStatusListValue) { + this.resourceExtensionStatusList = resourceExtensionStatusListValue; + } + + private String roleName; + + /** + * Optional. The name of the role. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Optional. The name of the role. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + + /** + * Initializes a new instance of the RoleInstance class. + * + */ + public RoleInstance() { + this.instanceEndpoints = new ArrayList(); + this.resourceExtensionStatusList = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstancePowerState.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstancePowerState.java new file mode 100644 index 0000000000000..0e20c51d2aca2 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstancePowerState.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The running state of the role instance. +*/ +public enum RoleInstancePowerState { + Starting, + + Started, + + Stopping, + + Stopped, + + Unknown, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstanceStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstanceStatus.java new file mode 100644 index 0000000000000..77e93032d4ae2 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RoleInstanceStatus.java @@ -0,0 +1,135 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The current status of a role instance. +*/ +public abstract class RoleInstanceStatus { + /** + * The role state is currently unknown. The state should automatically be + * resolved once the role state is detected, so no action is required. + */ + public static final String ROLESTATEUNKNOWN = "RoleStateUnknown"; + + /** + * The host agent is currently creating resources for the Virtual Machine. + */ + public static final String CREATINGVM = "CreatingVM"; + + /** + * The host agent is starting the Virtual Machine. + */ + public static final String STARTINGVM = "StartingVM"; + + /** + * Azure is creating resources for the role. + */ + public static final String CREATINGROLE = "CreatingRole"; + + /** + * Azure is starting the role. + */ + public static final String STARTINGROLE = "StartingRole"; + + /** + * The role instance has started and is ready to be used. + */ + public static final String READYROLE = "ReadyRole"; + + /** + * The role instance is unavailable for requests. This state is usually + * generated while the role is being created or stopped. + */ + public static final String BUSYROLE = "BusyRole"; + + /** + * Azure is stopping the role. + */ + public static final String STOPPINGROLE = "StoppingRole"; + + /** + * The host agent is stopping the Virtual Machine. This status also + * indicates that the role has already been stopped. + */ + public static final String STOPPINGVM = "StoppingVM"; + + /** + * The Virtual Machine is being deleted by the host agent. + */ + public static final String DELETINGVM = "DeletingVM"; + + /** + * The Virtual Machine is not running. This is the final state of the + * shutdown process, and no other status messages should be received after + * StoppedVM. + */ + public static final String STOPPEDVM = "StoppedVM"; + + /** + * The role has unexpectedly stopped or has failed to start. This status + * indicates that there is a problem with the role that is causing it to + * crash or is preventing it from starting, which must be corrected before + * the role can be started. The InstanceStateDetails and InstanceErrorCode + * fields can hold information about the role error that caused this state, + * which may be useful for identifying and debugging the problem. + */ + public static final String RESTARTINGROLE = "RestartingRole"; + + /** + * The role has continually crashed after being started by Azure. This + * status indicates that there is a problem with the role that prevents it + * from starting, and may be generated after the StartingRole and ReadyRole + * statuses are received. The problem in the role must be found and + * corrected before the role can be started. The InstanceStateDetails and + * InstanceErrorCode fields can hold information about the role error that + * caused this state, which may be useful for identifying and debugging the + * problem. + */ + public static final String CYCLINGROLE = "CyclingRole"; + + /** + * The role has continually failed to start. This status indicates that + * there is a problem with the role that prevents it from starting, and may + * be generated after the process returns StartingRole. The problem in the + * role must be found and corrected before the role can be started. The + * InstanceStateDetails and InstanceErrorCode fields can hold information + * about the role error that caused this state, which may be useful for + * identifying and debugging the problem. + */ + public static final String FAILEDSTARTINGROLE = "FailedStartingRole"; + + /** + * An Azure or container error is preventing the Virtual Machine from + * starting. This status is generated by Azure, and does not indicate an + * error with the role. It may be generated after the StartingRole state. + */ + public static final String FAILEDSTARTINGVM = "FailedStartingVM"; + + /** + * The role has timed out before receiving a status message and is not + * responding to requests. + */ + public static final String UNRESPONSIVEROLE = "UnresponsiveRole"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RollbackUpdateOrUpgradeMode.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RollbackUpdateOrUpgradeMode.java new file mode 100644 index 0000000000000..61df503d31400 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/RollbackUpdateOrUpgradeMode.java @@ -0,0 +1,37 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +public enum RollbackUpdateOrUpgradeMode { + /** + * The rollback proceeds without further user input. + */ + Auto, + + /** + * You must call the Walk Upgrade Domain operation to apply the rollback to + * each upgrade domain. + */ + Manual, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateCreateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateCreateParameters.java new file mode 100644 index 0000000000000..addeb9a1da1d7 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateCreateParameters.java @@ -0,0 +1,87 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Create Service Certificate operation. +*/ +public class ServiceCertificateCreateParameters { + private CertificateFormat certificateFormat; + + /** + * Required. The service certificate format. Azure supports the pfx and cer + * file formats. + * @return The CertificateFormat value. + */ + public CertificateFormat getCertificateFormat() { + return this.certificateFormat; + } + + /** + * Required. The service certificate format. Azure supports the pfx and cer + * file formats. + * @param certificateFormatValue The CertificateFormat value. + */ + public void setCertificateFormat(final CertificateFormat certificateFormatValue) { + this.certificateFormat = certificateFormatValue; + } + + private byte[] data; + + /** + * Required. The pfx or cer file. + * @return The Data value. + */ + public byte[] getData() { + return this.data; + } + + /** + * Required. The pfx or cer file. + * @param dataValue The Data value. + */ + public void setData(final byte[] dataValue) { + this.data = dataValue; + } + + private String password; + + /** + * Optional. The password for a pfx certificate. A cer certificate does not + * require a password. + * @return The Password value. + */ + public String getPassword() { + return this.password; + } + + /** + * Optional. The password for a pfx certificate. A cer certificate does not + * require a password. + * @param passwordValue The Password value. + */ + public void setPassword(final String passwordValue) { + this.password = passwordValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateDeleteParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateDeleteParameters.java new file mode 100644 index 0000000000000..00b2f40f64bb6 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateDeleteParameters.java @@ -0,0 +1,83 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Delete Service Certificate operation. +*/ +public class ServiceCertificateDeleteParameters { + private String serviceName; + + /** + * Required. The DNS prefix name of your service. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Required. The DNS prefix name of your service. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private String thumbprint; + + /** + * Required. The hexadecimal representation of the thumbprint. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Required. The hexadecimal representation of the thumbprint. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private String thumbprintAlgorithm; + + /** + * Required. The algorithm for the certificate's thumbprint. + * @return The ThumbprintAlgorithm value. + */ + public String getThumbprintAlgorithm() { + return this.thumbprintAlgorithm; + } + + /** + * Required. The algorithm for the certificate's thumbprint. + * @param thumbprintAlgorithmValue The ThumbprintAlgorithm value. + */ + public void setThumbprintAlgorithm(final String thumbprintAlgorithmValue) { + this.thumbprintAlgorithm = thumbprintAlgorithmValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateGetParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateGetParameters.java new file mode 100644 index 0000000000000..8cc3ab86e1e4b --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateGetParameters.java @@ -0,0 +1,83 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Get Service Certificate operation. +*/ +public class ServiceCertificateGetParameters { + private String serviceName; + + /** + * Required. The DNS prefix name of your service. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Required. The DNS prefix name of your service. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private String thumbprint; + + /** + * Required. The hexadecimal representation of the thumbprint. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Required. The hexadecimal representation of the thumbprint. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private String thumbprintAlgorithm; + + /** + * Required. The algorithm for the certificate's thumbprint. + * @return The ThumbprintAlgorithm value. + */ + public String getThumbprintAlgorithm() { + return this.thumbprintAlgorithm; + } + + /** + * Required. The algorithm for the certificate's thumbprint. + * @param thumbprintAlgorithmValue The ThumbprintAlgorithm value. + */ + public void setThumbprintAlgorithm(final String thumbprintAlgorithmValue) { + this.thumbprintAlgorithm = thumbprintAlgorithmValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateGetResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateGetResponse.java new file mode 100644 index 0000000000000..e3bec6ff13631 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateGetResponse.java @@ -0,0 +1,51 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Service Certificate operation response. +*/ +public class ServiceCertificateGetResponse extends OperationResponse { + private byte[] data; + + /** + * Optional. The public portion of the X.509 service certificate as a form + * of the cer file. + * @return The Data value. + */ + public byte[] getData() { + return this.data; + } + + /** + * Optional. The public portion of the X.509 service certificate as a form + * of the cer file. + * @param dataValue The Data value. + */ + public void setData(final byte[] dataValue) { + this.data = dataValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateListResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateListResponse.java new file mode 100644 index 0000000000000..6d2a50a0832cf --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/ServiceCertificateListResponse.java @@ -0,0 +1,152 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Service Certificates operation response. +*/ +public class ServiceCertificateListResponse extends OperationResponse implements Iterable { + private ArrayList certificates; + + /** + * Optional. The service certificates that are valid for your subscription. + * @return The Certificates value. + */ + public ArrayList getCertificates() { + return this.certificates; + } + + /** + * Optional. The service certificates that are valid for your subscription. + * @param certificatesValue The Certificates value. + */ + public void setCertificates(final ArrayList certificatesValue) { + this.certificates = certificatesValue; + } + + /** + * Initializes a new instance of the ServiceCertificateListResponse class. + * + */ + public ServiceCertificateListResponse() { + super(); + this.certificates = new ArrayList(); + } + + /** + * Gets the sequence of Certificates. + * + */ + public Iterator iterator() { + return this.getCertificates().iterator(); + } + + /** + * A service certificate that is valid for your subscription. + */ + public static class Certificate { + private URI certificateUri; + + /** + * Optional. The Service Management API request URI used to perform Get + * Service Certificate requests against the certificate store. + * @return The CertificateUri value. + */ + public URI getCertificateUri() { + return this.certificateUri; + } + + /** + * Optional. The Service Management API request URI used to perform Get + * Service Certificate requests against the certificate store. + * @param certificateUriValue The CertificateUri value. + */ + public void setCertificateUri(final URI certificateUriValue) { + this.certificateUri = certificateUriValue; + } + + private byte[] data; + + /** + * Optional. The public part of the service certificate as a cer file. + * @return The Data value. + */ + public byte[] getData() { + return this.data; + } + + /** + * Optional. The public part of the service certificate as a cer file. + * @param dataValue The Data value. + */ + public void setData(final byte[] dataValue) { + this.data = dataValue; + } + + private String thumbprint; + + /** + * Optional. The X509 certificate thumb print property of the service + * certificate. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. The X509 certificate thumb print property of the service + * certificate. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private String thumbprintAlgorithm; + + /** + * Optional. The algorithm that was used to hash the service + * certificate. Currently SHA-1 is the only supported algorithm. + * @return The ThumbprintAlgorithm value. + */ + public String getThumbprintAlgorithm() { + return this.thumbprintAlgorithm; + } + + /** + * Optional. The algorithm that was used to hash the service + * certificate. Currently SHA-1 is the only supported algorithm. + * @param thumbprintAlgorithmValue The ThumbprintAlgorithm value. + */ + public void setThumbprintAlgorithm(final String thumbprintAlgorithmValue) { + this.thumbprintAlgorithm = thumbprintAlgorithmValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettingKeyPair.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettingKeyPair.java new file mode 100644 index 0000000000000..44a964f101e69 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettingKeyPair.java @@ -0,0 +1,75 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Contains an SSH key pair to be installed on the virtual machine. +*/ +public class SshSettingKeyPair { + private String fingerprint; + + /** + * Required. Specifies the SHA1 fingerprint of an X509 certificate + * associated with the hosted service that includes the SSH key pair. + * @return The Fingerprint value. + */ + public String getFingerprint() { + return this.fingerprint; + } + + /** + * Required. Specifies the SHA1 fingerprint of an X509 certificate + * associated with the hosted service that includes the SSH key pair. + * @param fingerprintValue The Fingerprint value. + */ + public void setFingerprint(final String fingerprintValue) { + this.fingerprint = fingerprintValue; + } + + private String path; + + /** + * Required. Specifies the full path of a file on the virtual machine which + * stores the SSH private key. The file is overwritten when multiple keys + * are written to it. The SSH public key is stored in the same directory + * and has the same name as the private key file with .pub suffix. Example: + * /home/user/.ssh/id_rsa. + * @return The Path value. + */ + public String getPath() { + return this.path; + } + + /** + * Required. Specifies the full path of a file on the virtual machine which + * stores the SSH private key. The file is overwritten when multiple keys + * are written to it. The SSH public key is stored in the same directory + * and has the same name as the private key file with .pub suffix. Example: + * /home/user/.ssh/id_rsa. + * @param pathValue The Path value. + */ + public void setPath(final String pathValue) { + this.path = pathValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettingPublicKey.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettingPublicKey.java new file mode 100644 index 0000000000000..18085d6d57b21 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettingPublicKey.java @@ -0,0 +1,71 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies a public key in the SSH settings. +*/ +public class SshSettingPublicKey { + private String fingerprint; + + /** + * Required. Specifies the SHA1 fingerprint of an X509 certificate + * associated with the hosted service that includes the SSH public key. + * @return The Fingerprint value. + */ + public String getFingerprint() { + return this.fingerprint; + } + + /** + * Required. Specifies the SHA1 fingerprint of an X509 certificate + * associated with the hosted service that includes the SSH public key. + * @param fingerprintValue The Fingerprint value. + */ + public void setFingerprint(final String fingerprintValue) { + this.fingerprint = fingerprintValue; + } + + private String path; + + /** + * Required. Specifies the full path of a file on the virtual machine which + * stores the SSH public key. If the file already exists, the specified key + * is appended to the file. Example: /home/user/.ssh/authorized_keys. + * @return The Path value. + */ + public String getPath() { + return this.path; + } + + /** + * Required. Specifies the full path of a file on the virtual machine which + * stores the SSH public key. If the file already exists, the specified key + * is appended to the file. Example: /home/user/.ssh/authorized_keys. + * @param pathValue The Path value. + */ + public void setPath(final String pathValue) { + this.path = pathValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettings.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettings.java new file mode 100644 index 0000000000000..6f9520985cfa4 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/SshSettings.java @@ -0,0 +1,78 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Specifies the SSH public keys and key pairs to populate in the image during +* provisioning. This element is only used with the +* LinuxProvisioningConfiguration set. +*/ +public class SshSettings { + private ArrayList keyPairs; + + /** + * Optional. Specifies the collection of SSH key pairs. + * @return The KeyPairs value. + */ + public ArrayList getKeyPairs() { + return this.keyPairs; + } + + /** + * Optional. Specifies the collection of SSH key pairs. + * @param keyPairsValue The KeyPairs value. + */ + public void setKeyPairs(final ArrayList keyPairsValue) { + this.keyPairs = keyPairsValue; + } + + private ArrayList publicKeys; + + /** + * Optional. Specifies the collection of SSH public keys. + * @return The PublicKeys value. + */ + public ArrayList getPublicKeys() { + return this.publicKeys; + } + + /** + * Optional. Specifies the collection of SSH public keys. + * @param publicKeysValue The PublicKeys value. + */ + public void setPublicKeys(final ArrayList publicKeysValue) { + this.publicKeys = publicKeysValue; + } + + /** + * Initializes a new instance of the SshSettings class. + * + */ + public SshSettings() { + this.keyPairs = new ArrayList(); + this.publicKeys = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/StoredCertificateSettings.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/StoredCertificateSettings.java new file mode 100644 index 0000000000000..debfea82ab0e1 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/StoredCertificateSettings.java @@ -0,0 +1,73 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Service certificates with which to provision the new virtual machine. Stored +* certificate settings reference certificates that already exist in the Azure +* hosted service. Prior to configuring the stored certificates for the virtual +* machine, you must call the Add Service Certificate operation or add the +* certificate via the Azure Management portal. +*/ +public class StoredCertificateSettings { + private String storeName; + + /** + * Required. Specifies the name of the certificate store from which to + * retrieve certificates. For example, "My". + * @return The StoreName value. + */ + public String getStoreName() { + return this.storeName; + } + + /** + * Required. Specifies the name of the certificate store from which to + * retrieve certificates. For example, "My". + * @param storeNameValue The StoreName value. + */ + public void setStoreName(final String storeNameValue) { + this.storeName = storeNameValue; + } + + private String thumbprint; + + /** + * Required. Specifies the thumbprint of the certificate to be provisioned. + * The thumbprint must specify an existing service certificate. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Required. Specifies the thumbprint of the certificate to be provisioned. + * The thumbprint must specify an existing service certificate. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpdatedDeploymentStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpdatedDeploymentStatus.java new file mode 100644 index 0000000000000..ee031a7e9fdc1 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpdatedDeploymentStatus.java @@ -0,0 +1,30 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +public enum UpdatedDeploymentStatus { + Running, + + Suspended, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpgradeDomainState.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpgradeDomainState.java new file mode 100644 index 0000000000000..e1009194c9a07 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpgradeDomainState.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The current state of the upgrade. +*/ +public enum UpgradeDomainState { + Before, + + During, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpgradeStatus.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpgradeStatus.java new file mode 100644 index 0000000000000..7a32f0924eb00 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/UpgradeStatus.java @@ -0,0 +1,89 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Contains upgrade details of the deployment. +*/ +public class UpgradeStatus { + private int currentUpgradeDomain; + + /** + * Optional. An integer value that identifies the current upgrade domain. + * Upgrade domains are identified with a zero-based index: the first + * upgrade domain has an ID of 0, the second has an ID of 1, and so on. + * @return The CurrentUpgradeDomain value. + */ + public int getCurrentUpgradeDomain() { + return this.currentUpgradeDomain; + } + + /** + * Optional. An integer value that identifies the current upgrade domain. + * Upgrade domains are identified with a zero-based index: the first + * upgrade domain has an ID of 0, the second has an ID of 1, and so on. + * @param currentUpgradeDomainValue The CurrentUpgradeDomain value. + */ + public void setCurrentUpgradeDomain(final int currentUpgradeDomainValue) { + this.currentUpgradeDomain = currentUpgradeDomainValue; + } + + private UpgradeDomainState currentUpgradeDomainState; + + /** + * Optional. The current state of the upgrade. Possible values are Before + * and During + * @return The CurrentUpgradeDomainState value. + */ + public UpgradeDomainState getCurrentUpgradeDomainState() { + return this.currentUpgradeDomainState; + } + + /** + * Optional. The current state of the upgrade. Possible values are Before + * and During + * @param currentUpgradeDomainStateValue The CurrentUpgradeDomainState value. + */ + public void setCurrentUpgradeDomainState(final UpgradeDomainState currentUpgradeDomainStateValue) { + this.currentUpgradeDomainState = currentUpgradeDomainStateValue; + } + + private DeploymentUpgradeType upgradeType; + + /** + * Optional. The type of the upgrade. Possible values are Auto and Manual. + * @return The UpgradeType value. + */ + public DeploymentUpgradeType getUpgradeType() { + return this.upgradeType; + } + + /** + * Optional. The type of the upgrade. Possible values are Auto and Manual. + * @param upgradeTypeValue The UpgradeType value. + */ + public void setUpgradeType(final DeploymentUpgradeType upgradeTypeValue) { + this.upgradeType = upgradeTypeValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualHardDiskHostCaching.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualHardDiskHostCaching.java new file mode 100644 index 0000000000000..90d073adb8ef7 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualHardDiskHostCaching.java @@ -0,0 +1,36 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the platform caching behavior of the data disk blob for read/write +* efficiency. +*/ +public enum VirtualHardDiskHostCaching { + None, + + ReadOnly, + + ReadWrite, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualIPAddress.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualIPAddress.java new file mode 100644 index 0000000000000..c2afdd9f621c5 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualIPAddress.java @@ -0,0 +1,85 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.InetAddress; + +/** +* The virtual IP address of the deployment. +*/ +public class VirtualIPAddress { + private InetAddress address; + + /** + * Optional. The virtual IP address of the deployment. + * @return The Address value. + */ + public InetAddress getAddress() { + return this.address; + } + + /** + * Optional. The virtual IP address of the deployment. + * @param addressValue The Address value. + */ + public void setAddress(final InetAddress addressValue) { + this.address = addressValue; + } + + private Boolean isDnsProgrammed; + + /** + * Optional. Indicates whether the IP address is DNS programmed. + * @return The IsDnsProgrammed value. + */ + public Boolean isDnsProgrammed() { + return this.isDnsProgrammed; + } + + /** + * Optional. Indicates whether the IP address is DNS programmed. + * @param isDnsProgrammedValue The IsDnsProgrammed value. + */ + public void setIsDnsProgrammed(final Boolean isDnsProgrammedValue) { + this.isDnsProgrammed = isDnsProgrammedValue; + } + + private String name; + + /** + * Optional. The name of the virtual IP. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the virtual IP. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCaptureOSImageParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCaptureOSImageParameters.java new file mode 100644 index 0000000000000..c3b0d29baedb7 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCaptureOSImageParameters.java @@ -0,0 +1,119 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Parameters supplied to the Capture Virtual Machine operation. +*/ +public class VirtualMachineCaptureOSImageParameters { + private PostCaptureAction postCaptureAction; + + /** + * Required. Specifies the action that is performed after the capture + * operation finishes. Possible values are: Delete - this value causes the + * virtual machine to be deleted after the image has been captured; or + * Reprovision - this value causes the virtual machine to be redeployed + * after the image is captured by using the specified information in + * ProvisioningConfiguration. + * @return The PostCaptureAction value. + */ + public PostCaptureAction getPostCaptureAction() { + return this.postCaptureAction; + } + + /** + * Required. Specifies the action that is performed after the capture + * operation finishes. Possible values are: Delete - this value causes the + * virtual machine to be deleted after the image has been captured; or + * Reprovision - this value causes the virtual machine to be redeployed + * after the image is captured by using the specified information in + * ProvisioningConfiguration. + * @param postCaptureActionValue The PostCaptureAction value. + */ + public void setPostCaptureAction(final PostCaptureAction postCaptureActionValue) { + this.postCaptureAction = postCaptureActionValue; + } + + private ConfigurationSet provisioningConfiguration; + + /** + * Optional. Provides information to be used to redeploy the virtual machine + * after the image has been captured. This element is only used when the + * PostCaptureAction is set to Reprovision. + * @return The ProvisioningConfiguration value. + */ + public ConfigurationSet getProvisioningConfiguration() { + return this.provisioningConfiguration; + } + + /** + * Optional. Provides information to be used to redeploy the virtual machine + * after the image has been captured. This element is only used when the + * PostCaptureAction is set to Reprovision. + * @param provisioningConfigurationValue The ProvisioningConfiguration value. + */ + public void setProvisioningConfiguration(final ConfigurationSet provisioningConfigurationValue) { + this.provisioningConfiguration = provisioningConfigurationValue; + } + + private String targetImageLabel; + + /** + * Required. Specifies the friendly name of the captured image. This is the + * value that appears in the Name column for the image in the Azure + * Management Portal. + * @return The TargetImageLabel value. + */ + public String getTargetImageLabel() { + return this.targetImageLabel; + } + + /** + * Required. Specifies the friendly name of the captured image. This is the + * value that appears in the Name column for the image in the Azure + * Management Portal. + * @param targetImageLabelValue The TargetImageLabel value. + */ + public void setTargetImageLabel(final String targetImageLabelValue) { + this.targetImageLabel = targetImageLabelValue; + } + + private String targetImageName; + + /** + * Required. Specifies the image name of the captured image. + * @return The TargetImageName value. + */ + public String getTargetImageName() { + return this.targetImageName; + } + + /** + * Required. Specifies the image name of the captured image. + * @param targetImageNameValue The TargetImageName value. + */ + public void setTargetImageName(final String targetImageNameValue) { + this.targetImageName = targetImageNameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCaptureVMImageParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCaptureVMImageParameters.java new file mode 100644 index 0000000000000..7ba28c13d299b --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCaptureVMImageParameters.java @@ -0,0 +1,103 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Virtual Machine Template Capture Role operation response. +*/ +public class VirtualMachineCaptureVMImageParameters extends OperationResponse { + private String operationType; + + /** + * Optional. Required. Must be set to CaptureRoleOperation. + * @return The OperationType value. + */ + public String getOperationType() { + return this.operationType; + } + + /** + * Optional. Required. Must be set to CaptureRoleOperation. + * @param operationTypeValue The OperationType value. + */ + public void setOperationType(final String operationTypeValue) { + this.operationType = operationTypeValue; + } + + private String oSState; + + /** + * Optional. Required. The OS state: Generalized | Specialized. + * @return The OSState value. + */ + public String getOSState() { + return this.oSState; + } + + /** + * Optional. Required. The OS state: Generalized | Specialized. + * @param oSStateValue The OSState value. + */ + public void setOSState(final String oSStateValue) { + this.oSState = oSStateValue; + } + + private String vMImageLabel; + + /** + * Optional. Required. The VM Template Label. + * @return The VMImageLabel value. + */ + public String getVMImageLabel() { + return this.vMImageLabel; + } + + /** + * Optional. Required. The VM Template Label. + * @param vMImageLabelValue The VMImageLabel value. + */ + public void setVMImageLabel(final String vMImageLabelValue) { + this.vMImageLabel = vMImageLabelValue; + } + + private String vMImageName; + + /** + * Optional. Required. The VM Template Name. + * @return The VMImageName value. + */ + public String getVMImageName() { + return this.vMImageName; + } + + /** + * Optional. Required. The VM Template Name. + * @param vMImageNameValue The VMImageName value. + */ + public void setVMImageName(final String vMImageNameValue) { + this.vMImageName = vMImageNameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCreateDeploymentParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCreateDeploymentParameters.java new file mode 100644 index 0000000000000..b3b587d4df2c2 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCreateDeploymentParameters.java @@ -0,0 +1,186 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Parameters supplied to the Create Virtual Machine Deployment operation. +*/ +public class VirtualMachineCreateDeploymentParameters { + private DeploymentSlot deploymentSlot; + + /** + * Required. Specifies the environment in which to deploy the virtual + * machine. Possible values are: Staging or Production. + * @return The DeploymentSlot value. + */ + public DeploymentSlot getDeploymentSlot() { + return this.deploymentSlot; + } + + /** + * Required. Specifies the environment in which to deploy the virtual + * machine. Possible values are: Staging or Production. + * @param deploymentSlotValue The DeploymentSlot value. + */ + public void setDeploymentSlot(final DeploymentSlot deploymentSlotValue) { + this.deploymentSlot = deploymentSlotValue; + } + + private DnsSettings dnsSettings; + + /** + * Optional. Contains a list of DNS servers to associate with the machine. + * @return The DnsSettings value. + */ + public DnsSettings getDnsSettings() { + return this.dnsSettings; + } + + /** + * Optional. Contains a list of DNS servers to associate with the machine. + * @param dnsSettingsValue The DnsSettings value. + */ + public void setDnsSettings(final DnsSettings dnsSettingsValue) { + this.dnsSettings = dnsSettingsValue; + } + + private String label; + + /** + * Required. A name for the hosted service. The name can be up to 100 + * characters in length. It is recommended that the label be unique within + * the subscription. The name can be used identify the hosted service for + * tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. A name for the hosted service. The name can be up to 100 + * characters in length. It is recommended that the label be unique within + * the subscription. The name can be used identify the hosted service for + * tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Required. A name for the deployment. The deployment name must be unique + * among other deployments for the hosted service. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. A name for the deployment. The deployment name must be unique + * among other deployments for the hosted service. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String reservedIPName; + + /** + * Optional. Optional and Preview Only. Specifies the name of an existing + * reserved IP to which the deployment will belong. Reserved IPs are + * created by calling the Create Reserved IP operation. + * @return The ReservedIPName value. + */ + public String getReservedIPName() { + return this.reservedIPName; + } + + /** + * Optional. Optional and Preview Only. Specifies the name of an existing + * reserved IP to which the deployment will belong. Reserved IPs are + * created by calling the Create Reserved IP operation. + * @param reservedIPNameValue The ReservedIPName value. + */ + public void setReservedIPName(final String reservedIPNameValue) { + this.reservedIPName = reservedIPNameValue; + } + + private ArrayList roles; + + /** + * Required. Contains the provisioning details for the new virtual machine + * deployment. + * @return The Roles value. + */ + public ArrayList getRoles() { + return this.roles; + } + + /** + * Required. Contains the provisioning details for the new virtual machine + * deployment. + * @param rolesValue The Roles value. + */ + public void setRoles(final ArrayList rolesValue) { + this.roles = rolesValue; + } + + private String virtualNetworkName; + + /** + * Optional. Specifies the name of an existing virtual network to which the + * deployment will belong. Virtual networks are created by calling the Set + * Network Configuration operation. + * @return The VirtualNetworkName value. + */ + public String getVirtualNetworkName() { + return this.virtualNetworkName; + } + + /** + * Optional. Specifies the name of an existing virtual network to which the + * deployment will belong. Virtual networks are created by calling the Set + * Network Configuration operation. + * @param virtualNetworkNameValue The VirtualNetworkName value. + */ + public void setVirtualNetworkName(final String virtualNetworkNameValue) { + this.virtualNetworkName = virtualNetworkNameValue; + } + + /** + * Initializes a new instance of the + * VirtualMachineCreateDeploymentParameters class. + * + */ + public VirtualMachineCreateDeploymentParameters() { + this.roles = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCreateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCreateParameters.java new file mode 100644 index 0000000000000..da7de4678acd8 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineCreateParameters.java @@ -0,0 +1,236 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Parameters supplied to the Create Virtual Machine operation. +*/ +public class VirtualMachineCreateParameters { + private String availabilitySetName; + + /** + * Optional. Specifies the name of an availability set to which to add the + * virtual machine. This value controls the virtual machine allocation in + * the Azure environment. Virtual machines specified in the same + * availability set are allocated to different nodes to maximize + * availability. + * @return The AvailabilitySetName value. + */ + public String getAvailabilitySetName() { + return this.availabilitySetName; + } + + /** + * Optional. Specifies the name of an availability set to which to add the + * virtual machine. This value controls the virtual machine allocation in + * the Azure environment. Virtual machines specified in the same + * availability set are allocated to different nodes to maximize + * availability. + * @param availabilitySetNameValue The AvailabilitySetName value. + */ + public void setAvailabilitySetName(final String availabilitySetNameValue) { + this.availabilitySetName = availabilitySetNameValue; + } + + private ArrayList configurationSets; + + /** + * Optional. Contains the collection of configuration sets that contain + * system and application configuration settings. + * @return The ConfigurationSets value. + */ + public ArrayList getConfigurationSets() { + return this.configurationSets; + } + + /** + * Optional. Contains the collection of configuration sets that contain + * system and application configuration settings. + * @param configurationSetsValue The ConfigurationSets value. + */ + public void setConfigurationSets(final ArrayList configurationSetsValue) { + this.configurationSets = configurationSetsValue; + } + + private ArrayList dataVirtualHardDisks; + + /** + * Optional. Contains the parameters Azure used to create the data disk for + * the virtual machine. + * @return The DataVirtualHardDisks value. + */ + public ArrayList getDataVirtualHardDisks() { + return this.dataVirtualHardDisks; + } + + /** + * Optional. Contains the parameters Azure used to create the data disk for + * the virtual machine. + * @param dataVirtualHardDisksValue The DataVirtualHardDisks value. + */ + public void setDataVirtualHardDisks(final ArrayList dataVirtualHardDisksValue) { + this.dataVirtualHardDisks = dataVirtualHardDisksValue; + } + + private OSVirtualHardDisk oSVirtualHardDisk; + + /** + * Optional. Contains the parameters Azure used to create the operating + * system disk for the virtual machine. + * @return The OSVirtualHardDisk value. + */ + public OSVirtualHardDisk getOSVirtualHardDisk() { + return this.oSVirtualHardDisk; + } + + /** + * Optional. Contains the parameters Azure used to create the operating + * system disk for the virtual machine. + * @param oSVirtualHardDiskValue The OSVirtualHardDisk value. + */ + public void setOSVirtualHardDisk(final OSVirtualHardDisk oSVirtualHardDiskValue) { + this.oSVirtualHardDisk = oSVirtualHardDiskValue; + } + + private Boolean provisionGuestAgent; + + /** + * Optional. Indicates whether the WindowsAzureGuestAgent service is + * installed on the Virtual Machine. To run a resource extension in a + * Virtual Machine, this service must be installed. + * @return The ProvisionGuestAgent value. + */ + public Boolean isProvisionGuestAgent() { + return this.provisionGuestAgent; + } + + /** + * Optional. Indicates whether the WindowsAzureGuestAgent service is + * installed on the Virtual Machine. To run a resource extension in a + * Virtual Machine, this service must be installed. + * @param provisionGuestAgentValue The ProvisionGuestAgent value. + */ + public void setProvisionGuestAgent(final Boolean provisionGuestAgentValue) { + this.provisionGuestAgent = provisionGuestAgentValue; + } + + private ArrayList resourceExtensionReferences; + + /** + * Optional. Contains a collection of resource extensions that are to be + * installed on the Virtual Machine. This element is used if + * ProvisionGuestAgent is set to true. + * @return The ResourceExtensionReferences value. + */ + public ArrayList getResourceExtensionReferences() { + return this.resourceExtensionReferences; + } + + /** + * Optional. Contains a collection of resource extensions that are to be + * installed on the Virtual Machine. This element is used if + * ProvisionGuestAgent is set to true. + * @param resourceExtensionReferencesValue The ResourceExtensionReferences + * value. + */ + public void setResourceExtensionReferences(final ArrayList resourceExtensionReferencesValue) { + this.resourceExtensionReferences = resourceExtensionReferencesValue; + } + + private String roleName; + + /** + * Required. Specifies the name for the virtual machine. The name must be + * unique within the deployment. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Required. Specifies the name for the virtual machine. The name must be + * unique within the deployment. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + + private String roleSize; + + /** + * Optional. The size of the virtual machine. + * @return The RoleSize value. + */ + public String getRoleSize() { + return this.roleSize; + } + + /** + * Optional. The size of the virtual machine. + * @param roleSizeValue The RoleSize value. + */ + public void setRoleSize(final String roleSizeValue) { + this.roleSize = roleSizeValue; + } + + private String vMImageName; + + /** + * Optional. Name of the VMImage from which this Role is to be created. If + * the OSDisk in the VMImage was Specialized, then no + * WindowsProvisioningConfigurationSet or LinuxProvisioningConfigurationSet + * should be provided. No OSVirtualHardDisk or DataVirtualHardDisk should + * be specified when using this argument. + * @return The VMImageName value. + */ + public String getVMImageName() { + return this.vMImageName; + } + + /** + * Optional. Name of the VMImage from which this Role is to be created. If + * the OSDisk in the VMImage was Specialized, then no + * WindowsProvisioningConfigurationSet or LinuxProvisioningConfigurationSet + * should be provided. No OSVirtualHardDisk or DataVirtualHardDisk should + * be specified when using this argument. + * @param vMImageNameValue The VMImageName value. + */ + public void setVMImageName(final String vMImageNameValue) { + this.vMImageName = vMImageNameValue; + } + + /** + * Initializes a new instance of the VirtualMachineCreateParameters class. + * + */ + public VirtualMachineCreateParameters() { + this.configurationSets = new ArrayList(); + this.dataVirtualHardDisks = new ArrayList(); + this.resourceExtensionReferences = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskCreateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskCreateParameters.java new file mode 100644 index 0000000000000..0bdd8d87add5b --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskCreateParameters.java @@ -0,0 +1,195 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; + +/** +* Parameters supplied to the Create Virtual Machine Data Disk operation. +*/ +public class VirtualMachineDataDiskCreateParameters { + private VirtualHardDiskHostCaching hostCaching; + + /** + * Required. Specifies the platform caching behavior of data disk blob for + * read/write efficiency. The default vault is ReadOnly. Possible values + * are: None, ReadOnly, or ReadWrite. Warning: Setting this property + * impacts the consistency of the disk. + * @return The HostCaching value. + */ + public VirtualHardDiskHostCaching getHostCaching() { + return this.hostCaching; + } + + /** + * Required. Specifies the platform caching behavior of data disk blob for + * read/write efficiency. The default vault is ReadOnly. Possible values + * are: None, ReadOnly, or ReadWrite. Warning: Setting this property + * impacts the consistency of the disk. + * @param hostCachingValue The HostCaching value. + */ + public void setHostCaching(final VirtualHardDiskHostCaching hostCachingValue) { + this.hostCaching = hostCachingValue; + } + + private String label; + + /** + * Optional. Specifies the description of the data disk. When you attach a + * disk, either by directly referencing a media using the MediaLink element + * or specifying the target disk size, you can use the DiskLabel element to + * customize the name property of the target data disk. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Specifies the description of the data disk. When you attach a + * disk, either by directly referencing a media using the MediaLink element + * or specifying the target disk size, you can use the DiskLabel element to + * customize the name property of the target data disk. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private int logicalDiskSizeInGB; + + /** + * Optional. Specifies the size, in GB, of an empty disk to be attached to + * the role. The disk can be created as part of disk attach or create VM + * role call by specifying the value for this property. Azure creates the + * empty disk based on size preference and attaches the newly created disk + * to the Role. + * @return The LogicalDiskSizeInGB value. + */ + public int getLogicalDiskSizeInGB() { + return this.logicalDiskSizeInGB; + } + + /** + * Optional. Specifies the size, in GB, of an empty disk to be attached to + * the role. The disk can be created as part of disk attach or create VM + * role call by specifying the value for this property. Azure creates the + * empty disk based on size preference and attaches the newly created disk + * to the Role. + * @param logicalDiskSizeInGBValue The LogicalDiskSizeInGB value. + */ + public void setLogicalDiskSizeInGB(final int logicalDiskSizeInGBValue) { + this.logicalDiskSizeInGB = logicalDiskSizeInGBValue; + } + + private Integer logicalUnitNumber; + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the disk. The LUN + * specifies the slot in which the data drive appears when mounted for + * usage by the virtual machine. Valid LUN values are 0 through 15. + * @return The LogicalUnitNumber value. + */ + public Integer getLogicalUnitNumber() { + return this.logicalUnitNumber; + } + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the disk. The LUN + * specifies the slot in which the data drive appears when mounted for + * usage by the virtual machine. Valid LUN values are 0 through 15. + * @param logicalUnitNumberValue The LogicalUnitNumber value. + */ + public void setLogicalUnitNumber(final Integer logicalUnitNumberValue) { + this.logicalUnitNumber = logicalUnitNumberValue; + } + + private URI mediaLinkUri; + + /** + * Required. Specifies the location of the blob in Azure storage where the + * media for the disk is located. The blob location must belong to the + * storage account in the subscription specified by the SubscriptionId + * value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Required. Specifies the location of the blob in Azure storage where the + * media for the disk is located. The blob location must belong to the + * storage account in the subscription specified by the SubscriptionId + * value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. Specifies the name of the disk. Azure uses the specified disk + * to create the data disk for the machine and populates this field with + * the disk name. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name of the disk. Azure uses the specified disk + * to create the data disk for the machine and populates this field with + * the disk name. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private URI sourceMediaLinkUri; + + /** + * Optional. Specifies the location of a blob in account storage which is + * mounted as a data disk when the virtual machine is created. + * @return The SourceMediaLinkUri value. + */ + public URI getSourceMediaLinkUri() { + return this.sourceMediaLinkUri; + } + + /** + * Optional. Specifies the location of a blob in account storage which is + * mounted as a data disk when the virtual machine is created. + * @param sourceMediaLinkUriValue The SourceMediaLinkUri value. + */ + public void setSourceMediaLinkUri(final URI sourceMediaLinkUriValue) { + this.sourceMediaLinkUri = sourceMediaLinkUriValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskGetResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskGetResponse.java new file mode 100644 index 0000000000000..02ab9361ae88b --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskGetResponse.java @@ -0,0 +1,152 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* The Get Data Disk operation response. +*/ +public class VirtualMachineDataDiskGetResponse extends OperationResponse { + private VirtualHardDiskHostCaching hostCaching; + + /** + * Optional. The current value of the platform caching behavior of data disk + * blob for read/write efficiency. Possible values are: None, ReadOnly, or + * ReadWrite. + * @return The HostCaching value. + */ + public VirtualHardDiskHostCaching getHostCaching() { + return this.hostCaching; + } + + /** + * Optional. The current value of the platform caching behavior of data disk + * blob for read/write efficiency. Possible values are: None, ReadOnly, or + * ReadWrite. + * @param hostCachingValue The HostCaching value. + */ + public void setHostCaching(final VirtualHardDiskHostCaching hostCachingValue) { + this.hostCaching = hostCachingValue; + } + + private String label; + + /** + * Optional. The description of the data disk. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The description of the data disk. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private int logicalDiskSizeInGB; + + /** + * Optional. The size, in GB, of the data disk. + * @return The LogicalDiskSizeInGB value. + */ + public int getLogicalDiskSizeInGB() { + return this.logicalDiskSizeInGB; + } + + /** + * Optional. The size, in GB, of the data disk. + * @param logicalDiskSizeInGBValue The LogicalDiskSizeInGB value. + */ + public void setLogicalDiskSizeInGB(final int logicalDiskSizeInGBValue) { + this.logicalDiskSizeInGB = logicalDiskSizeInGBValue; + } + + private Integer logicalUnitNumber; + + /** + * Optional. The Logical Unit Number (LUN) for the disk. The LUN specifies + * the slot in which the data drive appears when mounted for usage by the + * virtual machine. + * @return The LogicalUnitNumber value. + */ + public Integer getLogicalUnitNumber() { + return this.logicalUnitNumber; + } + + /** + * Optional. The Logical Unit Number (LUN) for the disk. The LUN specifies + * the slot in which the data drive appears when mounted for usage by the + * virtual machine. + * @param logicalUnitNumberValue The LogicalUnitNumber value. + */ + public void setLogicalUnitNumber(final Integer logicalUnitNumberValue) { + this.logicalUnitNumber = logicalUnitNumberValue; + } + + private URI mediaLinkUri; + + /** + * Optional. The location of the physical blob backing the data disk. The + * blob location is in the storage account in the subscription specified by + * the SubscriptionId value in the operation call. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. The location of the physical blob backing the data disk. The + * blob location is in the storage account in the subscription specified by + * the SubscriptionId value in the operation call. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. The name of the data disk. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the data disk. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskUpdateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskUpdateParameters.java new file mode 100644 index 0000000000000..76954a7cbdace --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDataDiskUpdateParameters.java @@ -0,0 +1,175 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; + +/** +* Parameters supplied to the Update Virtual Machine Data Disk operation. +*/ +public class VirtualMachineDataDiskUpdateParameters { + private VirtualHardDiskHostCaching hostCaching; + + /** + * Required. Specifies the platform caching behavior of data disk blob for + * read/write efficiency. The default vault is ReadOnly. Possible values + * are: None, ReadOnly, or ReadWrite. Warning: Setting this property + * impacts the consistency of the disk. + * @return The HostCaching value. + */ + public VirtualHardDiskHostCaching getHostCaching() { + return this.hostCaching; + } + + /** + * Required. Specifies the platform caching behavior of data disk blob for + * read/write efficiency. The default vault is ReadOnly. Possible values + * are: None, ReadOnly, or ReadWrite. Warning: Setting this property + * impacts the consistency of the disk. + * @param hostCachingValue The HostCaching value. + */ + public void setHostCaching(final VirtualHardDiskHostCaching hostCachingValue) { + this.hostCaching = hostCachingValue; + } + + private String label; + + /** + * Optional. Specifies the description of the data disk. When you attach a + * disk, either by directly referencing a media using the MediaLink element + * or specifying the target disk size, you can use the DiskLabel element to + * customize the name property of the target data disk. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Specifies the description of the data disk. When you attach a + * disk, either by directly referencing a media using the MediaLink element + * or specifying the target disk size, you can use the DiskLabel element to + * customize the name property of the target data disk. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private int logicalDiskSizeInGB; + + /** + * Optional. Specifies the size, in GB, of an empty disk to be attached to + * the role. The disk can be created as part of disk attach or create VM + * role call by specifying the value for this property. Azure creates the + * empty disk based on size preference and attaches the newly created disk + * to the Role. + * @return The LogicalDiskSizeInGB value. + */ + public int getLogicalDiskSizeInGB() { + return this.logicalDiskSizeInGB; + } + + /** + * Optional. Specifies the size, in GB, of an empty disk to be attached to + * the role. The disk can be created as part of disk attach or create VM + * role call by specifying the value for this property. Azure creates the + * empty disk based on size preference and attaches the newly created disk + * to the Role. + * @param logicalDiskSizeInGBValue The LogicalDiskSizeInGB value. + */ + public void setLogicalDiskSizeInGB(final int logicalDiskSizeInGBValue) { + this.logicalDiskSizeInGB = logicalDiskSizeInGBValue; + } + + private Integer logicalUnitNumber; + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the disk. The LUN + * specifies the slot in which the data drive appears when mounted for + * usage by the virtual machine. Valid LUN values are 0 through 15. + * @return The LogicalUnitNumber value. + */ + public Integer getLogicalUnitNumber() { + return this.logicalUnitNumber; + } + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the disk. The LUN + * specifies the slot in which the data drive appears when mounted for + * usage by the virtual machine. Valid LUN values are 0 through 15. + * @param logicalUnitNumberValue The LogicalUnitNumber value. + */ + public void setLogicalUnitNumber(final Integer logicalUnitNumberValue) { + this.logicalUnitNumber = logicalUnitNumberValue; + } + + private URI mediaLinkUri; + + /** + * Required. Specifies the location of the blob in Azure blob store where + * the media for the disk is located. The blob location must belong to the + * storage account in the subscription specified by the SubscriptionId + * value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Required. Specifies the location of the blob in Azure blob store where + * the media for the disk is located. The blob location must belong to the + * storage account in the subscription specified by the SubscriptionId + * value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. Specifies the name of the disk. Azure uses the specified disk + * to create the data disk for the machine and populates this field with + * the disk name. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name of the disk. Azure uses the specified disk + * to create the data disk for the machine and populates this field with + * the disk name. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskCreateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskCreateParameters.java new file mode 100644 index 0000000000000..a6d27b41d5428 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskCreateParameters.java @@ -0,0 +1,113 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; + +/** +* Parameters supplied to the Create Virtual Disk Image operation. +*/ +public class VirtualMachineDiskCreateParameters { + private String label; + + /** + * Required. Specifies the friendly name of the disk. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. Specifies the friendly name of the disk. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private URI mediaLinkUri; + + /** + * Required. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Required. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Required. Specifies a name for the disk. Azure uses the name to identify + * the disk when creating virtual machines from the disk. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. Specifies a name for the disk. Azure uses the name to identify + * the disk when creating virtual machines from the disk. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the disk. Possible values are: + * Linux or Windows. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the disk. Possible values are: + * Linux or Windows. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskCreateResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskCreateResponse.java new file mode 100644 index 0000000000000..5f2c87f9c9d68 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskCreateResponse.java @@ -0,0 +1,305 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* A virtual machine disk associated with your subscription. +*/ +public class VirtualMachineDiskCreateResponse extends OperationResponse { + private String affinityGroup; + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains the + * blob in which the media is located. If the storage account does not + * belong to an affinity group the value is NULL. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains the + * blob in which the media is located. If the storage account does not + * belong to an affinity group the value is NULL. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private Boolean isPremium; + + /** + * Optional. Specifies whether the comtained image is a premium image + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Specifies whether the comtained image is a premium image + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. The friendly name of the disk + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly name of the disk + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in which + * the disk is located. If the storage account belongs to an affinity group + * the value is NULL. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in which + * the disk is located. If the storage account belongs to an affinity group + * the value is NULL. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private int logicalSizeInGB; + + /** + * Optional. The size, in GB, of the disk. + * @return The LogicalSizeInGB value. + */ + public int getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the disk. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final int logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. The location of the blob in the blob store in which the media + * for the disk is located. The blob location belongs to a storage account + * in the subscription specified by the SubscriptionId value in the + * operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. The location of the blob in the blob store in which the media + * for the disk is located. The blob location belongs to a storage account + * in the subscription specified by the SubscriptionId value in the + * operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystem; + + /** + * Optional. The Operating System type for the disk. + * @return The OperatingSystem value. + */ + public String getOperatingSystem() { + return this.operatingSystem; + } + + /** + * Optional. The Operating System type for the disk. + * @param operatingSystemValue The OperatingSystem value. + */ + public void setOperatingSystem(final String operatingSystemValue) { + this.operatingSystem = operatingSystemValue; + } + + private String sourceImageName; + + /** + * Optional. The name of the OS Image from which the disk was created. This + * property is populated automatically when a disk is created from an OS + * image by calling the Add Role, Create Deployment, or Provision Disk + * operations. + * @return The SourceImageName value. + */ + public String getSourceImageName() { + return this.sourceImageName; + } + + /** + * Optional. The name of the OS Image from which the disk was created. This + * property is populated automatically when a disk is created from an OS + * image by calling the Add Role, Create Deployment, or Provision Disk + * operations. + * @param sourceImageNameValue The SourceImageName value. + */ + public void setSourceImageName(final String sourceImageNameValue) { + this.sourceImageName = sourceImageNameValue; + } + + private VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails usageDetails; + + /** + * Optional. Contains properties that specify a virtual machine that is + * currently using the disk. A disk cannot be deleted as long as it is + * attached to a virtual machine. + * @return The UsageDetails value. + */ + public VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails getUsageDetails() { + return this.usageDetails; + } + + /** + * Optional. Contains properties that specify a virtual machine that is + * currently using the disk. A disk cannot be deleted as long as it is + * attached to a virtual machine. + * @param usageDetailsValue The UsageDetails value. + */ + public void setUsageDetails(final VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails usageDetailsValue) { + this.usageDetails = usageDetailsValue; + } + + /** + * Contains properties that specify a virtual machine that currently using + * the disk. A disk cannot be deleted as long as it is attached to a + * virtual machine. + */ + public static class VirtualMachineDiskUsageDetails { + private String deploymentName; + + /** + * Optional. The deployment in which the disk is being used. + * @return The DeploymentName value. + */ + public String getDeploymentName() { + return this.deploymentName; + } + + /** + * Optional. The deployment in which the disk is being used. + * @param deploymentNameValue The DeploymentName value. + */ + public void setDeploymentName(final String deploymentNameValue) { + this.deploymentName = deploymentNameValue; + } + + private String hostedServiceName; + + /** + * Optional. The hosted service in which the disk is being used. + * @return The HostedServiceName value. + */ + public String getHostedServiceName() { + return this.hostedServiceName; + } + + /** + * Optional. The hosted service in which the disk is being used. + * @param hostedServiceNameValue The HostedServiceName value. + */ + public void setHostedServiceName(final String hostedServiceNameValue) { + this.hostedServiceName = hostedServiceNameValue; + } + + private String roleName; + + /** + * Optional. The virtual machine that the disk is attached to. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Optional. The virtual machine that the disk is attached to. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskGetResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskGetResponse.java new file mode 100644 index 0000000000000..4f68edeeedb8a --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskGetResponse.java @@ -0,0 +1,327 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* A virtual machine disk associated with your subscription. +*/ +public class VirtualMachineDiskGetResponse extends OperationResponse { + private String affinityGroup; + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains the + * blob in which the media is located. If the storage account does not + * belong to an affinity group the value is NULL. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains the + * blob in which the media is located. If the storage account does not + * belong to an affinity group the value is NULL. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private Boolean isCorrupted; + + /** + * Optional. Specifies whether the disk is known to be corrupt. + * @return The IsCorrupted value. + */ + public Boolean isCorrupted() { + return this.isCorrupted; + } + + /** + * Optional. Specifies whether the disk is known to be corrupt. + * @param isCorruptedValue The IsCorrupted value. + */ + public void setIsCorrupted(final Boolean isCorruptedValue) { + this.isCorrupted = isCorruptedValue; + } + + private Boolean isPremium; + + /** + * Optional. Specifies whether or not the disk contains a premium virtual + * machine image. + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Specifies whether or not the disk contains a premium virtual + * machine image. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. The friendly name of the disk. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly name of the disk. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in which + * the disk is located. If the storage account belongs to an affinity group + * the value is NULL. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in which + * the disk is located. If the storage account belongs to an affinity group + * the value is NULL. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private int logicalSizeInGB; + + /** + * Optional. The size, in GB, of the disk. + * @return The LogicalSizeInGB value. + */ + public int getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the disk. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final int logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. The location of the blob in the blob store in which the media + * for the disk is located. The blob location belongs to a storage account + * in the subscription specified by the SubscriptionId value in the + * operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. The location of the blob in the blob store in which the media + * for the disk is located. The blob location belongs to a storage account + * in the subscription specified by the SubscriptionId value in the + * operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the OS image. Possible Values are: + * Linux, Windows, or NULL. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the OS image. Possible Values are: + * Linux, Windows, or NULL. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } + + private String sourceImageName; + + /** + * Optional. The name of the OS Image from which the disk was created. This + * property is populated automatically when a disk is created from an OS + * image by calling the Add Role, Create Deployment, or Provision Disk + * operations. + * @return The SourceImageName value. + */ + public String getSourceImageName() { + return this.sourceImageName; + } + + /** + * Optional. The name of the OS Image from which the disk was created. This + * property is populated automatically when a disk is created from an OS + * image by calling the Add Role, Create Deployment, or Provision Disk + * operations. + * @param sourceImageNameValue The SourceImageName value. + */ + public void setSourceImageName(final String sourceImageNameValue) { + this.sourceImageName = sourceImageNameValue; + } + + private VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails usageDetails; + + /** + * Optional. Contains properties that specify a virtual machine that is + * currently using the disk. A disk cannot be deleted as long as it is + * attached to a virtual machine. + * @return The UsageDetails value. + */ + public VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails getUsageDetails() { + return this.usageDetails; + } + + /** + * Optional. Contains properties that specify a virtual machine that is + * currently using the disk. A disk cannot be deleted as long as it is + * attached to a virtual machine. + * @param usageDetailsValue The UsageDetails value. + */ + public void setUsageDetails(final VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails usageDetailsValue) { + this.usageDetails = usageDetailsValue; + } + + /** + * Contains properties that specify a virtual machine that currently using + * the disk. A disk cannot be deleted as long as it is attached to a + * virtual machine. + */ + public static class VirtualMachineDiskUsageDetails { + private String deploymentName; + + /** + * Optional. The deployment in which the disk is being used. + * @return The DeploymentName value. + */ + public String getDeploymentName() { + return this.deploymentName; + } + + /** + * Optional. The deployment in which the disk is being used. + * @param deploymentNameValue The DeploymentName value. + */ + public void setDeploymentName(final String deploymentNameValue) { + this.deploymentName = deploymentNameValue; + } + + private String hostedServiceName; + + /** + * Optional. The hosted service in which the disk is being used. + * @return The HostedServiceName value. + */ + public String getHostedServiceName() { + return this.hostedServiceName; + } + + /** + * Optional. The hosted service in which the disk is being used. + * @param hostedServiceNameValue The HostedServiceName value. + */ + public void setHostedServiceName(final String hostedServiceNameValue) { + this.hostedServiceName = hostedServiceNameValue; + } + + private String roleName; + + /** + * Optional. The virtual machine that the disk is attached to. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Optional. The virtual machine that the disk is attached to. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskListResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskListResponse.java new file mode 100644 index 0000000000000..1cc785e49a4c6 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskListResponse.java @@ -0,0 +1,369 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Disks operation response. +*/ +public class VirtualMachineDiskListResponse extends OperationResponse implements Iterable { + private ArrayList disks; + + /** + * Optional. The virtual machine disks associated with your subscription. + * @return The Disks value. + */ + public ArrayList getDisks() { + return this.disks; + } + + /** + * Optional. The virtual machine disks associated with your subscription. + * @param disksValue The Disks value. + */ + public void setDisks(final ArrayList disksValue) { + this.disks = disksValue; + } + + /** + * Initializes a new instance of the VirtualMachineDiskListResponse class. + * + */ + public VirtualMachineDiskListResponse() { + super(); + this.disks = new ArrayList(); + } + + /** + * Gets the sequence of Disks. + * + */ + public Iterator iterator() { + return this.getDisks().iterator(); + } + + /** + * A virtual machine disk associated with your subscription. + */ + public static class VirtualMachineDisk { + private String affinityGroup; + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains + * the blob in which the media is located. If the storage account does + * not belong to an affinity group the value is NULL. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains + * the blob in which the media is located. If the storage account does + * not belong to an affinity group the value is NULL. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private Boolean isCorrupted; + + /** + * Optional. Specifies thether the disk is known to be corrupt. + * @return The IsCorrupted value. + */ + public Boolean isCorrupted() { + return this.isCorrupted; + } + + /** + * Optional. Specifies thether the disk is known to be corrupt. + * @param isCorruptedValue The IsCorrupted value. + */ + public void setIsCorrupted(final Boolean isCorruptedValue) { + this.isCorrupted = isCorruptedValue; + } + + private Boolean isPremium; + + /** + * Optional. Specifies whether or not the disk contains a premium + * virtual machine image. + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Specifies whether or not the disk contains a premium + * virtual machine image. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. The friendly name of the disk. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly name of the disk. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in + * which the disk is located. If the storage account belongs to an + * affinity group the value is NULL. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in + * which the disk is located. If the storage account belongs to an + * affinity group the value is NULL. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private int logicalSizeInGB; + + /** + * Optional. The size, in GB, of the disk. + * @return The LogicalSizeInGB value. + */ + public int getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the disk. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final int logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. The location of the blob in the blob store in which the + * media for the disk is located. The blob location belongs to a + * storage account in the subscription specified by the SubscriptionId + * value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. The location of the blob in the blob store in which the + * media for the disk is located. The blob location belongs to a + * storage account in the subscription specified by the SubscriptionId + * value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the OS image. Possible Values + * are: Linux, Windows, or NULL. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the OS image. Possible Values + * are: Linux, Windows, or NULL. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } + + private String sourceImageName; + + /** + * Optional. The name of the OS Image from which the disk was created. + * This property is populated automatically when a disk is created from + * an OS image by calling the Add Role, Create Deployment, or Provision + * Disk operations. + * @return The SourceImageName value. + */ + public String getSourceImageName() { + return this.sourceImageName; + } + + /** + * Optional. The name of the OS Image from which the disk was created. + * This property is populated automatically when a disk is created from + * an OS image by calling the Add Role, Create Deployment, or Provision + * Disk operations. + * @param sourceImageNameValue The SourceImageName value. + */ + public void setSourceImageName(final String sourceImageNameValue) { + this.sourceImageName = sourceImageNameValue; + } + + private VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails usageDetails; + + /** + * Optional. Contains properties that specify a virtual machine that + * currently using the disk. A disk cannot be deleted as long as it is + * attached to a virtual machine. + * @return The UsageDetails value. + */ + public VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails getUsageDetails() { + return this.usageDetails; + } + + /** + * Optional. Contains properties that specify a virtual machine that + * currently using the disk. A disk cannot be deleted as long as it is + * attached to a virtual machine. + * @param usageDetailsValue The UsageDetails value. + */ + public void setUsageDetails(final VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails usageDetailsValue) { + this.usageDetails = usageDetailsValue; + } + } + + /** + * Contains properties that specify a virtual machine that currently using + * the disk. A disk cannot be deleted as long as it is attached to a + * virtual machine. + */ + public static class VirtualMachineDiskUsageDetails { + private String deploymentName; + + /** + * Optional. The deployment in which the disk is being used. + * @return The DeploymentName value. + */ + public String getDeploymentName() { + return this.deploymentName; + } + + /** + * Optional. The deployment in which the disk is being used. + * @param deploymentNameValue The DeploymentName value. + */ + public void setDeploymentName(final String deploymentNameValue) { + this.deploymentName = deploymentNameValue; + } + + private String hostedServiceName; + + /** + * Optional. The hosted service in which the disk is being used. + * @return The HostedServiceName value. + */ + public String getHostedServiceName() { + return this.hostedServiceName; + } + + /** + * Optional. The hosted service in which the disk is being used. + * @param hostedServiceNameValue The HostedServiceName value. + */ + public void setHostedServiceName(final String hostedServiceNameValue) { + this.hostedServiceName = hostedServiceNameValue; + } + + private String roleName; + + /** + * Optional. The virtual machine that the disk is attached to. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Optional. The virtual machine that the disk is attached to. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskUpdateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskUpdateParameters.java new file mode 100644 index 0000000000000..55d6ffe0acbfc --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskUpdateParameters.java @@ -0,0 +1,135 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; + +/** +* Parameters supplied to the Update Virtual Disk Image operation. +*/ +public class VirtualMachineDiskUpdateParameters { + private Boolean hasOperatingSystem; + + /** + * Optional. Specifies whether the disk contains an operating system. Note: + * Only a disk with an operating system installed can be mounted as OS + * Drive. + * @return The HasOperatingSystem value. + */ + public Boolean isHasOperatingSystem() { + return this.hasOperatingSystem; + } + + /** + * Optional. Specifies whether the disk contains an operating system. Note: + * Only a disk with an operating system installed can be mounted as OS + * Drive. + * @param hasOperatingSystemValue The HasOperatingSystem value. + */ + public void setHasOperatingSystem(final Boolean hasOperatingSystemValue) { + this.hasOperatingSystem = hasOperatingSystemValue; + } + + private String label; + + /** + * Required. Specifies the friendly name of the disk. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. Specifies the friendly name of the disk. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private URI mediaLinkUri; + + /** + * Optional. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Required. Specifies a name for the disk. Azure uses the name to identify + * the disk when creating virtual machines from the disk. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. Specifies a name for the disk. Azure uses the name to identify + * the disk when creating virtual machines from the disk. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the disk. Possible values are: + * Linux or Windows. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the disk. Possible values are: + * Linux or Windows. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskUpdateResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskUpdateResponse.java new file mode 100644 index 0000000000000..abc8ccde60b5d --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineDiskUpdateResponse.java @@ -0,0 +1,198 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* A virtual machine disk associated with your subscription. +*/ +public class VirtualMachineDiskUpdateResponse extends OperationResponse { + private String affinityGroup; + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains the + * blob in which the media is located. If the storage account does not + * belong to an affinity group the value is NULL. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity group in which the disk is located. The + * AffinityGroup value is derived from storage account that contains the + * blob in which the media is located. If the storage account does not + * belong to an affinity group the value is NULL. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private Boolean isPremium; + + /** + * Optional. Specifies whether the contained image is a premium image. + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Specifies whether the contained image is a premium image. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. The friendly name of the disk + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly name of the disk + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in which + * the disk is located. If the storage account belongs to an affinity group + * the value is NULL. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which the disk is located. The Location + * value is derived from storage account that contains the blob in which + * the disk is located. If the storage account belongs to an affinity group + * the value is NULL. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private int logicalSizeInGB; + + /** + * Optional. The size, in GB, of the disk. + * @return The LogicalSizeInGB value. + */ + public int getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the disk. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final int logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. The location of the blob in the blob store in which the media + * for the disk is located. The blob location belongs to a storage account + * in the subscription specified by the SubscriptionId value in the + * operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. The location of the blob in the blob store in which the media + * for the disk is located. The blob location belongs to a storage account + * in the subscription specified by the SubscriptionId value in the + * operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the disk. This is the name that is used when + * creating one or more virtual machines using the disk. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystem; + + /** + * Optional. The Operating System type for the disk. + * @return The OperatingSystem value. + */ + public String getOperatingSystem() { + return this.operatingSystem; + } + + /** + * Optional. The Operating System type for the disk. + * @param operatingSystemValue The OperatingSystem value. + */ + public void setOperatingSystem(final String operatingSystemValue) { + this.operatingSystem = operatingSystemValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineExtensionListResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineExtensionListResponse.java new file mode 100644 index 0000000000000..544822e8d0b7c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineExtensionListResponse.java @@ -0,0 +1,349 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Resource Extensions operation response. +*/ +public class VirtualMachineExtensionListResponse extends OperationResponse implements Iterable { + private ArrayList resourceExtensions; + + /** + * Optional. The extensions that are available to add to your cloud service. + * @return The ResourceExtensions value. + */ + public ArrayList getResourceExtensions() { + return this.resourceExtensions; + } + + /** + * Optional. The extensions that are available to add to your cloud service. + * @param resourceExtensionsValue The ResourceExtensions value. + */ + public void setResourceExtensions(final ArrayList resourceExtensionsValue) { + this.resourceExtensions = resourceExtensionsValue; + } + + /** + * Initializes a new instance of the VirtualMachineExtensionListResponse + * class. + * + */ + public VirtualMachineExtensionListResponse() { + super(); + this.resourceExtensions = new ArrayList(); + } + + /** + * Gets the sequence of ResourceExtensions. + * + */ + public Iterator iterator() { + return this.getResourceExtensions().iterator(); + } + + /** + * An extension available to add to your virtual machine. + */ + public static class ResourceExtension { + private String description; + + /** + * Optional. The description of the extension. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. The description of the extension. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private URI eula; + + /** + * Optional. URI string pointing to the EULA (End User License + * Agreement) of this version of extension. This is optionally + * specified by the third-party publishing the extension instead of + * Azure, at the time of extension creation or update. + * @return The Eula value. + */ + public URI getEula() { + return this.eula; + } + + /** + * Optional. URI string pointing to the EULA (End User License + * Agreement) of this version of extension. This is optionally + * specified by the third-party publishing the extension instead of + * Azure, at the time of extension creation or update. + * @param eulaValue The Eula value. + */ + public void setEula(final URI eulaValue) { + this.eula = eulaValue; + } + + private URI homepageUri; + + /** + * Optional. URI string pointing to the homepage of this version of + * extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @return The HomepageUri value. + */ + public URI getHomepageUri() { + return this.homepageUri; + } + + /** + * Optional. URI string pointing to the homepage of this version of + * extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @param homepageUriValue The HomepageUri value. + */ + public void setHomepageUri(final URI homepageUriValue) { + this.homepageUri = homepageUriValue; + } + + private Boolean isJsonExtension; + + /** + * Optional. Indicates whether the extension accepts JSON or XML based + * configuration. If this property is 'true' the extension accepts JSON + * based configuration. If this property is 'false' the extension + * accepts XML based configuration. + * @return The IsJsonExtension value. + */ + public Boolean isJsonExtension() { + return this.isJsonExtension; + } + + /** + * Optional. Indicates whether the extension accepts JSON or XML based + * configuration. If this property is 'true' the extension accepts JSON + * based configuration. If this property is 'false' the extension + * accepts XML based configuration. + * @param isJsonExtensionValue The IsJsonExtension value. + */ + public void setIsJsonExtension(final Boolean isJsonExtensionValue) { + this.isJsonExtension = isJsonExtensionValue; + } + + private String label; + + /** + * Optional. The label that is used to identify the extension. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The label that is used to identify the extension. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Optional. The name of the extension. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the extension. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private URI privacyUri; + + /** + * Optional. URI string pointing to the privacy document of this version + * of extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. URI string pointing to the privacy document of this version + * of extension. This is optionally specified by the third-party + * publishing the extension instead of Azure, at the time of extension + * creation or update. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private String privateConfigurationSchema; + + /** + * Optional. The base64-encoded schema of the private configuration. + * @return The PrivateConfigurationSchema value. + */ + public String getPrivateConfigurationSchema() { + return this.privateConfigurationSchema; + } + + /** + * Optional. The base64-encoded schema of the private configuration. + * @param privateConfigurationSchemaValue The PrivateConfigurationSchema + * value. + */ + public void setPrivateConfigurationSchema(final String privateConfigurationSchemaValue) { + this.privateConfigurationSchema = privateConfigurationSchemaValue; + } + + private String publicConfigurationSchema; + + /** + * Optional. The base64-encoded schema of the public configuration. + * @return The PublicConfigurationSchema value. + */ + public String getPublicConfigurationSchema() { + return this.publicConfigurationSchema; + } + + /** + * Optional. The base64-encoded schema of the public configuration. + * @param publicConfigurationSchemaValue The PublicConfigurationSchema + * value. + */ + public void setPublicConfigurationSchema(final String publicConfigurationSchemaValue) { + this.publicConfigurationSchema = publicConfigurationSchemaValue; + } + + private String publisher; + + /** + * Optional. The provider namespace of the extension. The provider + * namespace for Azure extensions is Microsoft.Compute. + * @return The Publisher value. + */ + public String getPublisher() { + return this.publisher; + } + + /** + * Optional. The provider namespace of the extension. The provider + * namespace for Azure extensions is Microsoft.Compute. + * @param publisherValue The Publisher value. + */ + public void setPublisher(final String publisherValue) { + this.publisher = publisherValue; + } + + private Boolean replicationCompleted; + + /** + * Optional. Indicates whether this version of extension has been + * replicated to all regions or not. If true, then the given extension + * version can be used in creating or updating deployments. Otherwise, + * the given extension version might cause failure in creating or + * updating deployments. The typical time is 20 minutes for a + * newly-registered or newly-updated extension to replicate completely + * by Azure. + * @return The ReplicationCompleted value. + */ + public Boolean isReplicationCompleted() { + return this.replicationCompleted; + } + + /** + * Optional. Indicates whether this version of extension has been + * replicated to all regions or not. If true, then the given extension + * version can be used in creating or updating deployments. Otherwise, + * the given extension version might cause failure in creating or + * updating deployments. The typical time is 20 minutes for a + * newly-registered or newly-updated extension to replicate completely + * by Azure. + * @param replicationCompletedValue The ReplicationCompleted value. + */ + public void setReplicationCompleted(final Boolean replicationCompletedValue) { + this.replicationCompleted = replicationCompletedValue; + } + + private String sampleConfig; + + /** + * Optional. A sample configuration file for the resource extension. + * @return The SampleConfig value. + */ + public String getSampleConfig() { + return this.sampleConfig; + } + + /** + * Optional. A sample configuration file for the resource extension. + * @param sampleConfigValue The SampleConfig value. + */ + public void setSampleConfig(final String sampleConfigValue) { + this.sampleConfig = sampleConfigValue; + } + + private String version; + + /** + * Optional. The version of the extension. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. The version of the extension. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineGetRemoteDesktopFileResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineGetRemoteDesktopFileResponse.java new file mode 100644 index 0000000000000..7624c026b246a --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineGetRemoteDesktopFileResponse.java @@ -0,0 +1,51 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Download RDP file operation response. +*/ +public class VirtualMachineGetRemoteDesktopFileResponse extends OperationResponse { + private byte[] remoteDesktopFile; + + /** + * Required. A Remote Desktop Protocol (.rdp) file that can be used to + * establish a remote desktop session to the virtual machine + * @return The RemoteDesktopFile value. + */ + public byte[] getRemoteDesktopFile() { + return this.remoteDesktopFile; + } + + /** + * Required. A Remote Desktop Protocol (.rdp) file that can be used to + * establish a remote desktop session to the virtual machine + * @param remoteDesktopFileValue The RemoteDesktopFile value. + */ + public void setRemoteDesktopFile(final byte[] remoteDesktopFileValue) { + this.remoteDesktopFile = remoteDesktopFileValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineGetResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineGetResponse.java new file mode 100644 index 0000000000000..8aaa35abd3c4c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineGetResponse.java @@ -0,0 +1,225 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; + +/** +* The Get Virtual Machine operation response. +*/ +public class VirtualMachineGetResponse extends OperationResponse { + private String availabilitySetName; + + /** + * Optional. The name of the availability set the virtual machine belongs + * to. This value controls the virtual machine allocation in the Windows + * Azure environment. Virtual machines specified in the same availability + * set are allocated to different nodes to maximize availability. + * @return The AvailabilitySetName value. + */ + public String getAvailabilitySetName() { + return this.availabilitySetName; + } + + /** + * Optional. The name of the availability set the virtual machine belongs + * to. This value controls the virtual machine allocation in the Windows + * Azure environment. Virtual machines specified in the same availability + * set are allocated to different nodes to maximize availability. + * @param availabilitySetNameValue The AvailabilitySetName value. + */ + public void setAvailabilitySetName(final String availabilitySetNameValue) { + this.availabilitySetName = availabilitySetNameValue; + } + + private ArrayList configurationSets; + + /** + * Optional. Contains the collection of configuration sets that contain + * system and application configuration settings. + * @return The ConfigurationSets value. + */ + public ArrayList getConfigurationSets() { + return this.configurationSets; + } + + /** + * Optional. Contains the collection of configuration sets that contain + * system and application configuration settings. + * @param configurationSetsValue The ConfigurationSets value. + */ + public void setConfigurationSets(final ArrayList configurationSetsValue) { + this.configurationSets = configurationSetsValue; + } + + private ArrayList dataVirtualHardDisks; + + /** + * Optional. Contains the parameters Azure used to create the data disk for + * the virtual machine. + * @return The DataVirtualHardDisks value. + */ + public ArrayList getDataVirtualHardDisks() { + return this.dataVirtualHardDisks; + } + + /** + * Optional. Contains the parameters Azure used to create the data disk for + * the virtual machine. + * @param dataVirtualHardDisksValue The DataVirtualHardDisks value. + */ + public void setDataVirtualHardDisks(final ArrayList dataVirtualHardDisksValue) { + this.dataVirtualHardDisks = dataVirtualHardDisksValue; + } + + private String defaultWinRmCertificateThumbprint; + + /** + * Optional. The read-only thumbprint of the certificate that is used with + * the HTTPS listener for WinRM. + * @return The DefaultWinRmCertificateThumbprint value. + */ + public String getDefaultWinRmCertificateThumbprint() { + return this.defaultWinRmCertificateThumbprint; + } + + /** + * Optional. The read-only thumbprint of the certificate that is used with + * the HTTPS listener for WinRM. + * @param defaultWinRmCertificateThumbprintValue The + * DefaultWinRmCertificateThumbprint value. + */ + public void setDefaultWinRmCertificateThumbprint(final String defaultWinRmCertificateThumbprintValue) { + this.defaultWinRmCertificateThumbprint = defaultWinRmCertificateThumbprintValue; + } + + private String osVersion; + + /** + * Optional. The version of the operating system on which the role instances + * are running. + * @return The OsVersion value. + */ + public String getOsVersion() { + return this.osVersion; + } + + /** + * Optional. The version of the operating system on which the role instances + * are running. + * @param osVersionValue The OsVersion value. + */ + public void setOsVersion(final String osVersionValue) { + this.osVersion = osVersionValue; + } + + private OSVirtualHardDisk oSVirtualHardDisk; + + /** + * Optional. Contains the parameters Azure used to create the operating + * system disk for the virtual machine. + * @return The OSVirtualHardDisk value. + */ + public OSVirtualHardDisk getOSVirtualHardDisk() { + return this.oSVirtualHardDisk; + } + + /** + * Optional. Contains the parameters Azure used to create the operating + * system disk for the virtual machine. + * @param oSVirtualHardDiskValue The OSVirtualHardDisk value. + */ + public void setOSVirtualHardDisk(final OSVirtualHardDisk oSVirtualHardDiskValue) { + this.oSVirtualHardDisk = oSVirtualHardDiskValue; + } + + private String roleName; + + /** + * Optional. The name for the virtual machine. The name is unique within + * Azure. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Optional. The name for the virtual machine. The name is unique within + * Azure. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + + private String roleSize; + + /** + * Optional. The size of the virtual machine. + * @return The RoleSize value. + */ + public String getRoleSize() { + return this.roleSize; + } + + /** + * Optional. The size of the virtual machine. + * @param roleSizeValue The RoleSize value. + */ + public void setRoleSize(final String roleSizeValue) { + this.roleSize = roleSizeValue; + } + + private VirtualMachineRoleType roleType; + + /** + * Optional. The type of the role for the virtual machine. The only + * supported value is PersistentVMRole. + * @return The RoleType value. + */ + public VirtualMachineRoleType getRoleType() { + return this.roleType; + } + + /** + * Optional. The type of the role for the virtual machine. The only + * supported value is PersistentVMRole. + * @param roleTypeValue The RoleType value. + */ + public void setRoleType(final VirtualMachineRoleType roleTypeValue) { + this.roleType = roleTypeValue; + } + + /** + * Initializes a new instance of the VirtualMachineGetResponse class. + * + */ + public VirtualMachineGetResponse() { + super(); + this.configurationSets = new ArrayList(); + this.dataVirtualHardDisks = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageCreateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageCreateParameters.java new file mode 100644 index 0000000000000..a09b0e67e50b9 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageCreateParameters.java @@ -0,0 +1,332 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; +import java.util.Calendar; + +/** +* Parameters supplied to the Create Virtual Machine Image operation. +*/ +public class VirtualMachineOSImageCreateParameters { + private String description; + + /** + * Optional. Specifies the description of the OS image. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Specifies the description of the OS image. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String eula; + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @return The Eula value. + */ + public String getEula() { + return this.eula; + } + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @param eulaValue The Eula value. + */ + public void setEula(final String eulaValue) { + this.eula = eulaValue; + } + + private URI iconUri; + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @return The IconUri value. + */ + public URI getIconUri() { + return this.iconUri; + } + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @param iconUriValue The IconUri value. + */ + public void setIconUri(final URI iconUriValue) { + this.iconUri = iconUriValue; + } + + private String imageFamily; + + /** + * Optional. Specifies a value that can be used to group OS images. + * @return The ImageFamily value. + */ + public String getImageFamily() { + return this.imageFamily; + } + + /** + * Optional. Specifies a value that can be used to group OS images. + * @param imageFamilyValue The ImageFamily value. + */ + public void setImageFamily(final String imageFamilyValue) { + this.imageFamily = imageFamilyValue; + } + + private boolean isPremium; + + /** + * Required. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @return The IsPremium value. + */ + public boolean isPremium() { + return this.isPremium; + } + + /** + * Required. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Required. Specifies the friendly name of the image. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. Specifies the friendly name of the image. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String language; + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @return The Language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @param languageValue The Language value. + */ + public void setLanguage(final String languageValue) { + this.language = languageValue; + } + + private URI mediaLinkUri; + + /** + * Required. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Required. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Required. Specifies a name that Azure uses to identify the image when + * creating one or more virtual machines. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. Specifies a name that Azure uses to identify the image when + * creating one or more virtual machines. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Required. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Required. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } + + private URI privacyUri; + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private Calendar publishedDate; + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @return The PublishedDate value. + */ + public Calendar getPublishedDate() { + return this.publishedDate; + } + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @param publishedDateValue The PublishedDate value. + */ + public void setPublishedDate(final Calendar publishedDateValue) { + this.publishedDate = publishedDateValue; + } + + private String recommendedVMSize; + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @return The RecommendedVMSize value. + */ + public String getRecommendedVMSize() { + return this.recommendedVMSize; + } + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @param recommendedVMSizeValue The RecommendedVMSize value. + */ + public void setRecommendedVMSize(final String recommendedVMSizeValue) { + this.recommendedVMSize = recommendedVMSizeValue; + } + + private boolean showInGui; + + /** + * Required. Specifies whether the image should appear in the image gallery. + * @return The ShowInGui value. + */ + public boolean isShowInGui() { + return this.showInGui; + } + + /** + * Required. Specifies whether the image should appear in the image gallery. + * @param showInGuiValue The ShowInGui value. + */ + public void setShowInGui(final boolean showInGuiValue) { + this.showInGui = showInGuiValue; + } + + private URI smallIconUri; + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @return The SmallIconUri value. + */ + public URI getSmallIconUri() { + return this.smallIconUri; + } + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @param smallIconUriValue The SmallIconUri value. + */ + public void setSmallIconUri(final URI smallIconUriValue) { + this.smallIconUri = smallIconUriValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageCreateResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageCreateResponse.java new file mode 100644 index 0000000000000..c23e85e432ce3 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageCreateResponse.java @@ -0,0 +1,417 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.Calendar; + +/** +* Parameters returned from the Create Virtual Machine Image operation. +*/ +public class VirtualMachineOSImageCreateResponse extends OperationResponse { + private String category; + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @return The Category value. + */ + public String getCategory() { + return this.category; + } + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @param categoryValue The Category value. + */ + public void setCategory(final String categoryValue) { + this.category = categoryValue; + } + + private String description; + + /** + * Optional. Specifies the description of the OS image. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Specifies the description of the OS image. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String eula; + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @return The Eula value. + */ + public String getEula() { + return this.eula; + } + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @param eulaValue The Eula value. + */ + public void setEula(final String eulaValue) { + this.eula = eulaValue; + } + + private URI iconUri; + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @return The IconUri value. + */ + public URI getIconUri() { + return this.iconUri; + } + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @param iconUriValue The IconUri value. + */ + public void setIconUri(final URI iconUriValue) { + this.iconUri = iconUriValue; + } + + private String imageFamily; + + /** + * Optional. Specifies a value that can be used to group OS images. + * @return The ImageFamily value. + */ + public String getImageFamily() { + return this.imageFamily; + } + + /** + * Optional. Specifies a value that can be used to group OS images. + * @param imageFamilyValue The ImageFamily value. + */ + public void setImageFamily(final String imageFamilyValue) { + this.imageFamily = imageFamilyValue; + } + + private Boolean isPremium; + + /** + * Optional. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. Specifies the friendly name of the image. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Specifies the friendly name of the image. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String language; + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @return The Language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @param languageValue The Language value. + */ + public void setLanguage(final String languageValue) { + this.language = languageValue; + } + + private String location; + + /** + * Optional. The geo-location in which this media is located. The Location + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account belongs to an affinity + * group the value is NULL. If the version is set to 2012-08-01 or later, + * the locations are returned for platform images; otherwise, this value is + * NULL for platform images. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which this media is located. The Location + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account belongs to an affinity + * group the value is NULL. If the version is set to 2012-08-01 or later, + * the locations are returned for platform images; otherwise, this value is + * NULL for platform images. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private double logicalSizeInGB; + + /** + * Optional. The size, in GB, of the image. + * @return The LogicalSizeInGB value. + */ + public double getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the image. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final double logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. Specifies a name that Azure uses to identify the image when + * creating one or more virtual machines. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies a name that Azure uses to identify the image when + * creating one or more virtual machines. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } + + private URI privacyUri; + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private Calendar publishedDate; + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @return The PublishedDate value. + */ + public Calendar getPublishedDate() { + return this.publishedDate; + } + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @param publishedDateValue The PublishedDate value. + */ + public void setPublishedDate(final Calendar publishedDateValue) { + this.publishedDate = publishedDateValue; + } + + private String publisherName; + + /** + * Optional. Specifies the name of the publisher of the image. + * @return The PublisherName value. + */ + public String getPublisherName() { + return this.publisherName; + } + + /** + * Optional. Specifies the name of the publisher of the image. + * @param publisherNameValue The PublisherName value. + */ + public void setPublisherName(final String publisherNameValue) { + this.publisherName = publisherNameValue; + } + + private String recommendedVMSize; + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @return The RecommendedVMSize value. + */ + public String getRecommendedVMSize() { + return this.recommendedVMSize; + } + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @param recommendedVMSizeValue The RecommendedVMSize value. + */ + public void setRecommendedVMSize(final String recommendedVMSizeValue) { + this.recommendedVMSize = recommendedVMSizeValue; + } + + private Boolean showInGui; + + /** + * Optional. Specifies whether the image should appear in the image gallery. + * @return The ShowInGui value. + */ + public Boolean isShowInGui() { + return this.showInGui; + } + + /** + * Optional. Specifies whether the image should appear in the image gallery. + * @param showInGuiValue The ShowInGui value. + */ + public void setShowInGui(final Boolean showInGuiValue) { + this.showInGui = showInGuiValue; + } + + private URI smallIconUri; + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @return The SmallIconUri value. + */ + public URI getSmallIconUri() { + return this.smallIconUri; + } + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @param smallIconUriValue The SmallIconUri value. + */ + public void setSmallIconUri(final URI smallIconUriValue) { + this.smallIconUri = smallIconUriValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageGetResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageGetResponse.java new file mode 100644 index 0000000000000..f7d702839b07f --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageGetResponse.java @@ -0,0 +1,443 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.Calendar; + +/** +* A virtual machine image associated with your subscription. +*/ +public class VirtualMachineOSImageGetResponse extends OperationResponse { + private String affinityGroup; + + /** + * Optional. The affinity in which the media is located. The AffinityGroup + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account does not belong to an + * affinity group the value is NULL and the element is not displayed in the + * response. This value is NULL for platform images. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity in which the media is located. The AffinityGroup + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account does not belong to an + * affinity group the value is NULL and the element is not displayed in the + * response. This value is NULL for platform images. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String category; + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @return The Category value. + */ + public String getCategory() { + return this.category; + } + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @param categoryValue The Category value. + */ + public void setCategory(final String categoryValue) { + this.category = categoryValue; + } + + private String description; + + /** + * Optional. Specifies the description of the image. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Specifies the description of the image. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String eula; + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @return The Eula value. + */ + public String getEula() { + return this.eula; + } + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @param eulaValue The Eula value. + */ + public void setEula(final String eulaValue) { + this.eula = eulaValue; + } + + private URI iconUri; + + /** + * Optional. Provides the URI to the icon for this Operating System Image. + * @return The IconUri value. + */ + public URI getIconUri() { + return this.iconUri; + } + + /** + * Optional. Provides the URI to the icon for this Operating System Image. + * @param iconUriValue The IconUri value. + */ + public void setIconUri(final URI iconUriValue) { + this.iconUri = iconUriValue; + } + + private String imageFamily; + + /** + * Optional. Specifies a value that can be used to group images. + * @return The ImageFamily value. + */ + public String getImageFamily() { + return this.imageFamily; + } + + /** + * Optional. Specifies a value that can be used to group images. + * @param imageFamilyValue The ImageFamily value. + */ + public void setImageFamily(final String imageFamilyValue) { + this.imageFamily = imageFamilyValue; + } + + private Boolean isPremium; + + /** + * Optional. Indicates whether the image contains software or associated + * services that will incur charges above the core price for the virtual + * machine. For additional details, see the PricingDetailLink element. + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Indicates whether the image contains software or associated + * services that will incur charges above the core price for the virtual + * machine. For additional details, see the PricingDetailLink element. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. An identifier for the image. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. An identifier for the image. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String language; + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @return The Language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @param languageValue The Language value. + */ + public void setLanguage(final String languageValue) { + this.language = languageValue; + } + + private String location; + + /** + * Optional. The geo-location in which this media is located. The Location + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account belongs to an affinity + * group the value is NULL. If the version is set to 2012-08-01 or later, + * the locations are returned for platform images; otherwise, this value is + * NULL for platform images. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which this media is located. The Location + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account belongs to an affinity + * group the value is NULL. If the version is set to 2012-08-01 or later, + * the locations are returned for platform images; otherwise, this value is + * NULL for platform images. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private double logicalSizeInGB; + + /** + * Optional. The size, in GB, of the image. + * @return The LogicalSizeInGB value. + */ + public double getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the image. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final double logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. The location of the blob in Azure storage. The blob location + * belongs to a storage account in the subscription specified by the + * SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/myimage.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. The location of the blob in Azure storage. The blob location + * belongs to a storage account in the subscription specified by the + * SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/myimage.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. The name of the operating system image. This is the name that + * is used when creating one or more virtual machines using the image. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the operating system image. This is the name that + * is used when creating one or more virtual machines using the image. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } + + private URI privacyUri; + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the image. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the image. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private Calendar publishedDate; + + /** + * Optional. Specifies the date when the image was added to the image + * repository. + * @return The PublishedDate value. + */ + public Calendar getPublishedDate() { + return this.publishedDate; + } + + /** + * Optional. Specifies the date when the image was added to the image + * repository. + * @param publishedDateValue The PublishedDate value. + */ + public void setPublishedDate(final Calendar publishedDateValue) { + this.publishedDate = publishedDateValue; + } + + private String publisherName; + + /** + * Optional. The name of the publisher of this OS Image in Azure. + * @return The PublisherName value. + */ + public String getPublisherName() { + return this.publisherName; + } + + /** + * Optional. The name of the publisher of this OS Image in Azure. + * @param publisherNameValue The PublisherName value. + */ + public void setPublisherName(final String publisherNameValue) { + this.publisherName = publisherNameValue; + } + + private String recommendedVMSize; + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @return The RecommendedVMSize value. + */ + public String getRecommendedVMSize() { + return this.recommendedVMSize; + } + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @param recommendedVMSizeValue The RecommendedVMSize value. + */ + public void setRecommendedVMSize(final String recommendedVMSizeValue) { + this.recommendedVMSize = recommendedVMSizeValue; + } + + private Boolean showInGui; + + /** + * Optional. Indicates whether the image should be shown in the Azure portal. + * @return The ShowInGui value. + */ + public Boolean isShowInGui() { + return this.showInGui; + } + + /** + * Optional. Indicates whether the image should be shown in the Azure portal. + * @param showInGuiValue The ShowInGui value. + */ + public void setShowInGui(final Boolean showInGuiValue) { + this.showInGui = showInGuiValue; + } + + private URI smallIconUri; + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @return The SmallIconUri value. + */ + public URI getSmallIconUri() { + return this.smallIconUri; + } + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @param smallIconUriValue The SmallIconUri value. + */ + public void setSmallIconUri(final URI smallIconUriValue) { + this.smallIconUri = smallIconUriValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageListResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageListResponse.java new file mode 100644 index 0000000000000..4a74ea7e7eb6e --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageListResponse.java @@ -0,0 +1,481 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; + +/** +* The List OS Images operation response. +*/ +public class VirtualMachineOSImageListResponse extends OperationResponse implements Iterable { + private ArrayList images; + + /** + * Optional. The virtual machine images associated with your subscription. + * @return The Images value. + */ + public ArrayList getImages() { + return this.images; + } + + /** + * Optional. The virtual machine images associated with your subscription. + * @param imagesValue The Images value. + */ + public void setImages(final ArrayList imagesValue) { + this.images = imagesValue; + } + + /** + * Initializes a new instance of the VirtualMachineOSImageListResponse class. + * + */ + public VirtualMachineOSImageListResponse() { + super(); + this.images = new ArrayList(); + } + + /** + * Gets the sequence of Images. + * + */ + public Iterator iterator() { + return this.getImages().iterator(); + } + + /** + * A virtual machine image associated with your subscription. + */ + public static class VirtualMachineOSImage { + private String affinityGroup; + + /** + * Optional. The affinity in which the media is located. The + * AffinityGroup value is derived from storage account that contains + * the blob in which the media is located. If the storage account does + * not belong to an affinity group the value is NULL and the element is + * not displayed in the response. This value is NULL for platform + * images. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity in which the media is located. The + * AffinityGroup value is derived from storage account that contains + * the blob in which the media is located. If the storage account does + * not belong to an affinity group the value is NULL and the element is + * not displayed in the response. This value is NULL for platform + * images. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String category; + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @return The Category value. + */ + public String getCategory() { + return this.category; + } + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @param categoryValue The Category value. + */ + public void setCategory(final String categoryValue) { + this.category = categoryValue; + } + + private String description; + + /** + * Optional. Specifies the description of the image. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Specifies the description of the image. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String eula; + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @return The Eula value. + */ + public String getEula() { + return this.eula; + } + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @param eulaValue The Eula value. + */ + public void setEula(final String eulaValue) { + this.eula = eulaValue; + } + + private String imageFamily; + + /** + * Optional. Specifies a value that can be used to group images. + * @return The ImageFamily value. + */ + public String getImageFamily() { + return this.imageFamily; + } + + /** + * Optional. Specifies a value that can be used to group images. + * @param imageFamilyValue The ImageFamily value. + */ + public void setImageFamily(final String imageFamilyValue) { + this.imageFamily = imageFamilyValue; + } + + private Boolean isPremium; + + /** + * Optional. Indicates whether the image contains software or associated + * services that will incur charges above the core price for the + * virtual machine. For additional details, see the PricingDetailLink + * element. + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Indicates whether the image contains software or associated + * services that will incur charges above the core price for the + * virtual machine. For additional details, see the PricingDetailLink + * element. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. An identifier for the image. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. An identifier for the image. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String language; + + /** + * Optional. Specifies the language of the image. The Language element + * is only available using version 2013-03-01 or higher. + * @return The Language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Optional. Specifies the language of the image. The Language element + * is only available using version 2013-03-01 or higher. + * @param languageValue The Language value. + */ + public void setLanguage(final String languageValue) { + this.language = languageValue; + } + + private String location; + + /** + * Optional. The geo-location in which this media is located. The + * Location value is derived from storage account that contains the + * blob in which the media is located. If the storage account belongs + * to an affinity group the value is NULL. If the version is set to + * 2012-08-01 or later, the locations are returned for platform images; + * otherwise, this value is NULL for platform images. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which this media is located. The + * Location value is derived from storage account that contains the + * blob in which the media is located. If the storage account belongs + * to an affinity group the value is NULL. If the version is set to + * 2012-08-01 or later, the locations are returned for platform images; + * otherwise, this value is NULL for platform images. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private double logicalSizeInGB; + + /** + * Optional. The size, in GB, of the image. + * @return The LogicalSizeInGB value. + */ + public double getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the image. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final double logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. The location of the blob in Azure storage. The blob + * location belongs to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/myimage.vhd + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. The location of the blob in Azure storage. The blob + * location belongs to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/myimage.vhd + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. The name of the operating system image. This is the name + * that is used when creating one or more virtual machines using the + * image. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the operating system image. This is the name + * that is used when creating one or more virtual machines using the + * image. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the OS image. Possible values + * are: Linux, Windows. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the OS image. Possible values + * are: Linux, Windows. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } + + private URI pricingDetailUri; + + /** + * Optional. Specifies a URL for an image with IsPremium set to true, + * which contains the pricing details for a virtual machine that is + * created from the image. The PricingDetailLink element is only + * available using version 2012-12-01 or higher. + * @return The PricingDetailUri value. + */ + public URI getPricingDetailUri() { + return this.pricingDetailUri; + } + + /** + * Optional. Specifies a URL for an image with IsPremium set to true, + * which contains the pricing details for a virtual machine that is + * created from the image. The PricingDetailLink element is only + * available using version 2012-12-01 or higher. + * @param pricingDetailUriValue The PricingDetailUri value. + */ + public void setPricingDetailUri(final URI pricingDetailUriValue) { + this.pricingDetailUri = pricingDetailUriValue; + } + + private URI privacyUri; + + /** + * Optional. Specifies the URI that points to a document that contains + * the privacy policy related to the image. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. Specifies the URI that points to a document that contains + * the privacy policy related to the image. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private Calendar publishedDate; + + /** + * Optional. Specifies the date when the image was added to the image + * repository. + * @return The PublishedDate value. + */ + public Calendar getPublishedDate() { + return this.publishedDate; + } + + /** + * Optional. Specifies the date when the image was added to the image + * repository. + * @param publishedDateValue The PublishedDate value. + */ + public void setPublishedDate(final Calendar publishedDateValue) { + this.publishedDate = publishedDateValue; + } + + private String publisherName; + + /** + * Optional. The name of the publisher of this OS Image in Azure. + * @return The PublisherName value. + */ + public String getPublisherName() { + return this.publisherName; + } + + /** + * Optional. The name of the publisher of this OS Image in Azure. + * @param publisherNameValue The PublisherName value. + */ + public void setPublisherName(final String publisherNameValue) { + this.publisherName = publisherNameValue; + } + + private String recommendedVMSize; + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @return The RecommendedVMSize value. + */ + public String getRecommendedVMSize() { + return this.recommendedVMSize; + } + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @param recommendedVMSizeValue The RecommendedVMSize value. + */ + public void setRecommendedVMSize(final String recommendedVMSizeValue) { + this.recommendedVMSize = recommendedVMSizeValue; + } + + private URI smallIconUri; + + /** + * Optional. Specifies the URI to the small icon that is displayed when + * the image is presented in the Azure Management Portal. The + * SmallIconUri element is only available using version 2013-03-01 or + * higher. + * @return The SmallIconUri value. + */ + public URI getSmallIconUri() { + return this.smallIconUri; + } + + /** + * Optional. Specifies the URI to the small icon that is displayed when + * the image is presented in the Azure Management Portal. The + * SmallIconUri element is only available using version 2013-03-01 or + * higher. + * @param smallIconUriValue The SmallIconUri value. + */ + public void setSmallIconUri(final URI smallIconUriValue) { + this.smallIconUri = smallIconUriValue; + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageOperatingSystemType.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageOperatingSystemType.java new file mode 100644 index 0000000000000..e35d3908a90fc --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageOperatingSystemType.java @@ -0,0 +1,34 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Known values for the operating system type of the OS in a virtual machine +* image. +*/ +public abstract class VirtualMachineOSImageOperatingSystemType { + public static final String LINUX = "Linux"; + + public static final String WINDOWS = "Windows"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageUpdateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageUpdateParameters.java new file mode 100644 index 0000000000000..b0a6bb1922923 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageUpdateParameters.java @@ -0,0 +1,254 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.URI; +import java.util.Calendar; + +/** +* Parameters supplied to the Update Virtual Machine Image operation. +*/ +public class VirtualMachineOSImageUpdateParameters { + private String description; + + /** + * Optional. Specifies the description of the OS image. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Specifies the description of the OS image. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String eula; + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @return The Eula value. + */ + public String getEula() { + return this.eula; + } + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @param eulaValue The Eula value. + */ + public void setEula(final String eulaValue) { + this.eula = eulaValue; + } + + private URI iconUri; + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @return The IconUri value. + */ + public URI getIconUri() { + return this.iconUri; + } + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @param iconUriValue The IconUri value. + */ + public void setIconUri(final URI iconUriValue) { + this.iconUri = iconUriValue; + } + + private String imageFamily; + + /** + * Optional. Specifies a value that can be used to group OS images. + * @return The ImageFamily value. + */ + public String getImageFamily() { + return this.imageFamily; + } + + /** + * Optional. Specifies a value that can be used to group OS images. + * @param imageFamilyValue The ImageFamily value. + */ + public void setImageFamily(final String imageFamilyValue) { + this.imageFamily = imageFamilyValue; + } + + private boolean isPremium; + + /** + * Optional. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @return The IsPremium value. + */ + public boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Required. Specifies the friendly name of the image to be updated. You + * cannot use this operation to update images provided by the Azure + * platform. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. Specifies the friendly name of the image to be updated. You + * cannot use this operation to update images provided by the Azure + * platform. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String language; + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @return The Language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @param languageValue The Language value. + */ + public void setLanguage(final String languageValue) { + this.language = languageValue; + } + + private URI privacyUri; + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private Calendar publishedDate; + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @return The PublishedDate value. + */ + public Calendar getPublishedDate() { + return this.publishedDate; + } + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @param publishedDateValue The PublishedDate value. + */ + public void setPublishedDate(final Calendar publishedDateValue) { + this.publishedDate = publishedDateValue; + } + + private String recommendedVMSize; + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @return The RecommendedVMSize value. + */ + public String getRecommendedVMSize() { + return this.recommendedVMSize; + } + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @param recommendedVMSizeValue The RecommendedVMSize value. + */ + public void setRecommendedVMSize(final String recommendedVMSizeValue) { + this.recommendedVMSize = recommendedVMSizeValue; + } + + private URI smallIconUri; + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @return The SmallIconUri value. + */ + public URI getSmallIconUri() { + return this.smallIconUri; + } + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @param smallIconUriValue The SmallIconUri value. + */ + public void setSmallIconUri(final URI smallIconUriValue) { + this.smallIconUri = smallIconUriValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageUpdateResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageUpdateResponse.java new file mode 100644 index 0000000000000..9ed2d70978815 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineOSImageUpdateResponse.java @@ -0,0 +1,417 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.Calendar; + +/** +* Parameters returned from the Create Virtual Machine Image operation. +*/ +public class VirtualMachineOSImageUpdateResponse extends OperationResponse { + private String category; + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @return The Category value. + */ + public String getCategory() { + return this.category; + } + + /** + * Optional. The repository classification of the image. All user images + * have the category User. + * @param categoryValue The Category value. + */ + public void setCategory(final String categoryValue) { + this.category = categoryValue; + } + + private String description; + + /** + * Optional. Specifies the description of the OS image. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Specifies the description of the OS image. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String eula; + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @return The Eula value. + */ + public String getEula() { + return this.eula; + } + + /** + * Optional. Specifies the End User License Agreement that is associated + * with the image. The value for this element is a string, but it is + * recommended that the value be a URL that points to a EULA. + * @param eulaValue The Eula value. + */ + public void setEula(final String eulaValue) { + this.eula = eulaValue; + } + + private URI iconUri; + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @return The IconUri value. + */ + public URI getIconUri() { + return this.iconUri; + } + + /** + * Optional. Specifies the URI to the icon that is displayed for the image + * in the Management Portal. + * @param iconUriValue The IconUri value. + */ + public void setIconUri(final URI iconUriValue) { + this.iconUri = iconUriValue; + } + + private String imageFamily; + + /** + * Optional. Specifies a value that can be used to group OS images. + * @return The ImageFamily value. + */ + public String getImageFamily() { + return this.imageFamily; + } + + /** + * Optional. Specifies a value that can be used to group OS images. + * @param imageFamilyValue The ImageFamily value. + */ + public void setImageFamily(final String imageFamilyValue) { + this.imageFamily = imageFamilyValue; + } + + private Boolean isPremium; + + /** + * Optional. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @return The IsPremium value. + */ + public Boolean isPremium() { + return this.isPremium; + } + + /** + * Optional. Indicates if the image contains software or associated services + * that will incur charges above the core price for the virtual machine. + * @param isPremiumValue The IsPremium value. + */ + public void setIsPremium(final Boolean isPremiumValue) { + this.isPremium = isPremiumValue; + } + + private String label; + + /** + * Optional. Specifies the friendly name of the image. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Specifies the friendly name of the image. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String language; + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @return The Language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Optional. Specifies the language of the image. The Language element is + * only available using version 2013-03-01 or higher. + * @param languageValue The Language value. + */ + public void setLanguage(final String languageValue) { + this.language = languageValue; + } + + private String location; + + /** + * Optional. The geo-location in which this media is located. The Location + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account belongs to an affinity + * group the value is NULL. If the version is set to 2012-08-01 or later, + * the locations are returned for platform images; otherwise, this value is + * NULL for platform images. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location in which this media is located. The Location + * value is derived from storage account that contains the blob in which + * the media is located. If the storage account belongs to an affinity + * group the value is NULL. If the version is set to 2012-08-01 or later, + * the locations are returned for platform images; otherwise, this value is + * NULL for platform images. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private double logicalSizeInGB; + + /** + * Optional. The size, in GB, of the image. + * @return The LogicalSizeInGB value. + */ + public double getLogicalSizeInGB() { + return this.logicalSizeInGB; + } + + /** + * Optional. The size, in GB, of the image. + * @param logicalSizeInGBValue The LogicalSizeInGB value. + */ + public void setLogicalSizeInGB(final double logicalSizeInGBValue) { + this.logicalSizeInGB = logicalSizeInGBValue; + } + + private URI mediaLinkUri; + + /** + * Optional. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @return The MediaLinkUri value. + */ + public URI getMediaLinkUri() { + return this.mediaLinkUri; + } + + /** + * Optional. Specifies the location of the blob in Azure storage. The blob + * location must belong to a storage account in the subscription specified + * by the SubscriptionId value in the operation call. Example: + * http://example.blob.core.windows.net/disks/mydisk.vhd. + * @param mediaLinkUriValue The MediaLinkUri value. + */ + public void setMediaLinkUri(final URI mediaLinkUriValue) { + this.mediaLinkUri = mediaLinkUriValue; + } + + private String name; + + /** + * Optional. Specifies a name that Azure uses to identify the image when + * creating one or more virtual machines. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies a name that Azure uses to identify the image when + * creating one or more virtual machines. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystemType; + + /** + * Optional. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @return The OperatingSystemType value. + */ + public String getOperatingSystemType() { + return this.operatingSystemType; + } + + /** + * Optional. The operating system type of the OS image. Possible values are: + * Linux or Windows. + * @param operatingSystemTypeValue The OperatingSystemType value. + */ + public void setOperatingSystemType(final String operatingSystemTypeValue) { + this.operatingSystemType = operatingSystemTypeValue; + } + + private URI privacyUri; + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @return The PrivacyUri value. + */ + public URI getPrivacyUri() { + return this.privacyUri; + } + + /** + * Optional. Specifies the URI that points to a document that contains the + * privacy policy related to the OS image. + * @param privacyUriValue The PrivacyUri value. + */ + public void setPrivacyUri(final URI privacyUriValue) { + this.privacyUri = privacyUriValue; + } + + private Calendar publishedDate; + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @return The PublishedDate value. + */ + public Calendar getPublishedDate() { + return this.publishedDate; + } + + /** + * Optional. Specifies the date when the OS image was added to the image + * repository. + * @param publishedDateValue The PublishedDate value. + */ + public void setPublishedDate(final Calendar publishedDateValue) { + this.publishedDate = publishedDateValue; + } + + private String publisherName; + + /** + * Optional. Specifies the name of the publisher of the image. + * @return The PublisherName value. + */ + public String getPublisherName() { + return this.publisherName; + } + + /** + * Optional. Specifies the name of the publisher of the image. + * @param publisherNameValue The PublisherName value. + */ + public void setPublisherName(final String publisherNameValue) { + this.publisherName = publisherNameValue; + } + + private String recommendedVMSize; + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @return The RecommendedVMSize value. + */ + public String getRecommendedVMSize() { + return this.recommendedVMSize; + } + + /** + * Optional. Specifies the size to use for the virtual machine that is + * created from the OS image. + * @param recommendedVMSizeValue The RecommendedVMSize value. + */ + public void setRecommendedVMSize(final String recommendedVMSizeValue) { + this.recommendedVMSize = recommendedVMSizeValue; + } + + private Boolean showInGui; + + /** + * Optional. Specifies whether the image should appear in the image gallery. + * @return The ShowInGui value. + */ + public Boolean isShowInGui() { + return this.showInGui; + } + + /** + * Optional. Specifies whether the image should appear in the image gallery. + * @param showInGuiValue The ShowInGui value. + */ + public void setShowInGui(final Boolean showInGuiValue) { + this.showInGui = showInGuiValue; + } + + private URI smallIconUri; + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @return The SmallIconUri value. + */ + public URI getSmallIconUri() { + return this.smallIconUri; + } + + /** + * Optional. Specifies the URI to the small icon that is displayed when the + * image is presented in the Azure Management Portal. The SmallIconUri + * element is only available using version 2013-03-01 or higher. + * @param smallIconUriValue The SmallIconUri value. + */ + public void setSmallIconUri(final URI smallIconUriValue) { + this.smallIconUri = smallIconUriValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineRoleSize.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineRoleSize.java new file mode 100644 index 0000000000000..bb22efcb13914 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineRoleSize.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The size of a virtual machine. +*/ +public abstract class VirtualMachineRoleSize { + public static final String SMALL = "Small"; + + public static final String EXTRASMALL = "ExtraSmall"; + + public static final String LARGE = "Large"; + + public static final String MEDIUM = "Medium"; + + public static final String EXTRALARGE = "ExtraLarge"; + + public static final String A5 = "A5"; + + public static final String A6 = "A6"; + + public static final String A7 = "A7"; + + public static final String A8 = "A8"; + + public static final String A9 = "A9"; +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineRoleType.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineRoleType.java new file mode 100644 index 0000000000000..d28ee096be86b --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineRoleType.java @@ -0,0 +1,31 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The type of the role for the virtual machine. +*/ +public enum VirtualMachineRoleType { + PersistentVMRole, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineShutdownParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineShutdownParameters.java new file mode 100644 index 0000000000000..b7501a5d9094e --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineShutdownParameters.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* The parameters required for shutting down the virtual machine. +*/ +public class VirtualMachineShutdownParameters { + private PostShutdownAction postShutdownAction; + + /** + * Optional. The state of the virtual machine after shutdown (Stopped or + * StoppedDeallocated). + * @return The PostShutdownAction value. + */ + public PostShutdownAction getPostShutdownAction() { + return this.postShutdownAction; + } + + /** + * Optional. The state of the virtual machine after shutdown (Stopped or + * StoppedDeallocated). + * @param postShutdownActionValue The PostShutdownAction value. + */ + public void setPostShutdownAction(final PostShutdownAction postShutdownActionValue) { + this.postShutdownAction = postShutdownActionValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineShutdownRolesParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineShutdownRolesParameters.java new file mode 100644 index 0000000000000..5984d69827433 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineShutdownRolesParameters.java @@ -0,0 +1,78 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Parameters for the shutdown roles operation. +*/ +public class VirtualMachineShutdownRolesParameters { + private PostShutdownAction postShutdownAction; + + /** + * Optional. The state of the roles after shutdown. Possible values include + * Stopped or StoppedDeallocated. + * @return The PostShutdownAction value. + */ + public PostShutdownAction getPostShutdownAction() { + return this.postShutdownAction; + } + + /** + * Optional. The state of the roles after shutdown. Possible values include + * Stopped or StoppedDeallocated. + * @param postShutdownActionValue The PostShutdownAction value. + */ + public void setPostShutdownAction(final PostShutdownAction postShutdownActionValue) { + this.postShutdownAction = postShutdownActionValue; + } + + private ArrayList roles; + + /** + * Optional. The set of roles to shut down. + * @return The Roles value. + */ + public ArrayList getRoles() { + return this.roles; + } + + /** + * Optional. The set of roles to shut down. + * @param rolesValue The Roles value. + */ + public void setRoles(final ArrayList rolesValue) { + this.roles = rolesValue; + } + + /** + * Initializes a new instance of the VirtualMachineShutdownRolesParameters + * class. + * + */ + public VirtualMachineShutdownRolesParameters() { + this.roles = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineStartRolesParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineStartRolesParameters.java new file mode 100644 index 0000000000000..d80a103c6dcc1 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineStartRolesParameters.java @@ -0,0 +1,58 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Parameters for the Start Roles operation. +*/ +public class VirtualMachineStartRolesParameters { + private ArrayList roles; + + /** + * Optional. The set of roles to shut down. + * @return The Roles value. + */ + public ArrayList getRoles() { + return this.roles; + } + + /** + * Optional. The set of roles to shut down. + * @param rolesValue The Roles value. + */ + public void setRoles(final ArrayList rolesValue) { + this.roles = rolesValue; + } + + /** + * Initializes a new instance of the VirtualMachineStartRolesParameters + * class. + * + */ + public VirtualMachineStartRolesParameters() { + this.roles = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineUpdateLoadBalancedSetParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineUpdateLoadBalancedSetParameters.java new file mode 100644 index 0000000000000..36df94bc0d738 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineUpdateLoadBalancedSetParameters.java @@ -0,0 +1,286 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.net.InetAddress; +import java.util.ArrayList; + +/** +* The set of parameters required to update a load balanced endpoint set. +*/ +public class VirtualMachineUpdateLoadBalancedSetParameters { + private ArrayList loadBalancedEndpoints; + + /** + * Optional. A list of load balanced InputEndpoints to update. + * @return The LoadBalancedEndpoints value. + */ + public ArrayList getLoadBalancedEndpoints() { + return this.loadBalancedEndpoints; + } + + /** + * Optional. A list of load balanced InputEndpoints to update. + * @param loadBalancedEndpointsValue The LoadBalancedEndpoints value. + */ + public void setLoadBalancedEndpoints(final ArrayList loadBalancedEndpointsValue) { + this.loadBalancedEndpoints = loadBalancedEndpointsValue; + } + + /** + * Initializes a new instance of the + * VirtualMachineUpdateLoadBalancedSetParameters class. + * + */ + public VirtualMachineUpdateLoadBalancedSetParameters() { + this.loadBalancedEndpoints = new ArrayList(); + } + + /** + * The modeled external endpoint for a persistent VM role. + */ + public static class InputEndpoint { + private Boolean enableDirectServerReturn; + + /** + * Optional. A Boolean specifying whether this endpoint uses Direct + * Server Return + * @return The EnableDirectServerReturn value. + */ + public Boolean isEnableDirectServerReturn() { + return this.enableDirectServerReturn; + } + + /** + * Optional. A Boolean specifying whether this endpoint uses Direct + * Server Return + * @param enableDirectServerReturnValue The EnableDirectServerReturn + * value. + */ + public void setEnableDirectServerReturn(final Boolean enableDirectServerReturnValue) { + this.enableDirectServerReturn = enableDirectServerReturnValue; + } + + private String loadBalancedEndpointSetName; + + /** + * Required. Specifies whether this endpoint is part of shared + * LoadBalanced endpoint and served by multiple role instances. If not + * specified a BadRequest error will be returned. It must also be in + * use by the deployment (at least one role in the deployment must have + * an endpoint whose LoadBalancedEndpointSetName matches this) + * otherwise a BadRequest error will be returned. + * @return The LoadBalancedEndpointSetName value. + */ + public String getLoadBalancedEndpointSetName() { + return this.loadBalancedEndpointSetName; + } + + /** + * Required. Specifies whether this endpoint is part of shared + * LoadBalanced endpoint and served by multiple role instances. If not + * specified a BadRequest error will be returned. It must also be in + * use by the deployment (at least one role in the deployment must have + * an endpoint whose LoadBalancedEndpointSetName matches this) + * otherwise a BadRequest error will be returned. + * @param loadBalancedEndpointSetNameValue The + * LoadBalancedEndpointSetName value. + */ + public void setLoadBalancedEndpointSetName(final String loadBalancedEndpointSetNameValue) { + this.loadBalancedEndpointSetName = loadBalancedEndpointSetNameValue; + } + + private LoadBalancerProbe loadBalancerProbe; + + /** + * Optional. This represents an endpoint setting which platform load + * balancer must monitor to detect the availability of this role before + * forwarding traffic to this endpoint. If not specified the probe + * settings (if any) from the existing load balanced endpoint + * definition will be retained. + * @return The LoadBalancerProbe value. + */ + public LoadBalancerProbe getLoadBalancerProbe() { + return this.loadBalancerProbe; + } + + /** + * Optional. This represents an endpoint setting which platform load + * balancer must monitor to detect the availability of this role before + * forwarding traffic to this endpoint. If not specified the probe + * settings (if any) from the existing load balanced endpoint + * definition will be retained. + * @param loadBalancerProbeValue The LoadBalancerProbe value. + */ + public void setLoadBalancerProbe(final LoadBalancerProbe loadBalancerProbeValue) { + this.loadBalancerProbe = loadBalancerProbeValue; + } + + private Integer localPort; + + /** + * Optional. Specifies the internal port on which a service running + * inside the VM is listening to serve this endpoint. WARNING: If + * specified then ALL the endpoints of this LB set on all the roles + * will be updated to have THIS local port. To keep unique local ports + * on each role for a load balanced endpoint specify this as 0 (zero) + * and if you need to change those use UpdateRole. In case of port + * conflict with a local port (or probe port) on a role a + * BadRequestwill be returned. + * @return The LocalPort value. + */ + public Integer getLocalPort() { + return this.localPort; + } + + /** + * Optional. Specifies the internal port on which a service running + * inside the VM is listening to serve this endpoint. WARNING: If + * specified then ALL the endpoints of this LB set on all the roles + * will be updated to have THIS local port. To keep unique local ports + * on each role for a load balanced endpoint specify this as 0 (zero) + * and if you need to change those use UpdateRole. In case of port + * conflict with a local port (or probe port) on a role a + * BadRequestwill be returned. + * @param localPortValue The LocalPort value. + */ + public void setLocalPort(final Integer localPortValue) { + this.localPort = localPortValue; + } + + private String name; + + /** + * Optional. The name of the InputEndpoint. The name is ignored if + * specified + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the InputEndpoint. The name is ignored if + * specified + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private Integer port; + + /** + * Optional. An integer specifying the public port for this endpoint. + * Allowed values are between 1 and 65535 inclusive. A unqiue Port and + * Protocol combination must be specified for each InputEndpoint in the + * list. + * @return The Port value. + */ + public Integer getPort() { + return this.port; + } + + /** + * Optional. An integer specifying the public port for this endpoint. + * Allowed values are between 1 and 65535 inclusive. A unqiue Port and + * Protocol combination must be specified for each InputEndpoint in the + * list. + * @param portValue The Port value. + */ + public void setPort(final Integer portValue) { + this.port = portValue; + } + + private String protocol; + + /** + * Optional. Specifies the transport protocol for the endpoint. + * @return The Protocol value. + */ + public String getProtocol() { + return this.protocol; + } + + /** + * Optional. Specifies the transport protocol for the endpoint. + * @param protocolValue The Protocol value. + */ + public void setProtocol(final String protocolValue) { + this.protocol = protocolValue; + } + + private ArrayList rules; + + /** + * Optional. A collection of access control rules which control the + * external network traffic reaching to this endpoint. NOTES: (1) To + * remove the ACLs from a load-balanced endpoint just omit this + * element. (2) ACLs are set as specified. There is no merge done with + * existing ACLs. + * @return The Rules value. + */ + public ArrayList getRules() { + return this.rules; + } + + /** + * Optional. A collection of access control rules which control the + * external network traffic reaching to this endpoint. NOTES: (1) To + * remove the ACLs from a load-balanced endpoint just omit this + * element. (2) ACLs are set as specified. There is no merge done with + * existing ACLs. + * @param rulesValue The Rules value. + */ + public void setRules(final ArrayList rulesValue) { + this.rules = rulesValue; + } + + private InetAddress virtualIPAddress; + + /** + * Optional. The virtual IP address of the endpoint. + * @return The VirtualIPAddress value. + */ + public InetAddress getVirtualIPAddress() { + return this.virtualIPAddress; + } + + /** + * Optional. The virtual IP address of the endpoint. + * @param virtualIPAddressValue The VirtualIPAddress value. + */ + public void setVirtualIPAddress(final InetAddress virtualIPAddressValue) { + this.virtualIPAddress = virtualIPAddressValue; + } + + /** + * Initializes a new instance of the InputEndpoint class. + * + */ + public InputEndpoint() { + this.rules = new ArrayList(); + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineUpdateParameters.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineUpdateParameters.java new file mode 100644 index 0000000000000..4d1f7265cb49b --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineUpdateParameters.java @@ -0,0 +1,228 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Parameters supplied to the Update Virtual Machine operation. +*/ +public class VirtualMachineUpdateParameters { + private String availabilitySetName; + + /** + * Optional. Specifies the name of an availability set to which to add the + * virtual machine. This value controls the virtual machine allocation in + * the Azure environment. Virtual machines specified in the same + * availability set are allocated to different nodes to maximize + * availability. + * @return The AvailabilitySetName value. + */ + public String getAvailabilitySetName() { + return this.availabilitySetName; + } + + /** + * Optional. Specifies the name of an availability set to which to add the + * virtual machine. This value controls the virtual machine allocation in + * the Azure environment. Virtual machines specified in the same + * availability set are allocated to different nodes to maximize + * availability. + * @param availabilitySetNameValue The AvailabilitySetName value. + */ + public void setAvailabilitySetName(final String availabilitySetNameValue) { + this.availabilitySetName = availabilitySetNameValue; + } + + private ArrayList configurationSets; + + /** + * Optional. Contains the collection of configuration sets that contain + * system and application configuration settings. + * @return The ConfigurationSets value. + */ + public ArrayList getConfigurationSets() { + return this.configurationSets; + } + + /** + * Optional. Contains the collection of configuration sets that contain + * system and application configuration settings. + * @param configurationSetsValue The ConfigurationSets value. + */ + public void setConfigurationSets(final ArrayList configurationSetsValue) { + this.configurationSets = configurationSetsValue; + } + + private ArrayList dataVirtualHardDisks; + + /** + * Optional. Contains the parameters Azure used to create the data disk for + * the virtual machine. + * @return The DataVirtualHardDisks value. + */ + public ArrayList getDataVirtualHardDisks() { + return this.dataVirtualHardDisks; + } + + /** + * Optional. Contains the parameters Azure used to create the data disk for + * the virtual machine. + * @param dataVirtualHardDisksValue The DataVirtualHardDisks value. + */ + public void setDataVirtualHardDisks(final ArrayList dataVirtualHardDisksValue) { + this.dataVirtualHardDisks = dataVirtualHardDisksValue; + } + + private String label; + + /** + * Optional. Specifies the friendly name for the virtual machine. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Specifies the friendly name for the virtual machine. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private OSVirtualHardDisk oSVirtualHardDisk; + + /** + * Required. Contains the parameters Azure used to create the operating + * system disk for the virtual machine. + * @return The OSVirtualHardDisk value. + */ + public OSVirtualHardDisk getOSVirtualHardDisk() { + return this.oSVirtualHardDisk; + } + + /** + * Required. Contains the parameters Azure used to create the operating + * system disk for the virtual machine. + * @param oSVirtualHardDiskValue The OSVirtualHardDisk value. + */ + public void setOSVirtualHardDisk(final OSVirtualHardDisk oSVirtualHardDiskValue) { + this.oSVirtualHardDisk = oSVirtualHardDiskValue; + } + + private Boolean provisionGuestAgent; + + /** + * Optional. Indicates whether the WindowsAzureGuestAgent service is + * installed on the Virtual Machine. To run a resource extension in a + * Virtual Machine, this service must be installed. + * @return The ProvisionGuestAgent value. + */ + public Boolean isProvisionGuestAgent() { + return this.provisionGuestAgent; + } + + /** + * Optional. Indicates whether the WindowsAzureGuestAgent service is + * installed on the Virtual Machine. To run a resource extension in a + * Virtual Machine, this service must be installed. + * @param provisionGuestAgentValue The ProvisionGuestAgent value. + */ + public void setProvisionGuestAgent(final Boolean provisionGuestAgentValue) { + this.provisionGuestAgent = provisionGuestAgentValue; + } + + private ArrayList resourceExtensionReferences; + + /** + * Optional. Contains a collection of resource extensions that are to be + * installed on the Virtual Machine. This element is used if + * ProvisionGuestAgent is set to true. + * @return The ResourceExtensionReferences value. + */ + public ArrayList getResourceExtensionReferences() { + return this.resourceExtensionReferences; + } + + /** + * Optional. Contains a collection of resource extensions that are to be + * installed on the Virtual Machine. This element is used if + * ProvisionGuestAgent is set to true. + * @param resourceExtensionReferencesValue The ResourceExtensionReferences + * value. + */ + public void setResourceExtensionReferences(final ArrayList resourceExtensionReferencesValue) { + this.resourceExtensionReferences = resourceExtensionReferencesValue; + } + + private String roleName; + + /** + * Required. Specifies the name for the virtual machine. The name must be + * unique within the deployment. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Required. Specifies the name for the virtual machine. The name must be + * unique within the deployment. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + + private String roleSize; + + /** + * Optional. The size of the virtual machine. + * @return The RoleSize value. + */ + public String getRoleSize() { + return this.roleSize; + } + + /** + * Optional. The size of the virtual machine. + * @param roleSizeValue The RoleSize value. + */ + public void setRoleSize(final String roleSizeValue) { + this.roleSize = roleSizeValue; + } + + /** + * Initializes a new instance of the VirtualMachineUpdateParameters class. + * + */ + public VirtualMachineUpdateParameters() { + this.configurationSets = new ArrayList(); + this.dataVirtualHardDisks = new ArrayList(); + this.resourceExtensionReferences = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineVMImageListResponse.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineVMImageListResponse.java new file mode 100644 index 0000000000000..5736f115ee86c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineVMImageListResponse.java @@ -0,0 +1,501 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; + +/** +* The List VM Images operation response. +*/ +public class VirtualMachineVMImageListResponse extends OperationResponse implements Iterable { + private ArrayList vMImages; + + /** + * Optional. The virtual machine images associated with your subscription. + * @return The VMImages value. + */ + public ArrayList getVMImages() { + return this.vMImages; + } + + /** + * Optional. The virtual machine images associated with your subscription. + * @param vMImagesValue The VMImages value. + */ + public void setVMImages(final ArrayList vMImagesValue) { + this.vMImages = vMImagesValue; + } + + /** + * Initializes a new instance of the VirtualMachineVMImageListResponse class. + * + */ + public VirtualMachineVMImageListResponse() { + super(); + this.vMImages = new ArrayList(); + } + + /** + * Gets the sequence of VMImages. + * + */ + public Iterator iterator() { + return this.getVMImages().iterator(); + } + + /** + * The data disk configuration. + */ + public static class DataDiskConfiguration { + private VirtualHardDiskHostCaching hostCaching; + + /** + * Optional. Specifies the platform caching behavior of the data disk + * blob for read/write efficiency. The default vault is ReadOnly. + * @return The HostCaching value. + */ + public VirtualHardDiskHostCaching getHostCaching() { + return this.hostCaching; + } + + /** + * Optional. Specifies the platform caching behavior of the data disk + * blob for read/write efficiency. The default vault is ReadOnly. + * @param hostCachingValue The HostCaching value. + */ + public void setHostCaching(final VirtualHardDiskHostCaching hostCachingValue) { + this.hostCaching = hostCachingValue; + } + + private int logicalDiskSizeInGB; + + /** + * Optional. Specifies the size, in GB, of an empty VHD to be attached + * to the virtual machine. The VHD can be created as part of disk + * attach or create virtual machine calls by specifying the value for + * this property. Azure creates the empty VHD based on size preference + * and attaches the newly created VHD to the virtual machine. + * @return The LogicalDiskSizeInGB value. + */ + public int getLogicalDiskSizeInGB() { + return this.logicalDiskSizeInGB; + } + + /** + * Optional. Specifies the size, in GB, of an empty VHD to be attached + * to the virtual machine. The VHD can be created as part of disk + * attach or create virtual machine calls by specifying the value for + * this property. Azure creates the empty VHD based on size preference + * and attaches the newly created VHD to the virtual machine. + * @param logicalDiskSizeInGBValue The LogicalDiskSizeInGB value. + */ + public void setLogicalDiskSizeInGB(final int logicalDiskSizeInGBValue) { + this.logicalDiskSizeInGB = logicalDiskSizeInGBValue; + } + + private Integer logicalUnitNumber; + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the data disk. + * The LUN specifies the slot in which the data drive appears when + * mounted for usage by the virtual machine. This element is only + * listed when more than one data disk is attached to a virtual machine. + * @return The LogicalUnitNumber value. + */ + public Integer getLogicalUnitNumber() { + return this.logicalUnitNumber; + } + + /** + * Optional. Specifies the Logical Unit Number (LUN) for the data disk. + * The LUN specifies the slot in which the data drive appears when + * mounted for usage by the virtual machine. This element is only + * listed when more than one data disk is attached to a virtual machine. + * @param logicalUnitNumberValue The LogicalUnitNumber value. + */ + public void setLogicalUnitNumber(final Integer logicalUnitNumberValue) { + this.logicalUnitNumber = logicalUnitNumberValue; + } + + private URI mediaLink; + + /** + * Optional. Specifies the location of the disk in Windows Azure storage. + * @return The MediaLink value. + */ + public URI getMediaLink() { + return this.mediaLink; + } + + /** + * Optional. Specifies the location of the disk in Windows Azure storage. + * @param mediaLinkValue The MediaLink value. + */ + public void setMediaLink(final URI mediaLinkValue) { + this.mediaLink = mediaLinkValue; + } + + private String name; + + /** + * Optional. Specifies the name of the VHD to use to create the data + * disk for the virtual machine. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name of the VHD to use to create the data + * disk for the virtual machine. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + } + + /** + * The OS disk configuration. + */ + public static class OSDiskConfiguration { + private VirtualHardDiskHostCaching hostCaching; + + /** + * Optional. Specifies the platform caching behavior of the operating + * system disk blob for read/write efficiency. + * @return The HostCaching value. + */ + public VirtualHardDiskHostCaching getHostCaching() { + return this.hostCaching; + } + + /** + * Optional. Specifies the platform caching behavior of the operating + * system disk blob for read/write efficiency. + * @param hostCachingValue The HostCaching value. + */ + public void setHostCaching(final VirtualHardDiskHostCaching hostCachingValue) { + this.hostCaching = hostCachingValue; + } + + private int logicalDiskSizeInGB; + + /** + * Optional. Specifies the size, in GB, of an empty VHD to be attached + * to the virtual machine. The VHD can be created as part of disk + * attach or create virtual machine calls by specifying the value for + * this property. Azure creates the empty VHD based on size preference + * and attaches the newly created VHD to the virtual machine. + * @return The LogicalDiskSizeInGB value. + */ + public int getLogicalDiskSizeInGB() { + return this.logicalDiskSizeInGB; + } + + /** + * Optional. Specifies the size, in GB, of an empty VHD to be attached + * to the virtual machine. The VHD can be created as part of disk + * attach or create virtual machine calls by specifying the value for + * this property. Azure creates the empty VHD based on size preference + * and attaches the newly created VHD to the virtual machine. + * @param logicalDiskSizeInGBValue The LogicalDiskSizeInGB value. + */ + public void setLogicalDiskSizeInGB(final int logicalDiskSizeInGBValue) { + this.logicalDiskSizeInGB = logicalDiskSizeInGBValue; + } + + private URI mediaLink; + + /** + * Optional. Specifies the location of the disk in Windows Azure storage. + * @return The MediaLink value. + */ + public URI getMediaLink() { + return this.mediaLink; + } + + /** + * Optional. Specifies the location of the disk in Windows Azure storage. + * @param mediaLinkValue The MediaLink value. + */ + public void setMediaLink(final URI mediaLinkValue) { + this.mediaLink = mediaLinkValue; + } + + private String name; + + /** + * Optional. Specifies the name of an operating system image in the + * image repository. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Specifies the name of an operating system image in the + * image repository. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operatingSystem; + + /** + * Optional. The operating system running in the virtual machine. + * @return The OperatingSystem value. + */ + public String getOperatingSystem() { + return this.operatingSystem; + } + + /** + * Optional. The operating system running in the virtual machine. + * @param operatingSystemValue The OperatingSystem value. + */ + public void setOperatingSystem(final String operatingSystemValue) { + this.operatingSystem = operatingSystemValue; + } + + private String oSState; + + /** + * Optional. The operating system state in the virtual machine. + * @return The OSState value. + */ + public String getOSState() { + return this.oSState; + } + + /** + * Optional. The operating system state in the virtual machine. + * @param oSStateValue The OSState value. + */ + public void setOSState(final String oSStateValue) { + this.oSState = oSStateValue; + } + } + + /** + * A virtual machine image associated with your subscription. + */ + public static class VirtualMachineVMImage { + private String affinityGroup; + + /** + * Optional. The affinity group name of the virtual machine image. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity group name of the virtual machine image. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String category; + + /** + * Optional. The classification of the virtual machine image. + * @return The Category value. + */ + public String getCategory() { + return this.category; + } + + /** + * Optional. The classification of the virtual machine image. + * @param categoryValue The Category value. + */ + public void setCategory(final String categoryValue) { + this.category = categoryValue; + } + + private Calendar createdTime; + + /** + * Optional. The date when the virtual machine image was created. + * @return The CreatedTime value. + */ + public Calendar getCreatedTime() { + return this.createdTime; + } + + /** + * Optional. The date when the virtual machine image was created. + * @param createdTimeValue The CreatedTime value. + */ + public void setCreatedTime(final Calendar createdTimeValue) { + this.createdTime = createdTimeValue; + } + + private ArrayList dataDiskConfigurations; + + /** + * Optional. The data disk configurations. + * @return The DataDiskConfigurations value. + */ + public ArrayList getDataDiskConfigurations() { + return this.dataDiskConfigurations; + } + + /** + * Optional. The data disk configurations. + * @param dataDiskConfigurationsValue The DataDiskConfigurations value. + */ + public void setDataDiskConfigurations(final ArrayList dataDiskConfigurationsValue) { + this.dataDiskConfigurations = dataDiskConfigurationsValue; + } + + private String deploymentName; + + /** + * Optional. The deployment name of the virtual machine image. + * @return The DeploymentName value. + */ + public String getDeploymentName() { + return this.deploymentName; + } + + /** + * Optional. The deployment name of the virtual machine image. + * @param deploymentNameValue The DeploymentName value. + */ + public void setDeploymentName(final String deploymentNameValue) { + this.deploymentName = deploymentNameValue; + } + + private String label; + + /** + * Optional. An identifier for the virtual machine image. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. An identifier for the virtual machine image. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Optional. The name of the virtual machine image. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the virtual machine image. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private VirtualMachineVMImageListResponse.OSDiskConfiguration oSDiskConfiguration; + + /** + * Optional. The OS disk configuration. + * @return The OSDiskConfiguration value. + */ + public VirtualMachineVMImageListResponse.OSDiskConfiguration getOSDiskConfiguration() { + return this.oSDiskConfiguration; + } + + /** + * Optional. The OS disk configuration. + * @param oSDiskConfigurationValue The OSDiskConfiguration value. + */ + public void setOSDiskConfiguration(final VirtualMachineVMImageListResponse.OSDiskConfiguration oSDiskConfigurationValue) { + this.oSDiskConfiguration = oSDiskConfigurationValue; + } + + private String roleName; + + /** + * Optional. The role name of the virtual machine image. + * @return The RoleName value. + */ + public String getRoleName() { + return this.roleName; + } + + /** + * Optional. The role name of the virtual machine image. + * @param roleNameValue The RoleName value. + */ + public void setRoleName(final String roleNameValue) { + this.roleName = roleNameValue; + } + + private String serviceName; + + /** + * Optional. The service name of the virtual machine image. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The service name of the virtual machine image. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + /** + * Initializes a new instance of the VirtualMachineVMImage class. + * + */ + public VirtualMachineVMImage() { + this.dataDiskConfigurations = new ArrayList(); + } + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineWindowsRemoteManagementListenerType.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineWindowsRemoteManagementListenerType.java new file mode 100644 index 0000000000000..8eacdc1bfaab8 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/VirtualMachineWindowsRemoteManagementListenerType.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Specifies the type of listener for enabling remote Windows PowerShell. +*/ +public enum VirtualMachineWindowsRemoteManagementListenerType { + Http, + + Https, +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/WindowsRemoteManagementListener.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/WindowsRemoteManagementListener.java new file mode 100644 index 0000000000000..b0b004904447c --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/WindowsRemoteManagementListener.java @@ -0,0 +1,75 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +/** +* Contains the type and certificate information for the listener. +*/ +public class WindowsRemoteManagementListener { + private String certificateThumbprint; + + /** + * Optional. Specifies the certificate thumbprint for the secure connection. + * If Type is Https then this value is an optional value that is set to the + * thumbprint of the service certificate that is used to provision the + * WinRM HTTPS listener. If this value is not specified, a self-signed + * certificate is generated and used for the virtual machine. + * @return The CertificateThumbprint value. + */ + public String getCertificateThumbprint() { + return this.certificateThumbprint; + } + + /** + * Optional. Specifies the certificate thumbprint for the secure connection. + * If Type is Https then this value is an optional value that is set to the + * thumbprint of the service certificate that is used to provision the + * WinRM HTTPS listener. If this value is not specified, a self-signed + * certificate is generated and used for the virtual machine. + * @param certificateThumbprintValue The CertificateThumbprint value. + */ + public void setCertificateThumbprint(final String certificateThumbprintValue) { + this.certificateThumbprint = certificateThumbprintValue; + } + + private VirtualMachineWindowsRemoteManagementListenerType listenerType; + + /** + * Required. Specifies the type of listener. This value can be Http or + * Https. The value is case sensitive. + * @return The ListenerType value. + */ + public VirtualMachineWindowsRemoteManagementListenerType getListenerType() { + return this.listenerType; + } + + /** + * Required. Specifies the type of listener. This value can be Http or + * Https. The value is case sensitive. + * @param listenerTypeValue The ListenerType value. + */ + public void setListenerType(final VirtualMachineWindowsRemoteManagementListenerType listenerTypeValue) { + this.listenerType = listenerTypeValue; + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/WindowsRemoteManagementSettings.java b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/WindowsRemoteManagementSettings.java new file mode 100644 index 0000000000000..cdeb5305938f6 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/WindowsRemoteManagementSettings.java @@ -0,0 +1,60 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.compute.models; + +import java.util.ArrayList; + +/** +* Configures the Windows Remote Management service on the virtual machine, +* which enables remote Windows PowerShell. +*/ +public class WindowsRemoteManagementSettings { + private ArrayList listeners; + + /** + * Optional. Contains a collection of information for enabling remote + * Windows PowerShell. + * @return The Listeners value. + */ + public ArrayList getListeners() { + return this.listeners; + } + + /** + * Optional. Contains a collection of information for enabling remote + * Windows PowerShell. + * @param listenersValue The Listeners value. + */ + public void setListeners(final ArrayList listenersValue) { + this.listeners = listenersValue; + } + + /** + * Initializes a new instance of the WindowsRemoteManagementSettings class. + * + */ + public WindowsRemoteManagementSettings() { + this.listeners = new ArrayList(); + } +} diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/package.html b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/package.html new file mode 100644 index 0000000000000..052417f5ec357 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/models/package.html @@ -0,0 +1,5 @@ + + +This package contains the models for the compute management service. + + diff --git a/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/package.html b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/package.html new file mode 100644 index 0000000000000..8b62480002a76 --- /dev/null +++ b/management-compute/src/main/java/com/microsoft/windowsazure/management/compute/package.html @@ -0,0 +1,6 @@ + + +This package contains the service management compute class, + interface, and associated configuration and utility classes. + + diff --git a/management-compute/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/management-compute/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..30371d60e3386 --- /dev/null +++ b/management-compute/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1 @@ +com.microsoft.windowsazure.management.compute.Exports diff --git a/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/ComputeManagementIntegrationTestBase.java b/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/ComputeManagementIntegrationTestBase.java new file mode 100644 index 0000000000000..64c410bd4c705 --- /dev/null +++ b/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/ComputeManagementIntegrationTestBase.java @@ -0,0 +1,77 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.compute; + +import java.net.URI; +import java.util.Random; + +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; + +import com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigurationProperties; +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.management.configuration.*; +import com.microsoft.windowsazure.management.*; +import com.microsoft.windowsazure.management.storage.StorageManagementClient; +import com.microsoft.windowsazure.management.storage.StorageManagementService; +import com.microsoft.windowsazure.*; + +public abstract class ComputeManagementIntegrationTestBase { + protected static String testVMPrefix = "aztst"; + protected static String testStoragePrefix = "aztst"; + protected static String testHostedServicePrefix = "azhst"; + + protected static ComputeManagementClient computeManagementClient; + protected static StorageManagementClient storageManagementClient; + protected static ManagementClient managementClient; + + protected static void createComputeManagementClient() throws Exception { + Configuration config = createConfiguration(); + computeManagementClient = ComputeManagementService.create(config); + } + + protected static void createStorageManagementClient() throws Exception { + Configuration config = createConfiguration(); + storageManagementClient = StorageManagementService.create(config); + } + + protected static void createManagementClient() throws Exception { + Configuration config = createConfiguration(); + config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER, new DefaultHttpRequestRetryHandler()); + + managementClient = ManagementService.create(config); + } + + protected static Configuration createConfiguration() throws Exception { + String baseUri = System.getenv(ManagementConfiguration.URI); + return ManagementConfiguration.configure( + baseUri != null ? new URI(baseUri) : null, + System.getenv(ManagementConfiguration.SUBSCRIPTION_ID), + System.getenv(ManagementConfiguration.KEYSTORE_PATH), + System.getenv(ManagementConfiguration.KEYSTORE_PASSWORD), + KeyStoreType.fromString(System.getenv(ManagementConfiguration.KEYSTORE_TYPE)) + ); + } + + protected static String randomString(int length) { + Random random = new Random(); + StringBuilder stringBuilder = new StringBuilder(length); + for (int i=0; i operatingSystemlist = operatingSystemListResponse.getOperatingSystems(); + for (OperatingSystemListResponse.OperatingSystem os: operatingSystemlist) { + if (os.getFamilyLabel().contains("R2 SP1")==true){ + Assert.assertEquals(2, os.getFamily()); + Assert.assertFalse(os.isActive()); + Assert.assertFalse(os.isDefault()); + } + } + } + + @Test + public void listOperationSystemFamiliesSuccess() throws Exception { + //Arrange + OperatingSystemListFamiliesResponse operatingSystemListFamiliesResponse = computeManagementClient.getOperatingSystemsOperations().listFamilies(); + ArrayList operatingSystemFamilylist = operatingSystemListFamiliesResponse.getOperatingSystemFamilies(); + Assert.assertNotNull(operatingSystemFamilylist); + + for (OperatingSystemListFamiliesResponse.OperatingSystemFamily osf: operatingSystemFamilylist) { + if (osf.getName() == 1){ + Assert.assertEquals("Windows Server 2008 SP2", osf.getLabel()); + } + } + } +} \ No newline at end of file diff --git a/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperationsTests.java b/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperationsTests.java new file mode 100644 index 0000000000000..ee199f6569f98 --- /dev/null +++ b/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/VirtualMachineExtensionOperationsTests.java @@ -0,0 +1,52 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.compute; + +import java.util.ArrayList; + +import com.microsoft.windowsazure.management.compute.models.*; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class VirtualMachineExtensionOperationsTests extends ComputeManagementIntegrationTestBase { + @BeforeClass + public static void setup() throws Exception { + createComputeManagementClient(); + } + + @Test + public void listVirtualMachineExtensionSuccess() throws Exception { + VirtualMachineExtensionListResponse virtualMachineExtensionListResponse = computeManagementClient.getVirtualMachineExtensionsOperations().list(); + ArrayList virtualMachineExtensionResourceExtensionlist = virtualMachineExtensionListResponse.getResourceExtensions(); + Assert.assertNotNull(virtualMachineExtensionResourceExtensionlist); + for (VirtualMachineExtensionListResponse.ResourceExtension resourceExtension : virtualMachineExtensionResourceExtensionlist) + { + Assert.assertNull(resourceExtension.getSampleConfig()); + } + } + + @Test + public void listVirtualMachineExtensionVersionSuccess() throws Exception { + //Arrange + String publisherName = "BGInfo"; + String extensionName = "BGInfo"; + //Act + VirtualMachineExtensionListResponse virtualMachineExtensionListResponse = computeManagementClient.getVirtualMachineExtensionsOperations().listVersions(publisherName, extensionName); + ArrayList virtualMachineExtensionResourceExtensionlist = virtualMachineExtensionListResponse.getResourceExtensions(); + Assert.assertNotNull(virtualMachineExtensionResourceExtensionlist); + } +} \ No newline at end of file diff --git a/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperationsTests.java b/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperationsTests.java new file mode 100644 index 0000000000000..20c70eca6e8f4 --- /dev/null +++ b/management-compute/src/test/java/com/microsoft/windowsazure/management/compute/VirtualMachineOperationsTests.java @@ -0,0 +1,574 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.compute; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.InvalidKeyException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.concurrent.ExecutionException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.*; +import com.microsoft.windowsazure.management.compute.models.*; +import com.microsoft.windowsazure.management.storage.models.*; +import com.microsoft.windowsazure.storage.*; +import com.microsoft.windowsazure.storage.blob.*; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.xml.sax.SAXException; + +public class VirtualMachineOperationsTests extends ComputeManagementIntegrationTestBase { + + //lower case only for storage account name, this is existed storage account with vhd-store container, + //need to create your own storage account and create container there to store VM images + private static String storageAccountName; + private static String storageAccountKey = ""; + private static String storageContainer = "vhd-store"; + private static String hostedServiceName; + private static String deploymentName = testVMPrefix + "deploy1"; + private static String virtualMachineName = testVMPrefix + "vm1"; + private static String vmLocation = "West US"; + private static String hostedServiceLabel = testVMPrefix + "HostedServiceLabel1"; + private static String hostedServiceDescription = testVMPrefix +"HostedServiceDescription1"; + private static String deploymentLabel = testVMPrefix + "deployLabel1"; + private static HostedServiceOperations hostedServicesOperations; + + @BeforeClass + public static void setup() throws Exception { + storageAccountName = testStoragePrefix + randomString(10); + hostedServiceName = testHostedServicePrefix + randomString(10); + + //create storage service for storage account creation + createStorageManagementClient(); + //create compute management service for all compute management operation + createComputeManagementClient(); + //create management service for accessing management operation + createManagementClient(); + + hostedServicesOperations = computeManagementClient.getHostedServicesOperations(); + + //dynamic get location for vm storage/hosted service + getLocation(); + //create a new storage account for vm .vhd storage. + createStorageAccount(); + //create a vm first for accessing non-creation vm operation first + createVMDeployment(); + } + + @AfterClass + public static void cleanup() { + cleanDeployment(); + cleanHostedService(); + cleanBlob(); + cleanStorageAccount(); + } + + @Test + public void createVirtualMachines() throws Exception { + int random = (int)(Math.random()* 100); + String roleName = testVMPrefix + "vm2"; + String computerName = testVMPrefix + "vm2"; + String adminuserPassword = testVMPrefix + "!12"; + String adminUserName = testVMPrefix; + URI mediaLinkUriValue = new URI("http://"+ storageAccountName + ".blob.core.windows.net/"+storageContainer+ "/" + testVMPrefix +random + ".vhd"); + String osVHarddiskName =testVMPrefix + "oshdname" + random; + String operatingSystemName ="Windows"; + + //required + ArrayList configlist = new ArrayList(); + ConfigurationSet configset = new ConfigurationSet(); + configset.setConfigurationSetType(ConfigurationSetTypes.WINDOWSPROVISIONINGCONFIGURATION); + //required + configset.setComputerName(computerName); + //required + configset.setAdminPassword(adminuserPassword); + //required + configset.setAdminUserName(adminUserName); + configset.setEnableAutomaticUpdates(false); + configlist.add(configset); + + //required + String sourceImageName = getOSSourceImage(); + OSVirtualHardDisk oSVirtualHardDisk = new OSVirtualHardDisk(); + //required + oSVirtualHardDisk.setName(osVHarddiskName); + oSVirtualHardDisk.setHostCaching(VirtualHardDiskHostCaching.ReadWrite); + oSVirtualHardDisk.setOperatingSystem(operatingSystemName); + //required + oSVirtualHardDisk.setMediaLink(mediaLinkUriValue); + //required + oSVirtualHardDisk.setSourceImageName(sourceImageName); + + VirtualMachineCreateParameters createParameters = new VirtualMachineCreateParameters(); + //required + createParameters.setRoleName(roleName); + createParameters.setRoleSize(VirtualMachineRoleSize.MEDIUM); + createParameters.setProvisionGuestAgent(true); + createParameters.setConfigurationSets(configlist); + createParameters.setOSVirtualHardDisk(oSVirtualHardDisk); + + //Act + OperationResponse operationResponse = computeManagementClient.getVirtualMachinesOperations().create(hostedServiceName, deploymentName, createParameters); + + //Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + private static void createHostedService() throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { + //hosted service required for vm deployment + HostedServiceCreateParameters createParameters = new HostedServiceCreateParameters(); + //required + createParameters.setLabel(hostedServiceLabel); + //required + createParameters.setServiceName(hostedServiceName); + createParameters.setDescription(hostedServiceDescription); + //required + createParameters.setLocation(vmLocation); + OperationResponse hostedServiceOperationResponse = hostedServicesOperations.create(createParameters); + Assert.assertEquals(201, hostedServiceOperationResponse.getStatusCode()); + Assert.assertNotNull(hostedServiceOperationResponse.getRequestId()); + + System.out.println("hostedservice created: " + hostedServiceName); + } + + private static ArrayList createRoleList() throws Exception { + int random = (int)(Math.random()* 100); + ArrayList roleList = new ArrayList(); + Role role = new Role(); + String roleName = virtualMachineName; + String computerName = virtualMachineName; + String adminUserPassword = testVMPrefix + "!12"; + String adminUserName = testVMPrefix; + URI mediaLinkUriValue = new URI("http://"+ storageAccountName + ".blob.core.windows.net/"+storageContainer+ "/" + testVMPrefix + random +".vhd"); + String osVHarddiskName =testVMPrefix + "oshdname"+ random; + String operatingSystemName ="Windows"; + + //required + ArrayList configurationSetList = new ArrayList(); + ConfigurationSet configurationSet = new ConfigurationSet(); + configurationSet.setConfigurationSetType(ConfigurationSetTypes.WINDOWSPROVISIONINGCONFIGURATION); + //required + configurationSet.setComputerName(computerName); + //required + configurationSet.setAdminPassword(adminUserPassword); + //required + configurationSet.setAdminUserName(adminUserName); + configurationSet.setEnableAutomaticUpdates(false); + configurationSet.setHostName(hostedServiceName + ".cloudapp.net"); + configurationSetList.add(configurationSet); + + String sourceImageName = getOSSourceImage(); + OSVirtualHardDisk oSVirtualHardDisk = new OSVirtualHardDisk(); + //required + oSVirtualHardDisk.setName(osVHarddiskName); + oSVirtualHardDisk.setHostCaching(VirtualHardDiskHostCaching.ReadWrite); + oSVirtualHardDisk.setOperatingSystem(operatingSystemName); + //required + oSVirtualHardDisk.setMediaLink(mediaLinkUriValue); + //required + oSVirtualHardDisk.setSourceImageName(sourceImageName); + + //required + role.setRoleName(roleName); + //required + role.setRoleType(VirtualMachineRoleType.PersistentVMRole.toString()); + role.setRoleSize(VirtualMachineRoleSize.MEDIUM); + role.setProvisionGuestAgent(true); + role.setConfigurationSets(configurationSetList); + role.setOSVirtualHardDisk(oSVirtualHardDisk); + roleList.add(role); + return roleList; + } + + private static void createVMDeployment() throws Exception { + createHostedService(); + + ArrayList rolelist = createRoleList(); + + VirtualMachineCreateDeploymentParameters deploymentParameters = new VirtualMachineCreateDeploymentParameters(); + deploymentParameters.setDeploymentSlot(DeploymentSlot.Staging); + deploymentParameters.setName(deploymentName); + deploymentParameters.setLabel(deploymentLabel); + deploymentParameters.setRoles(rolelist); + + // Act + OperationResponse operationResponse = computeManagementClient.getVirtualMachinesOperations().createDeployment(hostedServiceName, deploymentParameters); + + // Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void listVirtualMachines() throws Exception { + //there is no dedicated vm list methods, has to filter through hosted service, and deployment, rolelist to find out the vm list + //role that has VirtualMachineRoleType.PersistentVMRole property is a vm + ArrayList vmlist = new ArrayList(); + HostedServiceListResponse hostedServiceListResponse = computeManagementClient.getHostedServicesOperations().list(); + ArrayList hostedServicelist = hostedServiceListResponse.getHostedServices(); + Assert.assertNotNull(hostedServicelist); + + for (HostedServiceListResponse.HostedService hostedService : hostedServicelist) { + if (hostedService.getServiceName().contains(testVMPrefix)) { + HostedServiceGetDetailedResponse hostedServiceGetDetailedResponse = computeManagementClient.getHostedServicesOperations().getDetailed(hostedService.getServiceName()); + + int year = hostedServiceGetDetailedResponse.getProperties().getDateLastModified().get(Calendar.YEAR); + Assert.assertTrue(year > 2000); + + ArrayList deploymentlist = hostedServiceGetDetailedResponse.getDeployments(); + Assert.assertNotNull(deploymentlist); + + for (HostedServiceGetDetailedResponse.Deployment deployment : deploymentlist) { + ArrayList rolelist = deployment.getRoles(); + Assert.assertNotNull(rolelist); + + for (Role role : rolelist) { + if ((role.getRoleType()!=null) && (role.getRoleType().equalsIgnoreCase(VirtualMachineRoleType.PersistentVMRole.toString()))) { + Assert.assertTrue(role.getRoleName().contains(testVMPrefix)); + vmlist.add(role); + } + } + } + } + } + } + + @Test + public void getVirtualMachines() throws Exception { + //Act + VirtualMachineGetResponse virtualMachinesGetResponse = computeManagementClient.getVirtualMachinesOperations().get(hostedServiceName, deploymentName, virtualMachineName); + + //Assert + Assert.assertEquals(200, virtualMachinesGetResponse.getStatusCode()); + Assert.assertNotNull(virtualMachinesGetResponse.getRequestId()); + //vm always has VirtualMachineRoleType.PersistentVMRole property + Assert.assertEquals(VirtualMachineRoleType.PersistentVMRole, virtualMachinesGetResponse.getRoleType()); + + OSVirtualHardDisk osharddisk = virtualMachinesGetResponse.getOSVirtualHardDisk(); + Assert.assertTrue(osharddisk.getOperatingSystem().contains("Window")); + Assert.assertTrue(osharddisk.getSourceImageName().contains("Win")); + Assert.assertEquals(VirtualHardDiskHostCaching.ReadWrite, osharddisk.getHostCaching()); + } + + @Test + public void restartVirtualMachine() throws Exception { + //test for stop, start and restart + //Act + VirtualMachineGetResponse virtualMachinesGetResponse = computeManagementClient.getVirtualMachinesOperations().get(hostedServiceName, deploymentName, virtualMachineName); + + //Assert + Assert.assertEquals(200, virtualMachinesGetResponse.getStatusCode()); + Assert.assertNotNull(virtualMachinesGetResponse.getRequestId()); + + String vmName = virtualMachinesGetResponse.getRoleName(); + + VirtualMachineShutdownParameters stopParameters = new VirtualMachineShutdownParameters(); + stopParameters.setPostShutdownAction(PostShutdownAction.Stopped); + OperationStatusResponse shutdownresponse = computeManagementClient.getVirtualMachinesOperations().shutdown(hostedServiceName, deploymentName, vmName, stopParameters); + Assert.assertEquals(200, shutdownresponse.getStatusCode()); + Assert.assertNotNull(shutdownresponse.getRequestId()); + + OperationStatusResponse startresponse = computeManagementClient.getVirtualMachinesOperations().start(hostedServiceName, deploymentName, vmName); + Assert.assertEquals(200, startresponse.getStatusCode()); + Assert.assertNotNull(startresponse.getRequestId()); + + OperationStatusResponse restartresponse = computeManagementClient.getVirtualMachinesOperations().restart(hostedServiceName, deploymentName, vmName); + Assert.assertEquals(200, restartresponse.getStatusCode()); + Assert.assertNotNull(restartresponse.getRequestId()); + } + + @Test + @Ignore("Because it takes too long to run") + public void deleteVirtualMachines() throws Exception { + //Act + VirtualMachineGetResponse virtualMachinesGetResponse = computeManagementClient.getVirtualMachinesOperations().get(hostedServiceName, deploymentName, virtualMachineName); + //Assert + Assert.assertEquals(200, virtualMachinesGetResponse.getStatusCode()); + Assert.assertNotNull(virtualMachinesGetResponse.getRequestId()); + + OperationStatusResponse deleteResponse = computeManagementClient.getVirtualMachinesOperations().delete(hostedServiceName, deploymentName, virtualMachinesGetResponse.getRoleName(), true); + //Assert + Assert.assertEquals(200, deleteResponse.getStatusCode()); + Assert.assertNotNull(deleteResponse.getRequestId()); + } + + @Test + public void updateVMInputEndPoint() throws Exception { + //Act + VirtualMachineGetResponse virtualMachinesGetResponse = computeManagementClient.getVirtualMachinesOperations().get(hostedServiceName, deploymentName, virtualMachineName); + //Assert + Assert.assertEquals(200, virtualMachinesGetResponse.getStatusCode()); + Assert.assertNotNull(virtualMachinesGetResponse.getRequestId()); + + VirtualMachineUpdateParameters updateParameters = new VirtualMachineUpdateParameters(); + //get the configuration list + ArrayList configlist = virtualMachinesGetResponse.getConfigurationSets(); + //get inputendpoint list and update it + ArrayList endpointlist = configlist.get(0).getInputEndpoints(); + InputEndpoint inputEndpoint = new InputEndpoint(); + inputEndpoint.setEnableDirectServerReturn(false); + inputEndpoint.setPort(5987); + inputEndpoint.setLocalPort(5987); + inputEndpoint.setName("RDP"); + inputEndpoint.setProtocol(InputEndpointTransportProtocol.TCP); + endpointlist.add(inputEndpoint); + updateParameters.setConfigurationSets(configlist); + + //required for update + OSVirtualHardDisk osVirtualHardDisk = virtualMachinesGetResponse.getOSVirtualHardDisk(); + updateParameters.setOSVirtualHardDisk(osVirtualHardDisk); + updateParameters.setRoleName(virtualMachinesGetResponse.getRoleName()); + + OperationResponse updateoperationResponse = computeManagementClient.getVirtualMachinesOperations().update(hostedServiceName, deploymentName, virtualMachinesGetResponse.getRoleName(), updateParameters); + + //Assert + Assert.assertEquals(200, updateoperationResponse.getStatusCode()); + Assert.assertNotNull(updateoperationResponse.getRequestId()); + } + + @Test + public void updateVMSize() throws Exception { + //Act + VirtualMachineGetResponse virtualMachinesGetResponse = computeManagementClient.getVirtualMachinesOperations().get(hostedServiceName, deploymentName, virtualMachineName); + + //Assert + Assert.assertEquals(200, virtualMachinesGetResponse.getStatusCode()); + Assert.assertNotNull(virtualMachinesGetResponse.getRequestId()); + + VirtualMachineUpdateParameters updateParameters = new VirtualMachineUpdateParameters(); + updateParameters.setRoleName(virtualMachinesGetResponse.getRoleName()); + //update the role size + updateParameters.setRoleSize(VirtualMachineRoleSize.SMALL); + + //this is required parameters for update + OSVirtualHardDisk osVirtualHardDisk = virtualMachinesGetResponse.getOSVirtualHardDisk(); + updateParameters.setOSVirtualHardDisk(osVirtualHardDisk); + + //update + OperationResponse updateoperationResponse = computeManagementClient.getVirtualMachinesOperations().update(hostedServiceName, deploymentName, virtualMachineName, updateParameters); + + //Assert + Assert.assertEquals(200, updateoperationResponse.getStatusCode()); + Assert.assertNotNull(updateoperationResponse.getRequestId()); + } + + + private static String getOSSourceImage() throws Exception { + String sourceImageName = null; + VirtualMachineOSImageListResponse virtualMachineImageListResponse = computeManagementClient.getVirtualMachineOSImagesOperations().list(); + ArrayList virtualMachineOSImagelist = virtualMachineImageListResponse.getImages(); + + Assert.assertNotNull(virtualMachineOSImagelist); + for (VirtualMachineOSImageListResponse.VirtualMachineOSImage virtualMachineImage : virtualMachineOSImagelist) { + if ((virtualMachineImage.getName().contains("Win-GA")) && (virtualMachineImage.getName().contains("JDK"))) { + sourceImageName = virtualMachineImage.getName(); + break; + } + } + Assert.assertNotNull(sourceImageName); + return sourceImageName; + } + + private static void createStorageAccount() throws Exception { + String storageAccountCreateName = testStoragePrefix + randomString(10); + String storageAccountLabel = testStoragePrefix + "storageLabel1"; + + //Arrange + StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters(); + //required + createParameters.setName(storageAccountCreateName); + //required + createParameters.setLabel(storageAccountLabel); + //required if no affinity group has set + createParameters.setLocation(vmLocation); + + //act + OperationResponse operationResponse = storageManagementClient.getStorageAccountsOperations().create(createParameters); + + //Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + storageAccountName = storageAccountCreateName; + + //use container inside storage account, needed for os image storage. + StorageAccountGetKeysResponse storageAccountGetKeysResponse = storageManagementClient.getStorageAccountsOperations().getKeys(storageAccountCreateName); + storageAccountKey = storageAccountGetKeysResponse.getPrimaryKey(); + CloudBlobClient blobClient = createBlobClient(storageAccountName, storageAccountKey); + CloudBlobContainer container = blobClient.getContainerReference(storageContainer); + container.createIfNotExists(); + + //make sure it created and available, otherwise vm deployment will fail with storage/container still creating + boolean found = false; + while(found == false) { + Iterable listContainerResult = blobClient.listContainers(storageContainer); + for (CloudBlobContainer item : listContainerResult) { + if (item.getName().contains(storageContainer) == true) { + found = true; + } + } + + if (found == false) { + Thread.sleep(1000 * 30); + } + else { + Thread.sleep(1000 * 120); + } + } + } + + private static CloudBlobClient createBlobClient(String storageAccountName, String storageAccountKey) throws InvalidKeyException, URISyntaxException { + String storageconnectionstring = "DefaultEndpointsProtocol=http;AccountName="+ storageAccountName +";AccountKey=" + storageAccountKey ; + CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageconnectionstring); + + // Create the blob client + CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); + return blobClient; + } + + private static void cleanBlob() { + // Create the blob client + CloudBlobClient blobClient = null; + try { + blobClient = createBlobClient(storageAccountName, storageAccountKey); + } catch (InvalidKeyException e) { + } catch (URISyntaxException e) { + } + + // Retrieve reference to a previously created container + CloudBlobContainer container = null; + try { + container = blobClient.getContainerReference(storageContainer); + } catch (URISyntaxException e) { + } catch (StorageException e) { + } + + try { + container.breakLease(300); + } catch (StorageException e) { + } + try { + container.delete(); + } catch (StorageException e) { + } + } + + private static void getLocation() throws Exception { + //has to be a location that support compute, storage, vm, some of the locations are not, need to find out the right one + ArrayList serviceName = new ArrayList(); + serviceName.add(LocationAvailableServiceNames.COMPUTE); + serviceName.add(LocationAvailableServiceNames.PERSISTENTVMROLE); + serviceName.add(LocationAvailableServiceNames.STORAGE); + + LocationsListResponse locationsListResponse = managementClient.getLocationsOperations().list(); + for (LocationsListResponse.Location location : locationsListResponse) { + ArrayList availableServicelist = location.getAvailableServices(); + String locationName = location.getName(); + if ((availableServicelist.containsAll(serviceName) == true) && (locationName.contains("US") == true)) { + vmLocation = locationName; + } + } + } + + private static void cleanStorageAccount() { + StorageAccountGetResponse storageAccountGetResponse = null; + try { + storageAccountGetResponse = storageManagementClient.getStorageAccountsOperations().get(storageAccountName); + } catch (ServiceException e) { + } catch (IOException e) { + } catch (ParserConfigurationException e) { + } catch (SAXException e) { + } catch (URISyntaxException e) { + } + + if ((storageAccountGetResponse != null) && (storageAccountGetResponse.getStorageAccount().getName().contains(storageAccountName))) { + OperationResponse operationResponse = null; + try { + operationResponse = storageManagementClient.getStorageAccountsOperations().delete(storageAccountName); + } catch (IOException e) { + } catch (ServiceException e) { + } + if (operationResponse != null) { + Assert.assertEquals(200, operationResponse.getStatusCode()); + } + } + } + + private static void cleanHostedService() { + HostedServiceGetResponse hostedServiceGetResponse = null; + + try { + hostedServiceGetResponse = computeManagementClient.getHostedServicesOperations().get(hostedServiceName); + } catch (ServiceException e) { + } catch (IOException e) { + } catch (ParserConfigurationException e) { + } catch (SAXException e) { + } catch (URISyntaxException e) { + } + + if ((hostedServiceGetResponse != null ) &&(hostedServiceGetResponse.getServiceName().contains(hostedServiceName))) + { + OperationStatusResponse operationStatusResponse = null; + try { + operationStatusResponse = computeManagementClient.getHostedServicesOperations().deleteAll(hostedServiceName); + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (ServiceException e) { + } catch (IOException e) { + } + if (operationStatusResponse != null) { + Assert.assertEquals(200, operationStatusResponse.getStatusCode()); + } + } + } + + private static void cleanDeployment() { + DeploymentGetResponse deploymentGetResponse = null; + try { + deploymentGetResponse = computeManagementClient.getDeploymentsOperations().getByName(hostedServiceName, deploymentName); + } catch (ServiceException e) { + } catch (IOException e) { + } catch (ParserConfigurationException e) { + } catch (SAXException e) { + } catch (URISyntaxException e) { + } + + if ((deploymentGetResponse != null) && (deploymentGetResponse.getName().contains(deploymentName) == true)) { + OperationStatusResponse operationStatusResponse = null; + try { + operationStatusResponse = computeManagementClient.getDeploymentsOperations().deleteByName(hostedServiceName, deploymentName, true); + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (ServiceException e) { + } catch (IOException e) { + } + if (operationStatusResponse != null) { + Assert.assertEquals(200, operationStatusResponse.getStatusCode()); + } + } + } +} \ No newline at end of file diff --git a/management-network/pom.xml b/management-network/pom.xml new file mode 100644 index 0000000000000..7728de8b2a1a2 --- /dev/null +++ b/management-network/pom.xml @@ -0,0 +1,151 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-management-network + jar + + Microsoft Azure Network Management Client API + Microsoft Azure Network Management SDK Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + 2.1.1 + 3.0.7.RELEASE + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + org.apache.httpcomponents + httpclient + + + javax.inject + javax.inject + + + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk16 + test + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+
+
diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperations.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperations.java new file mode 100644 index 0000000000000..2a794f6027302 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperations.java @@ -0,0 +1,207 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.ClientRootCertificateCreateParameters; +import com.microsoft.windowsazure.management.network.models.ClientRootCertificateGetResponse; +import com.microsoft.windowsazure.management.network.models.ClientRootCertificateListResponse; +import com.microsoft.windowsazure.management.network.models.GatewayOperationResponse; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the client root +* certificates for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for more +* information) +*/ +public interface ClientRootCertificateOperations { + /** + * The Upload Client Root Certificate operation is used to upload a new + * client root certificate to Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Upload Client Root + * Certificate Virtual Network Gateway operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse create(String networkName, ClientRootCertificateCreateParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException; + + /** + * The Upload Client Root Certificate operation is used to upload a new + * client root certificate to Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Upload Client Root + * Certificate Virtual Network Gateway operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future createAsync(String networkName, ClientRootCertificateCreateParameters parameters); + + /** + * The Delete Client Root Certificate operation deletes a previously + * uploaded client root certificate from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse delete(String networkName, String certificateThumbprint) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException; + + /** + * The Delete Client Root Certificate operation deletes a previously + * uploaded client root certificate from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String networkName, String certificateThumbprint); + + /** + * The Get Client Root Certificate operation returns the public portion of a + * previously uploaded client root certificate in a base-64-encoded format + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response to the Get Client Root Certificate operation. + */ + ClientRootCertificateGetResponse get(String networkName, String certificateThumbprint) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Client Root Certificate operation returns the public portion of a + * previously uploaded client root certificate in a base-64-encoded format + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @return Response to the Get Client Root Certificate operation. + */ + Future getAsync(String networkName, String certificateThumbprint); + + /** + * The List Client Root Certificates operation returns a list of all the + * client root certificates that are associated with the specified virtual + * network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response for the List Client Root Certificates operation. + */ + ClientRootCertificateListResponse list(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Client Root Certificates operation returns a list of all the + * client root certificates that are associated with the specified virtual + * network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @return The response for the List Client Root Certificates operation. + */ + Future listAsync(String networkName); +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperationsImpl.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperationsImpl.java new file mode 100644 index 0000000000000..11caaaa11ebea --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperationsImpl.java @@ -0,0 +1,663 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.StreamUtils; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.ClientRootCertificateCreateParameters; +import com.microsoft.windowsazure.management.network.models.ClientRootCertificateGetResponse; +import com.microsoft.windowsazure.management.network.models.ClientRootCertificateListResponse; +import com.microsoft.windowsazure.management.network.models.GatewayOperationResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the client root +* certificates for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for more +* information) +*/ +public class ClientRootCertificateOperationsImpl implements ServiceOperations, ClientRootCertificateOperations { + /** + * Initializes a new instance of the ClientRootCertificateOperationsImpl + * class. + * + * @param client Reference to the service client. + */ + ClientRootCertificateOperationsImpl(NetworkManagementClientImpl client) { + this.client = client; + } + + private NetworkManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.network.NetworkManagementClientImpl. + * @return The Client value. + */ + public NetworkManagementClientImpl getClient() { + return this.client; + } + + /** + * The Upload Client Root Certificate operation is used to upload a new + * client root certificate to Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Upload Client Root + * Certificate Virtual Network Gateway operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future createAsync(final String networkName, final ClientRootCertificateCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return create(networkName, parameters); + } + }); + } + + /** + * The Upload Client Root Certificate operation is used to upload a new + * client root certificate to Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Upload Client Root + * Certificate Virtual Network Gateway operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse create(String networkName, ClientRootCertificateCreateParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getCertificate() == null) { + throw new NullPointerException("parameters.Certificate"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/clientrootcertificates"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = parameters.getCertificate(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Client Root Certificate operation deletes a previously + * uploaded client root certificate from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String networkName, final String certificateThumbprint) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return delete(networkName, certificateThumbprint); + } + }); + } + + /** + * The Delete Client Root Certificate operation deletes a previously + * uploaded client root certificate from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse delete(String networkName, String certificateThumbprint) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (certificateThumbprint == null) { + throw new NullPointerException("certificateThumbprint"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("certificateThumbprint", certificateThumbprint); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/clientrootcertificates/" + certificateThumbprint.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Client Root Certificate operation returns the public portion of a + * previously uploaded client root certificate in a base-64-encoded format + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @return Response to the Get Client Root Certificate operation. + */ + @Override + public Future getAsync(final String networkName, final String certificateThumbprint) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ClientRootCertificateGetResponse call() throws Exception { + return get(networkName, certificateThumbprint); + } + }); + } + + /** + * The Get Client Root Certificate operation returns the public portion of a + * previously uploaded client root certificate in a base-64-encoded format + * from Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param certificateThumbprint Required. The X509 certificate thumbprint. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response to the Get Client Root Certificate operation. + */ + @Override + public ClientRootCertificateGetResponse get(String networkName, String certificateThumbprint) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (certificateThumbprint == null) { + throw new NullPointerException("certificateThumbprint"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("certificateThumbprint", certificateThumbprint); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/clientrootcertificates/" + certificateThumbprint.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ClientRootCertificateGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ClientRootCertificateGetResponse(); + result.setCertificate(StreamUtils.toString(responseContent)); + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Client Root Certificates operation returns a list of all the + * client root certificates that are associated with the specified virtual + * network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @return The response for the List Client Root Certificates operation. + */ + @Override + public Future listAsync(final String networkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ClientRootCertificateListResponse call() throws Exception { + return list(networkName); + } + }); + } + + /** + * The List Client Root Certificates operation returns a list of all the + * client root certificates that are associated with the specified virtual + * network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response for the List Client Root Certificates operation. + */ + @Override + public ClientRootCertificateListResponse list(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/clientrootcertificates"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ClientRootCertificateListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ClientRootCertificateListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element clientRootCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ClientRootCertificates"); + if (clientRootCertificatesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(clientRootCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ClientRootCertificate").size(); i1 = i1 + 1) { + org.w3c.dom.Element clientRootCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(clientRootCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ClientRootCertificate").get(i1)); + ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificateInstance = new ClientRootCertificateListResponse.ClientRootCertificate(); + result.getClientRootCertificates().add(clientRootCertificateInstance); + + Element expirationTimeElement = XmlUtility.getElementByTagNameNS(clientRootCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ExpirationTime"); + if (expirationTimeElement != null) { + Calendar expirationTimeInstance; + expirationTimeInstance = DatatypeConverter.parseDateTime(expirationTimeElement.getTextContent()); + clientRootCertificateInstance.setExpirationTime(expirationTimeInstance); + } + + Element subjectElement = XmlUtility.getElementByTagNameNS(clientRootCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Subject"); + if (subjectElement != null) { + String subjectInstance; + subjectInstance = subjectElement.getTextContent(); + clientRootCertificateInstance.setSubject(subjectInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(clientRootCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + clientRootCertificateInstance.setThumbprint(thumbprintInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/Exports.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/Exports.java new file mode 100644 index 0000000000000..6b262fc4535ce --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/Exports.java @@ -0,0 +1,31 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.Builder; + +/** + * The Class Exports. + */ +public class Exports implements Builder.Exports { + /* (non-Javadoc) + * @see com.microsoft.windowsazure.services.core.Builder.Exports#register(com.microsoft.windowsazure.services.core.Builder.Registry) + */ + @Override + public void register(Builder.Registry registry) { + // provide contract implementation + registry.add(NetworkManagementClient.class, NetworkManagementClientImpl.class); + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperations.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperations.java new file mode 100644 index 0000000000000..a312d6af2e4e0 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperations.java @@ -0,0 +1,788 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.GatewayConnectDisconnectOrTestParameters; +import com.microsoft.windowsazure.management.network.models.GatewayCreateParameters; +import com.microsoft.windowsazure.management.network.models.GatewayGenerateVpnClientPackageParameters; +import com.microsoft.windowsazure.management.network.models.GatewayGetDeviceConfigurationScriptParameters; +import com.microsoft.windowsazure.management.network.models.GatewayGetDeviceConfigurationScriptResponse; +import com.microsoft.windowsazure.management.network.models.GatewayGetOperationStatusResponse; +import com.microsoft.windowsazure.management.network.models.GatewayGetResponse; +import com.microsoft.windowsazure.management.network.models.GatewayGetSharedKeyResponse; +import com.microsoft.windowsazure.management.network.models.GatewayListConnectionsResponse; +import com.microsoft.windowsazure.management.network.models.GatewayListSupportedDevicesResponse; +import com.microsoft.windowsazure.management.network.models.GatewayOperationResponse; +import com.microsoft.windowsazure.management.network.models.GatewayResetSharedKeyParameters; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the gateways for +* your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for more +* information) +*/ +public interface GatewayOperations { + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Begin Connect + * Disconnect Or Testing Gateway operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse beginConnectDisconnectOrTesting(String networkName, String localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Begin Connect + * Disconnect Or Testing Gateway operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future beginConnectDisconnectOrTestingAsync(String networkName, String localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters); + + /** + * The Begin Creating Virtual network Gateway operation creates a new + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Network Gateway operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse beginCreating(String networkName, GatewayCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Creating Virtual network Gateway operation creates a new + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Network Gateway operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future beginCreatingAsync(String networkName, GatewayCreateParameters parameters); + + /** + * The Begin Deleting Virtual Network Gateway operation deletes a network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse beginDeleting(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Begin Deleting Virtual Network Gateway operation deletes a network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future beginDeletingAsync(String networkName); + + /** + * The Begin Failover Virtual Network Gateway operation causes a network + * gateway failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse beginFailover(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Begin Failover Virtual Network Gateway operation causes a network + * gateway failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future beginFailoverAsync(String networkName); + + /** + * The Begin Reset Virtual Network Gateway Shared Key operation resets the + * shared key on the virtual network gateway for the specified virtual + * network connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. Parameters supplied to the Begin Virtual + * Network Gateway Reset Shared Key request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse beginResetSharedKey(String networkName, String localNetworkName, GatewayResetSharedKeyParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Begin Reset Virtual Network Gateway Shared Key operation resets the + * shared key on the virtual network gateway for the specified virtual + * network connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. Parameters supplied to the Begin Virtual + * Network Gateway Reset Shared Key request. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future beginResetSharedKeyAsync(String networkName, String localNetworkName, GatewayResetSharedKeyParameters parameters); + + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Connect Disconnect + * Or Testing Gateway operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + GatewayGetOperationStatusResponse connectDisconnectOrTest(String networkName, String localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Connect Disconnect + * Or Testing Gateway operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future connectDisconnectOrTestAsync(String networkName, String localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters); + + /** + * The Create Virtual network Gateway operation creates a new network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Create Virtual + * Network Gateway operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + GatewayGetOperationStatusResponse create(String networkName, GatewayCreateParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException; + + /** + * The Create Virtual network Gateway operation creates a new network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Create Virtual + * Network Gateway operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future createAsync(String networkName, GatewayCreateParameters parameters); + + /** + * The Delete Virtual Network Gateway operation deletes a network gateway + * for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + GatewayGetOperationStatusResponse delete(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException; + + /** + * The Delete Virtual Network Gateway operation deletes a network gateway + * for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future deleteAsync(String networkName); + + /** + * The Failover Virtual Network Gateway operation causes a network gateway + * failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + GatewayGetOperationStatusResponse failover(String networkName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Failover Virtual Network Gateway operation causes a network gateway + * failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future failoverAsync(String networkName); + + /** + * The Generate VPN Client Package operation creates a VPN client package + * for the specified virtual network and gateway in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205126.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Generate VPN + * Client Package operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayOperationResponse generateVpnClientPackage(String networkName, GatewayGenerateVpnClientPackageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Generate VPN Client Package operation creates a VPN client package + * for the specified virtual network and gateway in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205126.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Generate VPN + * Client Package operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future generateVpnClientPackageAsync(String networkName, GatewayGenerateVpnClientPackageParameters parameters); + + /** + * The Get Virtual Network Gateway operation gets information about the + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154109.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + GatewayGetResponse get(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Virtual Network Gateway operation gets information about the + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154109.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future getAsync(String networkName); + + /** + * The Get Device Configuration Script operation returns a script that you + * can use to configure local VPN devices to connect to the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154115.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. The parameters for the Get Device + * Configuration Script operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The configuration script returned from the get device + * configuration script operation. + */ + GatewayGetDeviceConfigurationScriptResponse getDeviceConfigurationScript(String networkName, GatewayGetDeviceConfigurationScriptParameters parameters) throws IOException, ServiceException; + + /** + * The Get Device Configuration Script operation returns a script that you + * can use to configure local VPN devices to connect to the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154115.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. The parameters for the Get Device + * Configuration Script operation. + * @return The configuration script returned from the get device + * configuration script operation. + */ + Future getDeviceConfigurationScriptAsync(String networkName, GatewayGetDeviceConfigurationScriptParameters parameters); + + /** + * The Get Virtual Network Gateway Operation Status gets information on the + * status of network gateway operations in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx for + * more information) + * + * @param operationId Required. The ID of the network operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + GatewayGetOperationStatusResponse getOperationStatus(String operationId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Virtual Network Gateway Operation Status gets information on the + * status of network gateway operations in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx for + * more information) + * + * @param operationId Required. The ID of the network operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future getOperationStatusAsync(String operationId); + + /** + * The Get Virtual Network Gateway Shared Key operation gets the shared key + * on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154122.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to the get shared key request. + */ + GatewayGetSharedKeyResponse getSharedKey(String networkName, String localNetworkName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Virtual Network Gateway Shared Key operation gets the shared key + * on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154122.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @return The response to the get shared key request. + */ + Future getSharedKeyAsync(String networkName, String localNetworkName); + + /** + * The List Connections operation returns a list of the local network + * connections that can be accessed through the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154120.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to a ListConnections request to a Virtual Network + * Gateway. + */ + GatewayListConnectionsResponse listConnections(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Connections operation returns a list of the local network + * connections that can be accessed through the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154120.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @return The response to a ListConnections request to a Virtual Network + * Gateway. + */ + Future listConnectionsAsync(String networkName); + + /** + * The List Virtual Network Gateway Supported Devices operation lists the + * supported, on-premise network devices that can connect to the gateway. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj154102.aspx + * for more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to the list supported devices request. + */ + GatewayListSupportedDevicesResponse listSupportedDevices() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Virtual Network Gateway Supported Devices operation lists the + * supported, on-premise network devices that can connect to the gateway. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj154102.aspx + * for more information) + * + * @return The response to the list supported devices request. + */ + Future listSupportedDevicesAsync(); + + /** + * The Reset Virtual Network Gateway Shared Key operation resets the shared + * key on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. The parameters to the Virtual Network Gateway + * Reset Shared Key request. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + GatewayGetOperationStatusResponse resetSharedKey(String networkName, String localNetworkName, GatewayResetSharedKeyParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Reset Virtual Network Gateway Shared Key operation resets the shared + * key on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. The parameters to the Virtual Network Gateway + * Reset Shared Key request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future resetSharedKeyAsync(String networkName, String localNetworkName, GatewayResetSharedKeyParameters parameters); +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperationsImpl.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperationsImpl.java new file mode 100644 index 0000000000000..5c03434459563 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperationsImpl.java @@ -0,0 +1,2637 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.StreamUtils; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.GatewayConnectDisconnectOrTestParameters; +import com.microsoft.windowsazure.management.network.models.GatewayConnectivityState; +import com.microsoft.windowsazure.management.network.models.GatewayCreateParameters; +import com.microsoft.windowsazure.management.network.models.GatewayEvent; +import com.microsoft.windowsazure.management.network.models.GatewayGenerateVpnClientPackageParameters; +import com.microsoft.windowsazure.management.network.models.GatewayGetDeviceConfigurationScriptParameters; +import com.microsoft.windowsazure.management.network.models.GatewayGetDeviceConfigurationScriptResponse; +import com.microsoft.windowsazure.management.network.models.GatewayGetOperationStatusResponse; +import com.microsoft.windowsazure.management.network.models.GatewayGetResponse; +import com.microsoft.windowsazure.management.network.models.GatewayGetSharedKeyResponse; +import com.microsoft.windowsazure.management.network.models.GatewayListConnectionsResponse; +import com.microsoft.windowsazure.management.network.models.GatewayListSupportedDevicesResponse; +import com.microsoft.windowsazure.management.network.models.GatewayOperationResponse; +import com.microsoft.windowsazure.management.network.models.GatewayOperationStatus; +import com.microsoft.windowsazure.management.network.models.GatewayResetSharedKeyParameters; +import com.microsoft.windowsazure.management.network.models.GatewayType; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.URLEncoder; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the gateways for +* your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for more +* information) +*/ +public class GatewayOperationsImpl implements ServiceOperations, GatewayOperations { + /** + * Initializes a new instance of the GatewayOperationsImpl class. + * + * @param client Reference to the service client. + */ + GatewayOperationsImpl(NetworkManagementClientImpl client) { + this.client = client; + } + + private NetworkManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.network.NetworkManagementClientImpl. + * @return The Client value. + */ + public NetworkManagementClientImpl getClient() { + return this.client; + } + + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Begin Connect + * Disconnect Or Testing Gateway operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future beginConnectDisconnectOrTestingAsync(final String networkName, final String localNetworkSiteName, final GatewayConnectDisconnectOrTestParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return beginConnectDisconnectOrTesting(networkName, localNetworkSiteName, parameters); + } + }); + } + + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Begin Connect + * Disconnect Or Testing Gateway operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse beginConnectDisconnectOrTesting(String networkName, String localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (localNetworkSiteName == null) { + throw new NullPointerException("localNetworkSiteName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("localNetworkSiteName", localNetworkSiteName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginConnectDisconnectOrTestingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/connection/" + localNetworkSiteName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element updateConnectionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateConnection"); + requestDoc.appendChild(updateConnectionElement); + + Element operationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Operation"); + operationElement.appendChild(requestDoc.createTextNode(parameters.getOperation().toString())); + updateConnectionElement.appendChild(operationElement); + + if (parameters.getIPAddress() != null) { + Element iPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IPAddress"); + iPAddressElement.appendChild(requestDoc.createTextNode(parameters.getIPAddress().getHostAddress())); + updateConnectionElement.appendChild(iPAddressElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Creating Virtual network Gateway operation creates a new + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Network Gateway operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCreatingAsync(final String networkName, final GatewayCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return beginCreating(networkName, parameters); + } + }); + } + + /** + * The Begin Creating Virtual network Gateway operation creates a new + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Begin Creating + * Virtual Network Gateway operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse beginCreating(String networkName, GatewayCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element createGatewayParametersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CreateGatewayParameters"); + requestDoc.appendChild(createGatewayParametersElement); + + Element gatewayTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "GatewayType"); + gatewayTypeElement.appendChild(requestDoc.createTextNode(parameters.getGatewayType().toString())); + createGatewayParametersElement.appendChild(gatewayTypeElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Deleting Virtual Network Gateway operation deletes a network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingAsync(final String networkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return beginDeleting(networkName); + } + }); + } + + /** + * The Begin Deleting Virtual Network Gateway operation deletes a network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse beginDeleting(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Failover Virtual Network Gateway operation causes a network + * gateway failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future beginFailoverAsync(final String networkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return beginFailover(networkName); + } + }); + } + + /** + * The Begin Failover Virtual Network Gateway operation causes a network + * gateway failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse beginFailover(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + CloudTracing.enter(invocationId, this, "beginFailoverAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = "<" + "?" + "xml version=\"1.0\" encoding=\"utf-8\"" + "?" + ">Failover"; + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Begin Reset Virtual Network Gateway Shared Key operation resets the + * shared key on the virtual network gateway for the specified virtual + * network connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. Parameters supplied to the Begin Virtual + * Network Gateway Reset Shared Key request. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future beginResetSharedKeyAsync(final String networkName, final String localNetworkName, final GatewayResetSharedKeyParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return beginResetSharedKey(networkName, localNetworkName, parameters); + } + }); + } + + /** + * The Begin Reset Virtual Network Gateway Shared Key operation resets the + * shared key on the virtual network gateway for the specified virtual + * network connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. Parameters supplied to the Begin Virtual + * Network Gateway Reset Shared Key request. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse beginResetSharedKey(String networkName, String localNetworkName, GatewayResetSharedKeyParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (localNetworkName == null) { + throw new NullPointerException("localNetworkName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("localNetworkName", localNetworkName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginResetSharedKeyAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/connection/" + localNetworkName.trim() + "/sharedkey"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element resetSharedKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResetSharedKey"); + requestDoc.appendChild(resetSharedKeyElement); + + Element keyLengthElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyLength"); + keyLengthElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getKeyLength()))); + resetSharedKeyElement.appendChild(keyLengthElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Connect Disconnect + * Or Testing Gateway operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future connectDisconnectOrTestAsync(final String networkName, final String localNetworkSiteName, final GatewayConnectDisconnectOrTestParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetOperationStatusResponse call() throws Exception { + return connectDisconnectOrTest(networkName, localNetworkSiteName, parameters); + } + }); + } + + /** + * To connect to, disconnect from, or test your connection to a local + * network site, access the connection resource representing the local + * network and specify Connect, Disconnect or Test to perform the desired + * operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154107.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkSiteName Required. The name of the site to connect to. + * @param parameters Required. Parameters supplied to the Connect Disconnect + * Or Testing Gateway operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public GatewayGetOperationStatusResponse connectDisconnectOrTest(String networkName, String localNetworkSiteName, GatewayConnectDisconnectOrTestParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("localNetworkSiteName", localNetworkSiteName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "connectDisconnectOrTestAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + GatewayOperationResponse response = client2.getGatewaysOperations().beginConnectDisconnectOrTestingAsync(networkName, localNetworkSiteName, parameters).get(); + GatewayGetOperationStatusResponse result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != GatewayOperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != GatewayOperationStatus.Successful) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Create Virtual network Gateway operation creates a new network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Create Virtual + * Network Gateway operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future createAsync(final String networkName, final GatewayCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetOperationStatusResponse call() throws Exception { + return create(networkName, parameters); + } + }); + } + + /** + * The Create Virtual network Gateway operation creates a new network + * gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154119.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Create Virtual + * Network Gateway operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public GatewayGetOperationStatusResponse create(String networkName, GatewayCreateParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + GatewayOperationResponse response = client2.getGatewaysOperations().beginCreatingAsync(networkName, parameters).get(); + GatewayGetOperationStatusResponse result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != GatewayOperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != GatewayOperationStatus.Successful) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Virtual Network Gateway operation deletes a network gateway + * for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future deleteAsync(final String networkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetOperationStatusResponse call() throws Exception { + return delete(networkName); + } + }); + } + + /** + * The Delete Virtual Network Gateway operation deletes a network gateway + * for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154129.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public GatewayGetOperationStatusResponse delete(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + GatewayOperationResponse response = client2.getGatewaysOperations().beginDeletingAsync(networkName).get(); + GatewayGetOperationStatusResponse result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != GatewayOperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != GatewayOperationStatus.Successful) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Failover Virtual Network Gateway operation causes a network gateway + * failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future failoverAsync(final String networkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetOperationStatusResponse call() throws Exception { + return failover(networkName); + } + }); + } + + /** + * The Failover Virtual Network Gateway operation causes a network gateway + * failover for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154118.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network in Azure. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public GatewayGetOperationStatusResponse failover(String networkName) throws InterruptedException, ExecutionException, ServiceException, IOException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + CloudTracing.enter(invocationId, this, "failoverAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + GatewayOperationResponse response = client2.getGatewaysOperations().beginFailoverAsync(networkName).get(); + GatewayGetOperationStatusResponse result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != GatewayOperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != GatewayOperationStatus.Successful) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Generate VPN Client Package operation creates a VPN client package + * for the specified virtual network and gateway in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205126.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Generate VPN + * Client Package operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future generateVpnClientPackageAsync(final String networkName, final GatewayGenerateVpnClientPackageParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayOperationResponse call() throws Exception { + return generateVpnClientPackage(networkName, parameters); + } + }); + } + + /** + * The Generate VPN Client Package operation creates a VPN client package + * for the specified virtual network and gateway in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn205126.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. Parameters supplied to the Generate VPN + * Client Package operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayOperationResponse generateVpnClientPackage(String networkName, GatewayGenerateVpnClientPackageParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "generateVpnClientPackageAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/vpnclientpackage"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element vpnClientParametersElement = requestDoc.createElementNS("", "VpnClientParameters"); + requestDoc.appendChild(vpnClientParametersElement); + + Element processorArchitectureElement = requestDoc.createElementNS("", "ProcessorArchitecture"); + processorArchitectureElement.appendChild(requestDoc.createTextNode(parameters.getProcessorArchitecture().toString())); + vpnClientParametersElement.appendChild(processorArchitectureElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayOperationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayOperationResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); + if (gatewayOperationAsyncResponseElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Virtual Network Gateway operation gets information about the + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154109.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future getAsync(final String networkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetResponse call() throws Exception { + return get(networkName); + } + }); + } + + /** + * The Get Virtual Network Gateway operation gets information about the + * network gateway for the specified virtual network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154109.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public GatewayGetResponse get(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element gatewayElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Gateway"); + if (gatewayElement != null) { + Element stateElement = XmlUtility.getElementByTagNameNS(gatewayElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + result.setState(stateInstance); + } + + Element vIPAddressElement = XmlUtility.getElementByTagNameNS(gatewayElement, "http://schemas.microsoft.com/windowsazure", "VIPAddress"); + if (vIPAddressElement != null) { + InetAddress vIPAddressInstance; + vIPAddressInstance = InetAddress.getByName(vIPAddressElement.getTextContent()); + result.setVipAddress(vIPAddressInstance); + } + + Element lastEventElement = XmlUtility.getElementByTagNameNS(gatewayElement, "http://schemas.microsoft.com/windowsazure", "LastEvent"); + if (lastEventElement != null) { + GatewayEvent lastEventInstance = new GatewayEvent(); + result.setLastEvent(lastEventInstance); + + Element timestampElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement != null) { + Calendar timestampInstance; + timestampInstance = DatatypeConverter.parseDateTime(timestampElement.getTextContent()); + lastEventInstance.setTimestamp(timestampInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + lastEventInstance.setId(idInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + lastEventInstance.setMessage(messageInstance); + } + + Element dataElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Data"); + if (dataElement != null) { + String dataInstance; + dataInstance = dataElement.getTextContent(); + lastEventInstance.setData(dataInstance); + } + } + + Element gatewayTypeElement = XmlUtility.getElementByTagNameNS(gatewayElement, "http://schemas.microsoft.com/windowsazure", "GatewayType"); + if (gatewayTypeElement != null) { + GatewayType gatewayTypeInstance; + gatewayTypeInstance = GatewayType.valueOf(gatewayTypeElement.getTextContent()); + result.setGatewayType(gatewayTypeInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Device Configuration Script operation returns a script that you + * can use to configure local VPN devices to connect to the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154115.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. The parameters for the Get Device + * Configuration Script operation. + * @return The configuration script returned from the get device + * configuration script operation. + */ + @Override + public Future getDeviceConfigurationScriptAsync(final String networkName, final GatewayGetDeviceConfigurationScriptParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetDeviceConfigurationScriptResponse call() throws Exception { + return getDeviceConfigurationScript(networkName, parameters); + } + }); + } + + /** + * The Get Device Configuration Script operation returns a script that you + * can use to configure local VPN devices to connect to the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154115.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param parameters Required. The parameters for the Get Device + * Configuration Script operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The configuration script returned from the get device + * configuration script operation. + */ + @Override + public GatewayGetDeviceConfigurationScriptResponse getDeviceConfigurationScript(String networkName, GatewayGetDeviceConfigurationScriptParameters parameters) throws IOException, ServiceException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "getDeviceConfigurationScriptAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/vpndeviceconfigurationscript" + "?"; + if (parameters.getVendor() != null) { + url = url + "vendor=" + URLEncoder.encode(parameters.getVendor().trim(), "UTF-8"); + } + if (parameters.getPlatform() != null) { + url = url + "&" + "platform=" + URLEncoder.encode(parameters.getPlatform().trim(), "UTF-8"); + } + if (parameters.getOSFamily() != null) { + url = url + "&" + "OSfamily=" + URLEncoder.encode(parameters.getOSFamily().trim(), "UTF-8"); + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayGetDeviceConfigurationScriptResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayGetDeviceConfigurationScriptResponse(); + result.setConfigurationScript(StreamUtils.toString(responseContent)); + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Virtual Network Gateway Operation Status gets information on the + * status of network gateway operations in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx for + * more information) + * + * @param operationId Required. The ID of the network operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future getOperationStatusAsync(final String operationId) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetOperationStatusResponse call() throws Exception { + return getOperationStatus(operationId); + } + }); + } + + /** + * The Get Virtual Network Gateway Operation Status gets information on the + * status of network gateway operations in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx for + * more information) + * + * @param operationId Required. The ID of the network operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public GatewayGetOperationStatusResponse getOperationStatus(String operationId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (operationId == null) { + throw new NullPointerException("operationId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("operationId", operationId); + CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/operation/" + operationId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayGetOperationStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayGetOperationStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element gatewayOperationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperation"); + if (gatewayOperationElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setId(idInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + GatewayOperationStatus statusInstance; + statusInstance = GatewayOperationStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement, "http://schemas.microsoft.com/windowsazure", "HttpStatusCode"); + if (httpStatusCodeElement != null) { + Integer httpStatusCodeInstance; + httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent()); + result.setHttpStatusCode(httpStatusCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + GatewayGetOperationStatusResponse.ErrorDetails errorInstance = new GatewayGetOperationStatusResponse.ErrorDetails(); + result.setError(errorInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + errorInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + errorInstance.setMessage(messageInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Virtual Network Gateway Shared Key operation gets the shared key + * on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154122.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @return The response to the get shared key request. + */ + @Override + public Future getSharedKeyAsync(final String networkName, final String localNetworkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetSharedKeyResponse call() throws Exception { + return getSharedKey(networkName, localNetworkName); + } + }); + } + + /** + * The Get Virtual Network Gateway Shared Key operation gets the shared key + * on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154122.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to the get shared key request. + */ + @Override + public GatewayGetSharedKeyResponse getSharedKey(String networkName, String localNetworkName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (localNetworkName == null) { + throw new NullPointerException("localNetworkName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("localNetworkName", localNetworkName); + CloudTracing.enter(invocationId, this, "getSharedKeyAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/connection/" + localNetworkName.trim() + "/sharedkey"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayGetSharedKeyResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayGetSharedKeyResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element sharedKeyElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "SharedKey"); + if (sharedKeyElement != null) { + Element valueElement = XmlUtility.getElementByTagNameNS(sharedKeyElement, "http://schemas.microsoft.com/windowsazure", "Value"); + if (valueElement != null) { + String valueInstance; + valueInstance = valueElement.getTextContent(); + result.setSharedKey(valueInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Connections operation returns a list of the local network + * connections that can be accessed through the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154120.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @return The response to a ListConnections request to a Virtual Network + * Gateway. + */ + @Override + public Future listConnectionsAsync(final String networkName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayListConnectionsResponse call() throws Exception { + return listConnections(networkName); + } + }); + } + + /** + * The List Connections operation returns a list of the local network + * connections that can be accessed through the gateway. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154120.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to a ListConnections request to a Virtual Network + * Gateway. + */ + @Override + public GatewayListConnectionsResponse listConnections(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + CloudTracing.enter(invocationId, this, "listConnectionsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "/gateway/connections"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayListConnectionsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayListConnectionsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element connectionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Connections"); + if (connectionsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(connectionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Connection").size(); i1 = i1 + 1) { + org.w3c.dom.Element connectionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(connectionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Connection").get(i1)); + GatewayListConnectionsResponse.GatewayConnection connectionInstance = new GatewayListConnectionsResponse.GatewayConnection(); + result.getConnections().add(connectionInstance); + + Element localNetworkSiteNameElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "LocalNetworkSiteName"); + if (localNetworkSiteNameElement != null) { + String localNetworkSiteNameInstance; + localNetworkSiteNameInstance = localNetworkSiteNameElement.getTextContent(); + connectionInstance.setLocalNetworkSiteName(localNetworkSiteNameInstance); + } + + Element connectivityStateElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "ConnectivityState"); + if (connectivityStateElement != null) { + GatewayConnectivityState connectivityStateInstance; + connectivityStateInstance = GatewayConnectivityState.valueOf(connectivityStateElement.getTextContent()); + connectionInstance.setConnectivityState(connectivityStateInstance); + } + + Element lastEventElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "LastEvent"); + if (lastEventElement != null) { + GatewayEvent lastEventInstance = new GatewayEvent(); + connectionInstance.setLastEvent(lastEventInstance); + + Element timestampElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Timestamp"); + if (timestampElement != null) { + Calendar timestampInstance; + timestampInstance = DatatypeConverter.parseDateTime(timestampElement.getTextContent()); + lastEventInstance.setTimestamp(timestampInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + lastEventInstance.setId(idInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + lastEventInstance.setMessage(messageInstance); + } + + Element dataElement = XmlUtility.getElementByTagNameNS(lastEventElement, "http://schemas.microsoft.com/windowsazure", "Data"); + if (dataElement != null) { + String dataInstance; + dataInstance = dataElement.getTextContent(); + lastEventInstance.setData(dataInstance); + } + } + + Element ingressBytesTransferredElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "IngressBytesTransferred"); + if (ingressBytesTransferredElement != null) { + long ingressBytesTransferredInstance; + ingressBytesTransferredInstance = DatatypeConverter.parseLong(ingressBytesTransferredElement.getTextContent()); + connectionInstance.setIngressBytesTransferred(ingressBytesTransferredInstance); + } + + Element egressBytesTransferredElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "EgressBytesTransferred"); + if (egressBytesTransferredElement != null) { + long egressBytesTransferredInstance; + egressBytesTransferredInstance = DatatypeConverter.parseLong(egressBytesTransferredElement.getTextContent()); + connectionInstance.setEgressBytesTransferred(egressBytesTransferredInstance); + } + + Element lastConnectionEstablishedElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "LastConnectionEstablished"); + if (lastConnectionEstablishedElement != null) { + Calendar lastConnectionEstablishedInstance; + lastConnectionEstablishedInstance = DatatypeConverter.parseDateTime(lastConnectionEstablishedElement.getTextContent()); + connectionInstance.setLastConnectionEstablished(lastConnectionEstablishedInstance); + } + + Element allocatedIPAddressesSequenceElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "AllocatedIPAddresses"); + if (allocatedIPAddressesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(allocatedIPAddressesSequenceElement, "http://schemas.microsoft.com/windowsazure", "string").size(); i2 = i2 + 1) { + org.w3c.dom.Element allocatedIPAddressesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(allocatedIPAddressesSequenceElement, "http://schemas.microsoft.com/windowsazure", "string").get(i2)); + connectionInstance.getAllocatedIPAddresses().add(allocatedIPAddressesElement.getTextContent()); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Virtual Network Gateway Supported Devices operation lists the + * supported, on-premise network devices that can connect to the gateway. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj154102.aspx + * for more information) + * + * @return The response to the list supported devices request. + */ + @Override + public Future listSupportedDevicesAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayListSupportedDevicesResponse call() throws Exception { + return listSupportedDevices(); + } + }); + } + + /** + * The List Virtual Network Gateway Supported Devices operation lists the + * supported, on-premise network devices that can connect to the gateway. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj154102.aspx + * for more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to the list supported devices request. + */ + @Override + public GatewayListSupportedDevicesResponse listSupportedDevices() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listSupportedDevicesAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/supporteddevices"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + GatewayListSupportedDevicesResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new GatewayListSupportedDevicesResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element vpnDeviceListElement = XmlUtility.getElementByTagNameNS(responseDoc, "", "VpnDeviceList"); + if (vpnDeviceListElement != null) { + Attr versionAttribute = vpnDeviceListElement.getAttributeNodeNS("", "version"); + if (versionAttribute != null) { + result.setVersion(versionAttribute.getValue()); + } + + if (vpnDeviceListElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(vpnDeviceListElement, "", "Vendor").size(); i1 = i1 + 1) { + org.w3c.dom.Element vendorsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(vpnDeviceListElement, "", "Vendor").get(i1)); + GatewayListSupportedDevicesResponse.Vendor vendorInstance = new GatewayListSupportedDevicesResponse.Vendor(); + result.getVendors().add(vendorInstance); + + Attr nameAttribute = vendorsElement.getAttributeNodeNS("", "name"); + if (nameAttribute != null) { + vendorInstance.setName(nameAttribute.getValue()); + } + + if (vendorsElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(vendorsElement, "", "Platform").size(); i2 = i2 + 1) { + org.w3c.dom.Element platformsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(vendorsElement, "", "Platform").get(i2)); + GatewayListSupportedDevicesResponse.Platform platformInstance = new GatewayListSupportedDevicesResponse.Platform(); + vendorInstance.getPlatforms().add(platformInstance); + + Attr nameAttribute2 = platformsElement.getAttributeNodeNS("", "name"); + if (nameAttribute2 != null) { + platformInstance.setName(nameAttribute2.getValue()); + } + + if (platformsElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(platformsElement, "", "OSFamily").size(); i3 = i3 + 1) { + org.w3c.dom.Element oSFamiliesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(platformsElement, "", "OSFamily").get(i3)); + GatewayListSupportedDevicesResponse.OSFamily oSFamilyInstance = new GatewayListSupportedDevicesResponse.OSFamily(); + platformInstance.getOSFamilies().add(oSFamilyInstance); + + Attr nameAttribute3 = oSFamiliesElement.getAttributeNodeNS("", "name"); + if (nameAttribute3 != null) { + oSFamilyInstance.setName(nameAttribute3.getValue()); + } + } + } + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Reset Virtual Network Gateway Shared Key operation resets the shared + * key on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. The parameters to the Virtual Network Gateway + * Reset Shared Key request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future resetSharedKeyAsync(final String networkName, final String localNetworkName, final GatewayResetSharedKeyParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public GatewayGetOperationStatusResponse call() throws Exception { + return resetSharedKey(networkName, localNetworkName, parameters); + } + }); + } + + /** + * The Reset Virtual Network Gateway Shared Key operation resets the shared + * key on the virtual network gateway for the specified virtual network + * connection to the specified local network in Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for + * more information) + * + * @param networkName Required. The name of the virtual network for this + * gateway. + * @param localNetworkName Required. The name of the local network. + * @param parameters Required. The parameters to the Virtual Network Gateway + * Reset Shared Key request. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is in + * progress, or has failed. Note that this status is distinct from the HTTP + * status code returned for the Get Operation Status operation itself. If + * the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public GatewayGetOperationStatusResponse resetSharedKey(String networkName, String localNetworkName, GatewayResetSharedKeyParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("localNetworkName", localNetworkName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "resetSharedKeyAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + GatewayOperationResponse response = client2.getGatewaysOperations().beginResetSharedKeyAsync(networkName, localNetworkName, parameters).get(); + GatewayGetOperationStatusResponse result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != GatewayOperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getGatewaysOperations().getOperationStatusAsync(response.getOperationId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != GatewayOperationStatus.Successful) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementClient.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementClient.java new file mode 100644 index 0000000000000..0869a8bdd7597 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementClient.java @@ -0,0 +1,155 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.FilterableService; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import java.io.Closeable; +import java.io.IOException; +import java.net.URI; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* networks for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for more +* information) +*/ +public interface NetworkManagementClient extends Closeable, FilterableService { + /** + * The URI used as the base for all SQL requests. + * @return The BaseUri value. + */ + URI getBaseUri(); + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + SubscriptionCloudCredentials getCredentials(); + + /** + * The Network Management API includes operations for managing the client + * root certificates for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for + * more information) + * @return The ClientRootCertificatesOperations value. + */ + ClientRootCertificateOperations getClientRootCertificatesOperations(); + + /** + * The Network Management API includes operations for managing the gateways + * for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for + * more information) + * @return The GatewaysOperations value. + */ + GatewayOperations getGatewaysOperations(); + + /** + * The Network Management API includes operations for managing the virtual + * networks for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for + * more information) + * @return The NetworksOperations value. + */ + NetworkOperations getNetworksOperations(); + + /** + * The Network Management API includes operations for managing the reserved + * IPs for your subscription. + * @return The ReservedIPsOperations value. + */ + ReservedIPOperations getReservedIPsOperations(); + + /** + * The Network Management API includes operations for managing the static + * IPs for your subscription. + * @return The StaticIPsOperations value. + */ + StaticIPOperations getStaticIPsOperations(); + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future getOperationStatusAsync(String requestId); +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementClientImpl.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementClientImpl.java new file mode 100644 index 0000000000000..d60e15bfe80c4 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementClientImpl.java @@ -0,0 +1,445 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceClient; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.management.network.models.LocalNetworkConnectionType; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import javax.inject.Inject; +import javax.inject.Named; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the virtual +* networks for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for more +* information) +*/ +public class NetworkManagementClientImpl extends ServiceClient implements NetworkManagementClient { + private URI baseUri; + + /** + * The URI used as the base for all SQL requests. + * @return The BaseUri value. + */ + public URI getBaseUri() { + return this.baseUri; + } + + private SubscriptionCloudCredentials credentials; + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + public SubscriptionCloudCredentials getCredentials() { + return this.credentials; + } + + private ClientRootCertificateOperations clientRootCertificates; + + /** + * The Network Management API includes operations for managing the client + * root certificates for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for + * more information) + * @return The ClientRootCertificatesOperations value. + */ + public ClientRootCertificateOperations getClientRootCertificatesOperations() { + return this.clientRootCertificates; + } + + private GatewayOperations gateways; + + /** + * The Network Management API includes operations for managing the gateways + * for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for + * more information) + * @return The GatewaysOperations value. + */ + public GatewayOperations getGatewaysOperations() { + return this.gateways; + } + + private NetworkOperations networks; + + /** + * The Network Management API includes operations for managing the virtual + * networks for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for + * more information) + * @return The NetworksOperations value. + */ + public NetworkOperations getNetworksOperations() { + return this.networks; + } + + private ReservedIPOperations reservedIPs; + + /** + * The Network Management API includes operations for managing the reserved + * IPs for your subscription. + * @return The ReservedIPsOperations value. + */ + public ReservedIPOperations getReservedIPsOperations() { + return this.reservedIPs; + } + + private StaticIPOperations staticIPs; + + /** + * The Network Management API includes operations for managing the static + * IPs for your subscription. + * @return The StaticIPsOperations value. + */ + public StaticIPOperations getStaticIPsOperations() { + return this.staticIPs; + } + + /** + * Initializes a new instance of the NetworkManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + private NetworkManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) { + super(httpBuilder, executorService); + this.clientRootCertificates = new ClientRootCertificateOperationsImpl(this); + this.gateways = new GatewayOperationsImpl(this); + this.networks = new NetworkOperationsImpl(this); + this.reservedIPs = new ReservedIPOperationsImpl(this); + this.staticIPs = new StaticIPOperationsImpl(this); + } + + /** + * Initializes a new instance of the NetworkManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @param baseUri Required. The URI used as the base for all SQL requests. + */ + @Inject + public NetworkManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } else { + this.credentials = credentials; + } + if (baseUri == null) { + try { + this.baseUri = new URI("https://management.core.windows.net"); + } + catch (URISyntaxException ex) { + } + } else { + this.baseUri = baseUri; + } + } + + /** + * Initializes a new instance of the NetworkManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + */ + public NetworkManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } + this.credentials = credentials; + this.baseUri = new URI("https://management.core.windows.net"); + } + + /** + * Initializes a new instance of the NetworkManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + protected NetworkManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) { + return new NetworkManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri()); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future getOperationStatusAsync(final String requestId) { + return this.getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return getOperationStatus(requestId); + } + }); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (requestId == null) { + throw new NullPointerException("requestId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("requestId", requestId); + CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getBaseUri().toString(); + String url = "/" + this.getCredentials().getSubscriptionId().trim() + "/operations/" + requestId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new OperationStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setId(idInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + OperationStatus statusInstance; + statusInstance = OperationStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "HttpStatusCode"); + if (httpStatusCodeElement != null) { + Integer httpStatusCodeInstance; + httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent()); + result.setHttpStatusCode(httpStatusCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); + result.setError(errorInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + errorInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + errorInstance.setMessage(messageInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Parse enum values for type LocalNetworkConnectionType. + * + * @param value The value to parse. + * @return The enum value. + */ + static LocalNetworkConnectionType parseLocalNetworkConnectionType(String value) { + if ("IPsec".equalsIgnoreCase(value)) { + return LocalNetworkConnectionType.IPSecurity; + } + if ("Dedicated".equalsIgnoreCase(value)) { + return LocalNetworkConnectionType.Dedicated; + } + throw new IllegalArgumentException("value"); + } + + /** + * Convert an enum of type LocalNetworkConnectionType to a string. + * + * @param value The value to convert to a string. + * @return The enum value as a string. + */ + static String localNetworkConnectionTypeToString(LocalNetworkConnectionType value) { + if (value == LocalNetworkConnectionType.IPSecurity) { + return "IPsec"; + } + if (value == LocalNetworkConnectionType.Dedicated) { + return "Dedicated"; + } + throw new IllegalArgumentException("value"); + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementService.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementService.java new file mode 100644 index 0000000000000..c4f874ae14802 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkManagementService.java @@ -0,0 +1,82 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.Configuration; + +/** + * + * Access service management functionality. + * + */ +public final class NetworkManagementService { + private NetworkManagementService() { + // class is not instantiated + } + + /** + * Creates an instance of the VirtualNetworkManagementClient + * API. + * @return An instance of the VirtualNetworkManagementClient + * API. + */ + public static NetworkManagementClient create() { + return Configuration.getInstance().create( + NetworkManagementClient.class); + } + + /** + * Creates an instance of the VirtualNetworkManagementClient + * API using the specified configuration. + * + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the VirtualNetworkManagementClient + * API. + */ + public static NetworkManagementClient create( + final Configuration config) { + return config.create(NetworkManagementClient.class); + } + + /** + * Creates an instance of the VirtualNetworkManagementClient + * API. + * + * @param profile A String object that representing the profile + * of the service management service. + * @return An instance of the VirtualNetworkManagementClient + * API. + */ + public static NetworkManagementClient create(final String profile) { + return Configuration.getInstance().create(profile, + NetworkManagementClient.class); + } + + /** + * Creates an instance of the VirtualNetworkManagementClient + * API using the specified configuration. + * + * @param profile The profile. + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the VirtualNetworkManagementClient + * API. + */ + public static NetworkManagementClient create(final String profile, + final Configuration config) { + return config.create(profile, NetworkManagementClient.class); + } +} \ No newline at end of file diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkOperations.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkOperations.java new file mode 100644 index 0000000000000..31dc0569aa2c1 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkOperations.java @@ -0,0 +1,178 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.NetworkGetConfigurationResponse; +import com.microsoft.windowsazure.management.network.models.NetworkListResponse; +import com.microsoft.windowsazure.management.network.models.NetworkSetConfigurationParameters; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the virtual +* networks for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for more +* information) +*/ +public interface NetworkOperations { + /** + * The Begin Setting Network Configuration operation asynchronously + * configures the virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + OperationResponse beginSettingConfiguration(NetworkSetConfigurationParameters parameters) throws IOException, ServiceException; + + /** + * The Begin Setting Network Configuration operation asynchronously + * configures the virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future beginSettingConfigurationAsync(NetworkSetConfigurationParameters parameters); + + /** + * The Get Network Configuration operation retrieves the network + * configuration file for the given subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The Get Network Configuration operation response. + */ + NetworkGetConfigurationResponse getConfiguration() throws IOException, ServiceException; + + /** + * The Get Network Configuration operation retrieves the network + * configuration file for the given subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for + * more information) + * + * @return The Get Network Configuration operation response. + */ + Future getConfigurationAsync(); + + /** + * The List Virtual network sites operation retrieves the virtual networks + * configured for the subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response structure for the Network Operations List operation. + */ + NetworkListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Virtual network sites operation retrieves the virtual networks + * configured for the subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx for + * more information) + * + * @return The response structure for the Network Operations List operation. + */ + Future listAsync(); + + /** + * The Set Network Configuration operation asynchronously configures the + * virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse setConfiguration(NetworkSetConfigurationParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Set Network Configuration operation asynchronously configures the + * virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future setConfigurationAsync(NetworkSetConfigurationParameters parameters); +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkOperationsImpl.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkOperationsImpl.java new file mode 100644 index 0000000000000..71d01a44a1fb6 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/NetworkOperationsImpl.java @@ -0,0 +1,718 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.StreamUtils; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.GatewayProfile; +import com.microsoft.windowsazure.management.network.models.LocalNetworkConnectionType; +import com.microsoft.windowsazure.management.network.models.NetworkGetConfigurationResponse; +import com.microsoft.windowsazure.management.network.models.NetworkListResponse; +import com.microsoft.windowsazure.management.network.models.NetworkSetConfigurationParameters; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the virtual +* networks for your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for more +* information) +*/ +public class NetworkOperationsImpl implements ServiceOperations, NetworkOperations { + /** + * Initializes a new instance of the NetworkOperationsImpl class. + * + * @param client Reference to the service client. + */ + NetworkOperationsImpl(NetworkManagementClientImpl client) { + this.client = client; + } + + private NetworkManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.network.NetworkManagementClientImpl. + * @return The Client value. + */ + public NetworkManagementClientImpl getClient() { + return this.client; + } + + /** + * The Begin Setting Network Configuration operation asynchronously + * configures the virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future beginSettingConfigurationAsync(final NetworkSetConfigurationParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginSettingConfiguration(parameters); + } + }); + } + + /** + * The Begin Setting Network Configuration operation asynchronously + * configures the virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginSettingConfiguration(NetworkSetConfigurationParameters parameters) throws IOException, ServiceException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getConfiguration() == null) { + throw new NullPointerException("parameters.Configuration"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginSettingConfigurationAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/media"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/octet-stream"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = parameters.getConfiguration(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/octet-stream"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Network Configuration operation retrieves the network + * configuration file for the given subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for + * more information) + * + * @return The Get Network Configuration operation response. + */ + @Override + public Future getConfigurationAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public NetworkGetConfigurationResponse call() throws Exception { + return getConfiguration(); + } + }); + } + + /** + * The Get Network Configuration operation retrieves the network + * configuration file for the given subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The Get Network Configuration operation response. + */ + @Override + public NetworkGetConfigurationResponse getConfiguration() throws IOException, ServiceException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "getConfigurationAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/media"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + NetworkGetConfigurationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new NetworkGetConfigurationResponse(); + result.setConfiguration(StreamUtils.toString(responseContent)); + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Virtual network sites operation retrieves the virtual networks + * configured for the subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx for + * more information) + * + * @return The response structure for the Network Operations List operation. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public NetworkListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Virtual network sites operation retrieves the virtual networks + * configured for the subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response structure for the Network Operations List operation. + */ + @Override + public NetworkListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/virtualnetwork"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + NetworkListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new NetworkListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element virtualNetworkSitesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "VirtualNetworkSites"); + if (virtualNetworkSitesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualNetworkSitesSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualNetworkSite").size(); i1 = i1 + 1) { + org.w3c.dom.Element virtualNetworkSitesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(virtualNetworkSitesSequenceElement, "http://schemas.microsoft.com/windowsazure", "VirtualNetworkSite").get(i1)); + NetworkListResponse.VirtualNetworkSite virtualNetworkSiteInstance = new NetworkListResponse.VirtualNetworkSite(); + result.getVirtualNetworkSites().add(virtualNetworkSiteInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + virtualNetworkSiteInstance.setName(nameInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + virtualNetworkSiteInstance.setLabel(labelInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + virtualNetworkSiteInstance.setId(idInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + virtualNetworkSiteInstance.setAffinityGroup(affinityGroupInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + virtualNetworkSiteInstance.setState(stateInstance); + } + + Element addressSpaceElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "AddressSpace"); + if (addressSpaceElement != null) { + NetworkListResponse.AddressSpace addressSpaceInstance = new NetworkListResponse.AddressSpace(); + virtualNetworkSiteInstance.setAddressSpace(addressSpaceInstance); + + Element addressPrefixesSequenceElement = XmlUtility.getElementByTagNameNS(addressSpaceElement, "http://schemas.microsoft.com/windowsazure", "AddressPrefixes"); + if (addressPrefixesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(addressPrefixesSequenceElement, "http://schemas.microsoft.com/windowsazure", "AddressPrefix").size(); i2 = i2 + 1) { + org.w3c.dom.Element addressPrefixesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(addressPrefixesSequenceElement, "http://schemas.microsoft.com/windowsazure", "AddressPrefix").get(i2)); + addressSpaceInstance.getAddressPrefixes().add(addressPrefixesElement.getTextContent()); + } + } + } + + Element subnetsSequenceElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "Subnets"); + if (subnetsSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Subnet").size(); i3 = i3 + 1) { + org.w3c.dom.Element subnetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subnetsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Subnet").get(i3)); + NetworkListResponse.Subnet subnetInstance = new NetworkListResponse.Subnet(); + virtualNetworkSiteInstance.getSubnets().add(subnetInstance); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(subnetsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + subnetInstance.setName(nameInstance2); + } + + Element addressPrefixElement = XmlUtility.getElementByTagNameNS(subnetsElement, "http://schemas.microsoft.com/windowsazure", "AddressPrefix"); + if (addressPrefixElement != null) { + String addressPrefixInstance; + addressPrefixInstance = addressPrefixElement.getTextContent(); + subnetInstance.setAddressPrefix(addressPrefixInstance); + } + } + } + + Element dnsElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "Dns"); + if (dnsElement != null) { + Element dnsServersSequenceElement = XmlUtility.getElementByTagNameNS(dnsElement, "http://schemas.microsoft.com/windowsazure", "DnsServers"); + if (dnsServersSequenceElement != null) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").size(); i4 = i4 + 1) { + org.w3c.dom.Element dnsServersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dnsServersSequenceElement, "http://schemas.microsoft.com/windowsazure", "DnsServer").get(i4)); + NetworkListResponse.DnsServer dnsServerInstance = new NetworkListResponse.DnsServer(); + virtualNetworkSiteInstance.getDnsServers().add(dnsServerInstance); + + Element nameElement3 = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement3 != null) { + String nameInstance3; + nameInstance3 = nameElement3.getTextContent(); + dnsServerInstance.setName(nameInstance3); + } + + Element addressElement = XmlUtility.getElementByTagNameNS(dnsServersElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement != null) { + InetAddress addressInstance; + addressInstance = InetAddress.getByName(addressElement.getTextContent()); + dnsServerInstance.setAddress(addressInstance); + } + } + } + } + + Element gatewayElement = XmlUtility.getElementByTagNameNS(virtualNetworkSitesElement, "http://schemas.microsoft.com/windowsazure", "Gateway"); + if (gatewayElement != null) { + NetworkListResponse.Gateway gatewayInstance = new NetworkListResponse.Gateway(); + virtualNetworkSiteInstance.setGateway(gatewayInstance); + + Element profileElement = XmlUtility.getElementByTagNameNS(gatewayElement, "http://schemas.microsoft.com/windowsazure", "Profile"); + if (profileElement != null) { + GatewayProfile profileInstance; + profileInstance = GatewayProfile.valueOf(profileElement.getTextContent()); + gatewayInstance.setProfile(profileInstance); + } + + Element sitesSequenceElement = XmlUtility.getElementByTagNameNS(gatewayElement, "http://schemas.microsoft.com/windowsazure", "Sites"); + if (sitesSequenceElement != null) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sitesSequenceElement, "http://schemas.microsoft.com/windowsazure", "LocalNetworkSite").size(); i5 = i5 + 1) { + org.w3c.dom.Element sitesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sitesSequenceElement, "http://schemas.microsoft.com/windowsazure", "LocalNetworkSite").get(i5)); + NetworkListResponse.LocalNetworkSite localNetworkSiteInstance = new NetworkListResponse.LocalNetworkSite(); + gatewayInstance.getSites().add(localNetworkSiteInstance); + + Element nameElement4 = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement4 != null) { + String nameInstance4; + nameInstance4 = nameElement4.getTextContent(); + localNetworkSiteInstance.setName(nameInstance4); + } + + Element vpnGatewayAddressElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "VpnGatewayAddress"); + if (vpnGatewayAddressElement != null) { + InetAddress vpnGatewayAddressInstance; + vpnGatewayAddressInstance = InetAddress.getByName(vpnGatewayAddressElement.getTextContent()); + localNetworkSiteInstance.setVpnGatewayAddress(vpnGatewayAddressInstance); + } + + Element addressSpaceElement2 = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "AddressSpace"); + if (addressSpaceElement2 != null) { + NetworkListResponse.AddressSpace addressSpaceInstance2 = new NetworkListResponse.AddressSpace(); + localNetworkSiteInstance.setAddressSpace(addressSpaceInstance2); + + Element addressPrefixesSequenceElement2 = XmlUtility.getElementByTagNameNS(addressSpaceElement2, "http://schemas.microsoft.com/windowsazure", "AddressPrefixes"); + if (addressPrefixesSequenceElement2 != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(addressPrefixesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "AddressPrefix").size(); i6 = i6 + 1) { + org.w3c.dom.Element addressPrefixesElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(addressPrefixesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "AddressPrefix").get(i6)); + addressSpaceInstance2.getAddressPrefixes().add(addressPrefixesElement2.getTextContent()); + } + } + } + + Element connectionsSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "Connections"); + if (connectionsSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(connectionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Connection").size(); i7 = i7 + 1) { + org.w3c.dom.Element connectionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(connectionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Connection").get(i7)); + NetworkListResponse.Connection connectionInstance = new NetworkListResponse.Connection(); + localNetworkSiteInstance.getConnections().add(connectionInstance); + + Element typeElement = XmlUtility.getElementByTagNameNS(connectionsElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + LocalNetworkConnectionType typeInstance; + typeInstance = NetworkManagementClientImpl.parseLocalNetworkConnectionType(typeElement.getTextContent()); + connectionInstance.setType(typeInstance); + } + } + } + } + } + + Element vPNClientAddressPoolElement = XmlUtility.getElementByTagNameNS(gatewayElement, "http://schemas.microsoft.com/windowsazure", "VPNClientAddressPool"); + if (vPNClientAddressPoolElement != null) { + NetworkListResponse.VPNClientAddressPool vPNClientAddressPoolInstance = new NetworkListResponse.VPNClientAddressPool(); + gatewayInstance.setVPNClientAddressPool(vPNClientAddressPoolInstance); + + Element addressPrefixesSequenceElement3 = XmlUtility.getElementByTagNameNS(vPNClientAddressPoolElement, "http://schemas.microsoft.com/windowsazure", "AddressPrefixes"); + if (addressPrefixesSequenceElement3 != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(addressPrefixesSequenceElement3, "http://schemas.microsoft.com/windowsazure", "AddressPrefix").size(); i8 = i8 + 1) { + org.w3c.dom.Element addressPrefixesElement3 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(addressPrefixesSequenceElement3, "http://schemas.microsoft.com/windowsazure", "AddressPrefix").get(i8)); + vPNClientAddressPoolInstance.getAddressPrefixes().add(addressPrefixesElement3.getTextContent()); + } + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Set Network Configuration operation asynchronously configures the + * virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future setConfigurationAsync(final NetworkSetConfigurationParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return setConfiguration(parameters); + } + }); + } + + /** + * The Set Network Configuration operation asynchronously configures the + * virtual network. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Set Network + * Configuration operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse setConfiguration(NetworkSetConfigurationParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "setConfigurationAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getNetworksOperations().beginSettingConfigurationAsync(parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/ReservedIPOperations.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ReservedIPOperations.java new file mode 100644 index 0000000000000..3390553acde4f --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ReservedIPOperations.java @@ -0,0 +1,275 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.NetworkReservedIPCreateParameters; +import com.microsoft.windowsazure.management.network.models.NetworkReservedIPGetResponse; +import com.microsoft.windowsazure.management.network.models.NetworkReservedIPListResponse; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the reserved IPs +* for your subscription. +*/ +public interface ReservedIPOperations { + /** + * Preview Only. The Begin Creating Reserved IP operation creates a reserved + * IP from your the subscription. + * + * @param parameters Required. Parameters supplied to the Begin Creating + * Reserved IP operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse beginCreating(NetworkReservedIPCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Preview Only. The Begin Creating Reserved IP operation creates a reserved + * IP from your the subscription. + * + * @param parameters Required. Parameters supplied to the Begin Creating + * Reserved IP operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future beginCreatingAsync(NetworkReservedIPCreateParameters parameters); + + /** + * Preview Only. The Begin Deleting Reserved IP operation removes a reserved + * IP from your the subscription. + * + * @param ipName Required. The name of the reserved IP. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + OperationResponse beginDeleting(String ipName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Preview Only. The Begin Deleting Reserved IP operation removes a reserved + * IP from your the subscription. + * + * @param ipName Required. The name of the reserved IP. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + Future beginDeletingAsync(String ipName); + + /** + * The Create Reserved IP operation creates a reserved IP from your the + * subscription. + * + * @param parameters Required. Parameters supplied to the Create Reserved IP + * operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse create(NetworkReservedIPCreateParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException; + + /** + * The Create Reserved IP operation creates a reserved IP from your the + * subscription. + * + * @param parameters Required. Parameters supplied to the Create Reserved IP + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future createAsync(NetworkReservedIPCreateParameters parameters); + + /** + * The Delete Reserved IP operation removes a reserved IP from your the + * subscription. + * + * @param ipName Required. The name of the reserved IP. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse delete(String ipName) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException; + + /** + * The Delete Reserved IP operation removes a reserved IP from your the + * subscription. + * + * @param ipName Required. The name of the reserved IP. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future deleteAsync(String ipName); + + /** + * Preview Only. The Get Reserved IP operation retrieves the details for the + * virtual IP reserved for the subscription. + * + * @param ipName Required. The name of the reserved IP to retrieve. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Preview Only. A reserved IP associated with your subscription. + */ + NetworkReservedIPGetResponse get(String ipName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Preview Only. The Get Reserved IP operation retrieves the details for the + * virtual IP reserved for the subscription. + * + * @param ipName Required. The name of the reserved IP to retrieve. + * @return Preview Only. A reserved IP associated with your subscription. + */ + Future getAsync(String ipName); + + /** + * Preview Only. The List Reserved IP operation retrieves all of the virtual + * IPs reserved for the subscription. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Preview Only. The response structure for the Server List + * operation. + */ + NetworkReservedIPListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Preview Only. The List Reserved IP operation retrieves all of the virtual + * IPs reserved for the subscription. + * + * @return Preview Only. The response structure for the Server List + * operation. + */ + Future listAsync(); +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/ReservedIPOperationsImpl.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ReservedIPOperationsImpl.java new file mode 100644 index 0000000000000..ad3bd133a70b8 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/ReservedIPOperationsImpl.java @@ -0,0 +1,962 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.NetworkReservedIPCreateParameters; +import com.microsoft.windowsazure.management.network.models.NetworkReservedIPGetResponse; +import com.microsoft.windowsazure.management.network.models.NetworkReservedIPListResponse; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the reserved IPs +* for your subscription. +*/ +public class ReservedIPOperationsImpl implements ServiceOperations, ReservedIPOperations { + /** + * Initializes a new instance of the ReservedIPOperationsImpl class. + * + * @param client Reference to the service client. + */ + ReservedIPOperationsImpl(NetworkManagementClientImpl client) { + this.client = client; + } + + private NetworkManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.network.NetworkManagementClientImpl. + * @return The Client value. + */ + public NetworkManagementClientImpl getClient() { + return this.client; + } + + /** + * Preview Only. The Begin Creating Reserved IP operation creates a reserved + * IP from your the subscription. + * + * @param parameters Required. Parameters supplied to the Begin Creating + * Reserved IP operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future beginCreatingAsync(final NetworkReservedIPCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return beginCreating(parameters); + } + }); + } + + /** + * Preview Only. The Begin Creating Reserved IP operation creates a reserved + * IP from your the subscription. + * + * @param parameters Required. Parameters supplied to the Begin Creating + * Reserved IP operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse beginCreating(NetworkReservedIPCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/reservedips"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element reservedIPElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIP"); + requestDoc.appendChild(reservedIPElement); + + if (parameters.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + reservedIPElement.appendChild(nameElement); + } + + if (parameters.getLabel() != null) { + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); + reservedIPElement.appendChild(labelElement); + } + + if (parameters.getAffinityGroup() != null) { + Element affinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + affinityGroupElement.appendChild(requestDoc.createTextNode(parameters.getAffinityGroup())); + reservedIPElement.appendChild(affinityGroupElement); + } + + if (parameters.getServiceName() != null) { + Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceName"); + serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName())); + reservedIPElement.appendChild(serviceNameElement); + } + + if (parameters.getDeploymentName() != null) { + Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DeploymentName"); + deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName())); + reservedIPElement.appendChild(deploymentNameElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationStatusResponse result = null; + result = new OperationStatusResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Preview Only. The Begin Deleting Reserved IP operation removes a reserved + * IP from your the subscription. + * + * @param ipName Required. The name of the reserved IP. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public Future beginDeletingAsync(final String ipName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginDeleting(ipName); + } + }); + } + + /** + * Preview Only. The Begin Deleting Reserved IP operation removes a reserved + * IP from your the subscription. + * + * @param ipName Required. The name of the reserved IP. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard storage response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginDeleting(String ipName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (ipName == null) { + throw new NullPointerException("ipName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("ipName", ipName); + CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/reservedips/" + ipName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Create Reserved IP operation creates a reserved IP from your the + * subscription. + * + * @param parameters Required. Parameters supplied to the Create Reserved IP + * operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future createAsync(final NetworkReservedIPCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return create(parameters); + } + }); + } + + /** + * The Create Reserved IP operation creates a reserved IP from your the + * subscription. + * + * @param parameters Required. Parameters supplied to the Create Reserved IP + * operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse create(NetworkReservedIPCreateParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationStatusResponse response = client2.getReservedIPsOperations().beginCreatingAsync(parameters).get(); + if (response.getStatus() == OperationStatus.Succeeded) { + return response; + } + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Reserved IP operation removes a reserved IP from your the + * subscription. + * + * @param ipName Required. The name of the reserved IP. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future deleteAsync(final String ipName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return delete(ipName); + } + }); + } + + /** + * The Delete Reserved IP operation removes a reserved IP from your the + * subscription. + * + * @param ipName Required. The name of the reserved IP. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse delete(String ipName) throws IOException, ServiceException, ParserConfigurationException, SAXException, InterruptedException, ExecutionException { + NetworkManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("ipName", ipName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getReservedIPsOperations().beginDeletingAsync(ipName).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * Preview Only. The Get Reserved IP operation retrieves the details for the + * virtual IP reserved for the subscription. + * + * @param ipName Required. The name of the reserved IP to retrieve. + * @return Preview Only. A reserved IP associated with your subscription. + */ + @Override + public Future getAsync(final String ipName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public NetworkReservedIPGetResponse call() throws Exception { + return get(ipName); + } + }); + } + + /** + * Preview Only. The Get Reserved IP operation retrieves the details for the + * virtual IP reserved for the subscription. + * + * @param ipName Required. The name of the reserved IP to retrieve. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Preview Only. A reserved IP associated with your subscription. + */ + @Override + public NetworkReservedIPGetResponse get(String ipName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (ipName == null) { + throw new NullPointerException("ipName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("ipName", ipName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/reservedips/" + ipName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + NetworkReservedIPGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new NetworkReservedIPGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element reservedIPElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ReservedIP"); + if (reservedIPElement != null) { + Element nameElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element addressElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement != null) { + InetAddress addressInstance; + addressInstance = InetAddress.getByName(addressElement.getTextContent()); + result.setAddress(addressInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setId(idInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + result.setLabel(labelInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + result.setAffinityGroup(affinityGroupInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + result.setState(stateInstance); + } + + Element inUseElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "InUse"); + if (inUseElement != null) { + boolean inUseInstance; + inUseInstance = DatatypeConverter.parseBoolean(inUseElement.getTextContent().toLowerCase()); + result.setInUse(inUseInstance); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + result.setServiceName(serviceNameInstance); + } + + Element deploymentNameElement = XmlUtility.getElementByTagNameNS(reservedIPElement, "http://schemas.microsoft.com/windowsazure", "DeploymentName"); + if (deploymentNameElement != null) { + String deploymentNameInstance; + deploymentNameInstance = deploymentNameElement.getTextContent(); + result.setDeploymentName(deploymentNameInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Preview Only. The List Reserved IP operation retrieves all of the virtual + * IPs reserved for the subscription. + * + * @return Preview Only. The response structure for the Server List + * operation. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public NetworkReservedIPListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * Preview Only. The List Reserved IP operation retrieves all of the virtual + * IPs reserved for the subscription. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Preview Only. The response structure for the Server List + * operation. + */ + @Override + public NetworkReservedIPListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/reservedips"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + NetworkReservedIPListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new NetworkReservedIPListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element reservedIPsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ReservedIPs"); + if (reservedIPsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(reservedIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ReservedIP").size(); i1 = i1 + 1) { + org.w3c.dom.Element reservedIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(reservedIPsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ReservedIP").get(i1)); + NetworkReservedIPListResponse.ReservedIP reservedIPInstance = new NetworkReservedIPListResponse.ReservedIP(); + result.getReservedIPs().add(reservedIPInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + reservedIPInstance.setName(nameInstance); + } + + Element addressElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "Address"); + if (addressElement != null) { + InetAddress addressInstance; + addressInstance = InetAddress.getByName(addressElement.getTextContent()); + reservedIPInstance.setAddress(addressInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + reservedIPInstance.setId(idInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + reservedIPInstance.setLabel(labelInstance); + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + reservedIPInstance.setAffinityGroup(affinityGroupInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + reservedIPInstance.setState(stateInstance); + } + + Element inUseElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "InUse"); + if (inUseElement != null) { + boolean inUseInstance; + inUseInstance = DatatypeConverter.parseBoolean(inUseElement.getTextContent().toLowerCase()); + reservedIPInstance.setInUse(inUseInstance); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + reservedIPInstance.setServiceName(serviceNameInstance); + } + + Element deploymentNameElement = XmlUtility.getElementByTagNameNS(reservedIPsElement, "http://schemas.microsoft.com/windowsazure", "DeploymentName"); + if (deploymentNameElement != null) { + String deploymentNameInstance; + deploymentNameInstance = deploymentNameElement.getTextContent(); + reservedIPInstance.setDeploymentName(deploymentNameInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/StaticIPOperations.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/StaticIPOperations.java new file mode 100644 index 0000000000000..bc696252c1810 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/StaticIPOperations.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.NetworkStaticIPAvailabilityResponse; +import java.io.IOException; +import java.net.InetAddress; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the static IPs +* for your subscription. +*/ +public interface StaticIPOperations { + /** + * The Check Static IP operation retrieves the details for the availability + * of static IP addresses for the given virtual network. + * + * @param networkName Required. The name of the virtual network. + * @param ipAddress Required. The address of the static IP. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A response that indicates the availability of a static IP + * address, and if not, provides a list of suggestions. + */ + NetworkStaticIPAvailabilityResponse check(String networkName, InetAddress ipAddress) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Check Static IP operation retrieves the details for the availability + * of static IP addresses for the given virtual network. + * + * @param networkName Required. The name of the virtual network. + * @param ipAddress Required. The address of the static IP. + * @return A response that indicates the availability of a static IP + * address, and if not, provides a list of suggestions. + */ + Future checkAsync(String networkName, InetAddress ipAddress); +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/StaticIPOperationsImpl.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/StaticIPOperationsImpl.java new file mode 100644 index 0000000000000..da139845f38ef --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/StaticIPOperationsImpl.java @@ -0,0 +1,214 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.network.models.NetworkStaticIPAvailabilityResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Network Management API includes operations for managing the static IPs +* for your subscription. +*/ +public class StaticIPOperationsImpl implements ServiceOperations, StaticIPOperations { + /** + * Initializes a new instance of the StaticIPOperationsImpl class. + * + * @param client Reference to the service client. + */ + StaticIPOperationsImpl(NetworkManagementClientImpl client) { + this.client = client; + } + + private NetworkManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.network.NetworkManagementClientImpl. + * @return The Client value. + */ + public NetworkManagementClientImpl getClient() { + return this.client; + } + + /** + * The Check Static IP operation retrieves the details for the availability + * of static IP addresses for the given virtual network. + * + * @param networkName Required. The name of the virtual network. + * @param ipAddress Required. The address of the static IP. + * @return A response that indicates the availability of a static IP + * address, and if not, provides a list of suggestions. + */ + @Override + public Future checkAsync(final String networkName, final InetAddress ipAddress) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public NetworkStaticIPAvailabilityResponse call() throws Exception { + return check(networkName, ipAddress); + } + }); + } + + /** + * The Check Static IP operation retrieves the details for the availability + * of static IP addresses for the given virtual network. + * + * @param networkName Required. The name of the virtual network. + * @param ipAddress Required. The address of the static IP. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A response that indicates the availability of a static IP + * address, and if not, provides a list of suggestions. + */ + @Override + public NetworkStaticIPAvailabilityResponse check(String networkName, InetAddress ipAddress) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (networkName == null) { + throw new NullPointerException("networkName"); + } + if (ipAddress == null) { + throw new NullPointerException("ipAddress"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("networkName", networkName); + tracingParameters.put("ipAddress", ipAddress); + CloudTracing.enter(invocationId, this, "checkAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/networking/" + networkName.trim() + "?"; + url = url + "op=checkavailability"; + url = url + "&" + "address=" + URLEncoder.encode(ipAddress.getHostAddress(), "UTF-8"); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-11-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + NetworkStaticIPAvailabilityResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new NetworkStaticIPAvailabilityResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element addressAvailabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "AddressAvailabilityResponse"); + if (addressAvailabilityResponseElement != null) { + Element isAvailableElement = XmlUtility.getElementByTagNameNS(addressAvailabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "IsAvailable"); + if (isAvailableElement != null) { + boolean isAvailableInstance; + isAvailableInstance = DatatypeConverter.parseBoolean(isAvailableElement.getTextContent().toLowerCase()); + result.setIsAvailable(isAvailableInstance); + } + + Element availableAddressesSequenceElement = XmlUtility.getElementByTagNameNS(addressAvailabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "AvailableAddresses"); + if (availableAddressesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(availableAddressesSequenceElement, "http://schemas.microsoft.com/windowsazure", "AvailableAddress").size(); i1 = i1 + 1) { + org.w3c.dom.Element availableAddressesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(availableAddressesSequenceElement, "http://schemas.microsoft.com/windowsazure", "AvailableAddress").get(i1)); + result.getAvailableAddresses().add(InetAddress.getByName(availableAddressesElement.getTextContent())); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateCreateParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateCreateParameters.java new file mode 100644 index 0000000000000..e6413550abd8e --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateCreateParameters.java @@ -0,0 +1,46 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +public class ClientRootCertificateCreateParameters { + private String certificate; + + /** + * Required. The new client root certificate to upload, represented as a + * hex-encoded string. + * @return The Certificate value. + */ + public String getCertificate() { + return this.certificate; + } + + /** + * Required. The new client root certificate to upload, represented as a + * hex-encoded string. + * @param certificateValue The Certificate value. + */ + public void setCertificate(final String certificateValue) { + this.certificate = certificateValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateGetResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateGetResponse.java new file mode 100644 index 0000000000000..006069b9e9768 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateGetResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response to the Get Client Root Certificate operation. +*/ +public class ClientRootCertificateGetResponse extends OperationResponse { + private String certificate; + + /** + * Optional. The current client root certificate for the network gateway. + * @return The Certificate value. + */ + public String getCertificate() { + return this.certificate; + } + + /** + * Optional. The current client root certificate for the network gateway. + * @param certificateValue The Certificate value. + */ + public void setCertificate(final String certificateValue) { + this.certificate = certificateValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateListResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateListResponse.java new file mode 100644 index 0000000000000..57b9202f012c7 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ClientRootCertificateListResponse.java @@ -0,0 +1,125 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; + +/** +* The response for the List Client Root Certificates operation. +*/ +public class ClientRootCertificateListResponse extends OperationResponse implements Iterable { + private ArrayList clientRootCertificates; + + /** + * Optional. The list of client root certificates. + * @return The ClientRootCertificates value. + */ + public ArrayList getClientRootCertificates() { + return this.clientRootCertificates; + } + + /** + * Optional. The list of client root certificates. + * @param clientRootCertificatesValue The ClientRootCertificates value. + */ + public void setClientRootCertificates(final ArrayList clientRootCertificatesValue) { + this.clientRootCertificates = clientRootCertificatesValue; + } + + /** + * Initializes a new instance of the ClientRootCertificateListResponse class. + * + */ + public ClientRootCertificateListResponse() { + super(); + this.clientRootCertificates = new ArrayList(); + } + + /** + * Gets the sequence of ClientRootCertificates. + * + */ + public Iterator iterator() { + return this.getClientRootCertificates().iterator(); + } + + public static class ClientRootCertificate { + private Calendar expirationTime; + + /** + * Optional. Specifies the time that the certificate will expire. + * @return The ExpirationTime value. + */ + public Calendar getExpirationTime() { + return this.expirationTime; + } + + /** + * Optional. Specifies the time that the certificate will expire. + * @param expirationTimeValue The ExpirationTime value. + */ + public void setExpirationTime(final Calendar expirationTimeValue) { + this.expirationTime = expirationTimeValue; + } + + private String subject; + + /** + * Optional. Specifies the distinguished name of the certificate issuer. + * @return The Subject value. + */ + public String getSubject() { + return this.subject; + } + + /** + * Optional. Specifies the distinguished name of the certificate issuer. + * @param subjectValue The Subject value. + */ + public void setSubject(final String subjectValue) { + this.subject = subjectValue; + } + + private String thumbprint; + + /** + * Optional. Specifies the thumbprint of the certificate. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. Specifies the thumbprint of the certificate. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectDisconnectOrTestParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectDisconnectOrTestParameters.java new file mode 100644 index 0000000000000..bcc7a4cea757e --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectDisconnectOrTestParameters.java @@ -0,0 +1,77 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import java.net.InetAddress; + +/** +* The parameters for the Connect, Disconnect, or Test request +*/ +public class GatewayConnectDisconnectOrTestParameters { + private InetAddress iPAddress; + + /** + * Optional. Required if operation is set to Test; otherwise not used. + * Specifies the IP address of the target local network site with which the + * gateway will test connectivity. + * @return The IPAddress value. + */ + public InetAddress getIPAddress() { + return this.iPAddress; + } + + /** + * Optional. Required if operation is set to Test; otherwise not used. + * Specifies the IP address of the target local network site with which the + * gateway will test connectivity. + * @param iPAddressValue The IPAddress value. + */ + public void setIPAddress(final InetAddress iPAddressValue) { + this.iPAddress = iPAddressValue; + } + + private GatewayConnectionUpdateOperation operation; + + /** + * Required. Specifies the operation to perform on the connection. Can be + * set to Connect, Disconnect, or Test to connect to a local network, + * disconnect from a local network, or test the gateway's connection to a + * local network site. + * @return The Operation value. + */ + public GatewayConnectionUpdateOperation getOperation() { + return this.operation; + } + + /** + * Required. Specifies the operation to perform on the connection. Can be + * set to Connect, Disconnect, or Test to connect to a local network, + * disconnect from a local network, or test the gateway's connection to a + * local network site. + * @param operationValue The Operation value. + */ + public void setOperation(final GatewayConnectionUpdateOperation operationValue) { + this.operation = operationValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectionUpdateOperation.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectionUpdateOperation.java new file mode 100644 index 0000000000000..f18082e0da8c0 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectionUpdateOperation.java @@ -0,0 +1,37 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Specifies the operation to perform on the connection. Can be set to Connect, +* Disconnect, or Test to connect to a local network, disconnect from a local +* network, or test the gateway's connection to a local network site. +*/ +public enum GatewayConnectionUpdateOperation { + Connect, + + Disconnect, + + Test, +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectivityState.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectivityState.java new file mode 100644 index 0000000000000..017ef6c31ea11 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayConnectivityState.java @@ -0,0 +1,34 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +public enum GatewayConnectivityState { + Connected, + + Connecting, + + NotConnected, + + Unknown, +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayCreateParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayCreateParameters.java new file mode 100644 index 0000000000000..74f40a45c438b --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayCreateParameters.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Parameters supplied to the Create Virtual Network Gateway operation. +*/ +public class GatewayCreateParameters { + private GatewayType gatewayType; + + /** + * Optional. The routing type for this virtual network gateway. + * @return The GatewayType value. + */ + public GatewayType getGatewayType() { + return this.gatewayType; + } + + /** + * Optional. The routing type for this virtual network gateway. + * @param gatewayTypeValue The GatewayType value. + */ + public void setGatewayType(final GatewayType gatewayTypeValue) { + this.gatewayType = gatewayTypeValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayEvent.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayEvent.java new file mode 100644 index 0000000000000..5d10dc3db0f29 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayEvent.java @@ -0,0 +1,103 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import java.util.Calendar; + +/** +* A management event for the virtual network gateway. +*/ +public class GatewayEvent { + private String data; + + /** + * Optional. Additional data associated with this event. + * @return The Data value. + */ + public String getData() { + return this.data; + } + + /** + * Optional. Additional data associated with this event. + * @param dataValue The Data value. + */ + public void setData(final String dataValue) { + this.data = dataValue; + } + + private String id; + + /** + * Optional. The event ID. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. The event ID. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private String message; + + /** + * Optional. The event message. + * @return The Message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Optional. The event message. + * @param messageValue The Message value. + */ + public void setMessage(final String messageValue) { + this.message = messageValue; + } + + private Calendar timestamp; + + /** + * Optional. The date and time when the event occurred. + * @return The Timestamp value. + */ + public Calendar getTimestamp() { + return this.timestamp; + } + + /** + * Optional. The date and time when the event occurred. + * @param timestampValue The Timestamp value. + */ + public void setTimestamp(final Calendar timestampValue) { + this.timestamp = timestampValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGenerateVpnClientPackageParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGenerateVpnClientPackageParameters.java new file mode 100644 index 0000000000000..3a8169326ba73 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGenerateVpnClientPackageParameters.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* The parameters to the Generate VPN Client Package request. +*/ +public class GatewayGenerateVpnClientPackageParameters { + private GatewayProcessorArchitecture processorArchitecture; + + /** + * Required. The client processor architecture. + * @return The ProcessorArchitecture value. + */ + public GatewayProcessorArchitecture getProcessorArchitecture() { + return this.processorArchitecture; + } + + /** + * Required. The client processor architecture. + * @param processorArchitectureValue The ProcessorArchitecture value. + */ + public void setProcessorArchitecture(final GatewayProcessorArchitecture processorArchitectureValue) { + this.processorArchitecture = processorArchitectureValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetDeviceConfigurationScriptParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetDeviceConfigurationScriptParameters.java new file mode 100644 index 0000000000000..8f1f2c713b8e6 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetDeviceConfigurationScriptParameters.java @@ -0,0 +1,84 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* The vendor, platform, and OS family of the requested device configuration +* script. +*/ +public class GatewayGetDeviceConfigurationScriptParameters { + private String oSFamily; + + /** + * Optional. The device OS family. + * @return The OSFamily value. + */ + public String getOSFamily() { + return this.oSFamily; + } + + /** + * Optional. The device OS family. + * @param oSFamilyValue The OSFamily value. + */ + public void setOSFamily(final String oSFamilyValue) { + this.oSFamily = oSFamilyValue; + } + + private String platform; + + /** + * Optional. The device platform. + * @return The Platform value. + */ + public String getPlatform() { + return this.platform; + } + + /** + * Optional. The device platform. + * @param platformValue The Platform value. + */ + public void setPlatform(final String platformValue) { + this.platform = platformValue; + } + + private String vendor; + + /** + * Optional. The name of the device vendor. + * @return The Vendor value. + */ + public String getVendor() { + return this.vendor; + } + + /** + * Optional. The name of the device vendor. + * @param vendorValue The Vendor value. + */ + public void setVendor(final String vendorValue) { + this.vendor = vendorValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetDeviceConfigurationScriptResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetDeviceConfigurationScriptResponse.java new file mode 100644 index 0000000000000..7d57ed87f68f6 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetDeviceConfigurationScriptResponse.java @@ -0,0 +1,50 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The configuration script returned from the get device configuration script +* operation. +*/ +public class GatewayGetDeviceConfigurationScriptResponse extends OperationResponse { + private String configurationScript; + + /** + * Optional. The requested configuration script for the local network device. + * @return The ConfigurationScript value. + */ + public String getConfigurationScript() { + return this.configurationScript; + } + + /** + * Optional. The requested configuration script for the local network device. + * @param configurationScriptValue The ConfigurationScript value. + */ + public void setConfigurationScript(final String configurationScriptValue) { + this.configurationScript = configurationScriptValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetOperationStatusResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetOperationStatusResponse.java new file mode 100644 index 0000000000000..12be25d027e6b --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetOperationStatusResponse.java @@ -0,0 +1,165 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The response body contains the status of the specified asynchronous +* operation, indicating whether it has succeeded, is in progress, or has +* failed. Note that this status is distinct from the HTTP status code returned +* for the Get Operation Status operation itself. If the asynchronous operation +* succeeded, the response body includes the HTTP status code for the +* successful request. If the asynchronous operation failed, the response body +* includes the HTTP status code for the failed request, and also includes +* error information regarding the failure. +*/ +public class GatewayGetOperationStatusResponse extends OperationResponse { + private GatewayGetOperationStatusResponse.ErrorDetails error; + + /** + * Optional. If the asynchronous operation failed, the response body + * includes the HTTP status code for the failed request, and also includes + * error information regarding the failure. + * @return The Error value. + */ + public GatewayGetOperationStatusResponse.ErrorDetails getError() { + return this.error; + } + + /** + * Optional. If the asynchronous operation failed, the response body + * includes the HTTP status code for the failed request, and also includes + * error information regarding the failure. + * @param errorValue The Error value. + */ + public void setError(final GatewayGetOperationStatusResponse.ErrorDetails errorValue) { + this.error = errorValue; + } + + private Integer httpStatusCode; + + /** + * Optional. The HTTP status code for the asynchronous request. + * @return The HttpStatusCode value. + */ + public Integer getHttpStatusCode() { + return this.httpStatusCode; + } + + /** + * Optional. The HTTP status code for the asynchronous request. + * @param httpStatusCodeValue The HttpStatusCode value. + */ + public void setHttpStatusCode(final Integer httpStatusCodeValue) { + this.httpStatusCode = httpStatusCodeValue; + } + + private String id; + + /** + * Optional. The request ID of the asynchronous request. This value is + * returned in the x-ms-request-id response header of the asynchronous + * request. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. The request ID of the asynchronous request. This value is + * returned in the x-ms-request-id response header of the asynchronous + * request. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private GatewayOperationStatus status; + + /** + * Optional. The status of the asynchronous request. + * @return The Status value. + */ + public GatewayOperationStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the asynchronous request. + * @param statusValue The Status value. + */ + public void setStatus(final GatewayOperationStatus statusValue) { + this.status = statusValue; + } + + /** + * If the asynchronous operation failed, the response body includes the HTTP + * status code for the failed request, and also includes error information + * regarding the failure. + */ + public static class ErrorDetails { + private String code; + + /** + * Optional. The management service error code returned if the + * asynchronous request failed. + * @return The Code value. + */ + public String getCode() { + return this.code; + } + + /** + * Optional. The management service error code returned if the + * asynchronous request failed. + * @param codeValue The Code value. + */ + public void setCode(final String codeValue) { + this.code = codeValue; + } + + private String message; + + /** + * Optional. The management service error message returned if the + * asynchronous request failed. + * @return The Message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Optional. The management service error message returned if the + * asynchronous request failed. + * @param messageValue The Message value. + */ + public void setMessage(final String messageValue) { + this.message = messageValue; + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetResponse.java new file mode 100644 index 0000000000000..f6456a9ce82b2 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetResponse.java @@ -0,0 +1,104 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.InetAddress; + +/** +* A standard storage response including an HTTP status code and request ID. +*/ +public class GatewayGetResponse extends OperationResponse { + private GatewayType gatewayType; + + /** + * Optional. The type of gateway routing used for this virtual network. + * @return The GatewayType value. + */ + public GatewayType getGatewayType() { + return this.gatewayType; + } + + /** + * Optional. The type of gateway routing used for this virtual network. + * @param gatewayTypeValue The GatewayType value. + */ + public void setGatewayType(final GatewayType gatewayTypeValue) { + this.gatewayType = gatewayTypeValue; + } + + private GatewayEvent lastEvent; + + /** + * Optional. The last recorded event for this virtual network gateway. + * @return The LastEvent value. + */ + public GatewayEvent getLastEvent() { + return this.lastEvent; + } + + /** + * Optional. The last recorded event for this virtual network gateway. + * @param lastEventValue The LastEvent value. + */ + public void setLastEvent(final GatewayEvent lastEventValue) { + this.lastEvent = lastEventValue; + } + + private String state; + + /** + * Optional. The provisioning state of the virtual network gateway. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. The provisioning state of the virtual network gateway. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private InetAddress vipAddress; + + /** + * Optional. The virtual IP address for this virtual network gateway. + * @return The VipAddress value. + */ + public InetAddress getVipAddress() { + return this.vipAddress; + } + + /** + * Optional. The virtual IP address for this virtual network gateway. + * @param vipAddressValue The VipAddress value. + */ + public void setVipAddress(final InetAddress vipAddressValue) { + this.vipAddress = vipAddressValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetSharedKeyResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetSharedKeyResponse.java new file mode 100644 index 0000000000000..9105c9b920f2d --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayGetSharedKeyResponse.java @@ -0,0 +1,51 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The response to the get shared key request. +*/ +public class GatewayGetSharedKeyResponse extends OperationResponse { + private String sharedKey; + + /** + * Optional. Contains the shared key used by the gateway to authenticate + * connections to sites on a virtual network. + * @return The SharedKey value. + */ + public String getSharedKey() { + return this.sharedKey; + } + + /** + * Optional. Contains the shared key used by the gateway to authenticate + * connections to sites on a virtual network. + * @param sharedKeyValue The SharedKey value. + */ + public void setSharedKey(final String sharedKeyValue) { + this.sharedKey = sharedKeyValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayListConnectionsResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayListConnectionsResponse.java new file mode 100644 index 0000000000000..7c6eb8e855597 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayListConnectionsResponse.java @@ -0,0 +1,218 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; + +/** +* The response to a ListConnections request to a Virtual Network Gateway. +*/ +public class GatewayListConnectionsResponse extends OperationResponse implements Iterable { + private ArrayList connections; + + /** + * Optional. The list of connections. + * @return The Connections value. + */ + public ArrayList getConnections() { + return this.connections; + } + + /** + * Optional. The list of connections. + * @param connectionsValue The Connections value. + */ + public void setConnections(final ArrayList connectionsValue) { + this.connections = connectionsValue; + } + + /** + * Initializes a new instance of the GatewayListConnectionsResponse class. + * + */ + public GatewayListConnectionsResponse() { + super(); + this.connections = new ArrayList(); + } + + /** + * Gets the sequence of Connections. + * + */ + public Iterator iterator() { + return this.getConnections().iterator(); + } + + public static class GatewayConnection { + private ArrayList allocatedIPAddresses; + + /** + * Optional. If LocalNetworkSiteName is defined as VPNClientConnection, + * this element contains a list of IP addresses (represented as + * strings) that are assigned to currently connected VPN clients. + * @return The AllocatedIPAddresses value. + */ + public ArrayList getAllocatedIPAddresses() { + return this.allocatedIPAddresses; + } + + /** + * Optional. If LocalNetworkSiteName is defined as VPNClientConnection, + * this element contains a list of IP addresses (represented as + * strings) that are assigned to currently connected VPN clients. + * @param allocatedIPAddressesValue The AllocatedIPAddresses value. + */ + public void setAllocatedIPAddresses(final ArrayList allocatedIPAddressesValue) { + this.allocatedIPAddresses = allocatedIPAddressesValue; + } + + private GatewayConnectivityState connectivityState; + + /** + * Optional. The connection state of the site. You can set the + * connection state to Connected, Connecting, or NotConnected. + * @return The ConnectivityState value. + */ + public GatewayConnectivityState getConnectivityState() { + return this.connectivityState; + } + + /** + * Optional. The connection state of the site. You can set the + * connection state to Connected, Connecting, or NotConnected. + * @param connectivityStateValue The ConnectivityState value. + */ + public void setConnectivityState(final GatewayConnectivityState connectivityStateValue) { + this.connectivityState = connectivityStateValue; + } + + private long egressBytesTransferred; + + /** + * Optional. The number of bytes of data transferred out through this + * connection since it was started. + * @return The EgressBytesTransferred value. + */ + public long getEgressBytesTransferred() { + return this.egressBytesTransferred; + } + + /** + * Optional. The number of bytes of data transferred out through this + * connection since it was started. + * @param egressBytesTransferredValue The EgressBytesTransferred value. + */ + public void setEgressBytesTransferred(final long egressBytesTransferredValue) { + this.egressBytesTransferred = egressBytesTransferredValue; + } + + private long ingressBytesTransferred; + + /** + * Optional. The number of bytes of data transferred in through this + * connection since it was started. + * @return The IngressBytesTransferred value. + */ + public long getIngressBytesTransferred() { + return this.ingressBytesTransferred; + } + + /** + * Optional. The number of bytes of data transferred in through this + * connection since it was started. + * @param ingressBytesTransferredValue The IngressBytesTransferred value. + */ + public void setIngressBytesTransferred(final long ingressBytesTransferredValue) { + this.ingressBytesTransferred = ingressBytesTransferredValue; + } + + private Calendar lastConnectionEstablished; + + /** + * Optional. The time that the last connection was established. + * @return The LastConnectionEstablished value. + */ + public Calendar getLastConnectionEstablished() { + return this.lastConnectionEstablished; + } + + /** + * Optional. The time that the last connection was established. + * @param lastConnectionEstablishedValue The LastConnectionEstablished + * value. + */ + public void setLastConnectionEstablished(final Calendar lastConnectionEstablishedValue) { + this.lastConnectionEstablished = lastConnectionEstablishedValue; + } + + private GatewayEvent lastEvent; + + /** + * Optional. A record of the last provisioning event for this connection. + * @return The LastEvent value. + */ + public GatewayEvent getLastEvent() { + return this.lastEvent; + } + + /** + * Optional. A record of the last provisioning event for this connection. + * @param lastEventValue The LastEvent value. + */ + public void setLastEvent(final GatewayEvent lastEventValue) { + this.lastEvent = lastEventValue; + } + + private String localNetworkSiteName; + + /** + * Optional. The name of the local network site represented by the + * connection. + * @return The LocalNetworkSiteName value. + */ + public String getLocalNetworkSiteName() { + return this.localNetworkSiteName; + } + + /** + * Optional. The name of the local network site represented by the + * connection. + * @param localNetworkSiteNameValue The LocalNetworkSiteName value. + */ + public void setLocalNetworkSiteName(final String localNetworkSiteNameValue) { + this.localNetworkSiteName = localNetworkSiteNameValue; + } + + /** + * Initializes a new instance of the GatewayConnection class. + * + */ + public GatewayConnection() { + this.allocatedIPAddresses = new ArrayList(); + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayListSupportedDevicesResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayListSupportedDevicesResponse.java new file mode 100644 index 0000000000000..e0e33ddf773f3 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayListSupportedDevicesResponse.java @@ -0,0 +1,196 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; + +/** +* The response to the list supported devices request. +*/ +public class GatewayListSupportedDevicesResponse extends OperationResponse { + private ArrayList vendors; + + /** + * Optional. The set of supported vendors. + * @return The Vendors value. + */ + public ArrayList getVendors() { + return this.vendors; + } + + /** + * Optional. The set of supported vendors. + * @param vendorsValue The Vendors value. + */ + public void setVendors(final ArrayList vendorsValue) { + this.vendors = vendorsValue; + } + + private String version; + + /** + * Optional. The version for this device configuration list. + * @return The Version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Optional. The version for this device configuration list. + * @param versionValue The Version value. + */ + public void setVersion(final String versionValue) { + this.version = versionValue; + } + + /** + * Initializes a new instance of the GatewayListSupportedDevicesResponse + * class. + * + */ + public GatewayListSupportedDevicesResponse() { + super(); + this.vendors = new ArrayList(); + } + + public static class OSFamily { + private String name; + + /** + * Optional. The name of the OS family. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the OS family. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + } + + /** + * The name and supported OS families for this vendor on the platform. + */ + public static class Platform { + private String name; + + /** + * Optional. The platform name. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The platform name. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private ArrayList oSFamilies; + + /** + * Optional. The supported OS families for this platform. + * @return The OSFamilies value. + */ + public ArrayList getOSFamilies() { + return this.oSFamilies; + } + + /** + * Optional. The supported OS families for this platform. + * @param oSFamiliesValue The OSFamilies value. + */ + public void setOSFamilies(final ArrayList oSFamiliesValue) { + this.oSFamilies = oSFamiliesValue; + } + + /** + * Initializes a new instance of the Platform class. + * + */ + public Platform() { + this.oSFamilies = new ArrayList(); + } + } + + /** + * The name and supported platforms for the vendor. + */ + public static class Vendor { + private String name; + + /** + * Optional. The vendor name. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The vendor name. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private ArrayList platforms; + + /** + * Optional. The supported platforms for the vendor. + * @return The Platforms value. + */ + public ArrayList getPlatforms() { + return this.platforms; + } + + /** + * Optional. The supported platforms for the vendor. + * @param platformsValue The Platforms value. + */ + public void setPlatforms(final ArrayList platformsValue) { + this.platforms = platformsValue; + } + + /** + * Initializes a new instance of the Vendor class. + * + */ + public Vendor() { + this.platforms = new ArrayList(); + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayOperationResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayOperationResponse.java new file mode 100644 index 0000000000000..6633ea0b335ff --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayOperationResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* A standard storage response including an HTTP status code and request ID. +*/ +public class GatewayOperationResponse extends OperationResponse { + private String operationId; + + /** + * Optional. + * @return The OperationId value. + */ + public String getOperationId() { + return this.operationId; + } + + /** + * Optional. + * @param operationIdValue The OperationId value. + */ + public void setOperationId(final String operationIdValue) { + this.operationId = operationIdValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayOperationStatus.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayOperationStatus.java new file mode 100644 index 0000000000000..5043234e3f2a5 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayOperationStatus.java @@ -0,0 +1,44 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* The status of the asynchronous request. +*/ +public enum GatewayOperationStatus { + /** + * The asynchronous request is in progress. + */ + InProgress, + + /** + * The asynchronous request succeeded. + */ + Successful, + + /** + * The asynchronous request failed. + */ + Failed, +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProcessorArchitecture.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProcessorArchitecture.java new file mode 100644 index 0000000000000..68b3f79af9ec3 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProcessorArchitecture.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* The processor architecture for the generated VPN client package. +*/ +public enum GatewayProcessorArchitecture { + Amd64, + + X86, +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProfile.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProfile.java new file mode 100644 index 0000000000000..3cdf02a510e36 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProfile.java @@ -0,0 +1,37 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Possible values for the Gateway Profile. +*/ +public enum GatewayProfile { + Small, + + Medium, + + Large, + + ExtraLarge, +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProvisioningEventStates.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProvisioningEventStates.java new file mode 100644 index 0000000000000..435800efdacea --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayProvisioningEventStates.java @@ -0,0 +1,37 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Standard states for Virtual Network Gateway Provisioning Events. +*/ +public abstract class GatewayProvisioningEventStates { + public static final String NOTPROVISIONED = "NotProvisioned"; + + public static final String DEPROVISIONING = "Deprovisioning"; + + public static final String PROVISIONING = "Provisioning"; + + public static final String PROVISIONED = "Provisioned"; +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayResetSharedKeyParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayResetSharedKeyParameters.java new file mode 100644 index 0000000000000..b6699327ad336 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayResetSharedKeyParameters.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* The length of shared key to generate. +*/ +public class GatewayResetSharedKeyParameters { + private int keyLength; + + /** + * Optional. The number of bytes in the shared key. Minimum is 1 and maximum + * is 128 + * @return The KeyLength value. + */ + public int getKeyLength() { + return this.keyLength; + } + + /** + * Optional. The number of bytes in the shared key. Minimum is 1 and maximum + * is 128 + * @param keyLengthValue The KeyLength value. + */ + public void setKeyLength(final int keyLengthValue) { + this.keyLength = keyLengthValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayType.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayType.java new file mode 100644 index 0000000000000..66fb02ae23a53 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/GatewayType.java @@ -0,0 +1,30 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +public enum GatewayType { + StaticRouting, + + DynamicRouting, +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/LocalNetworkConnectionType.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/LocalNetworkConnectionType.java new file mode 100644 index 0000000000000..0db06e83eb417 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/LocalNetworkConnectionType.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Possible values for the Local Network Connection Type. +*/ +public enum LocalNetworkConnectionType { + IPSecurity, + + Dedicated, +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkGetConfigurationResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkGetConfigurationResponse.java new file mode 100644 index 0000000000000..208688d99e132 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkGetConfigurationResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Network Configuration operation response. +*/ +public class NetworkGetConfigurationResponse extends OperationResponse { + private String configuration; + + /** + * Required. The network configuration for this subscription. + * @return The Configuration value. + */ + public String getConfiguration() { + return this.configuration; + } + + /** + * Required. The network configuration for this subscription. + * @param configurationValue The Configuration value. + */ + public void setConfiguration(final String configurationValue) { + this.configuration = configurationValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkListResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkListResponse.java new file mode 100644 index 0000000000000..e6a4566dec142 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkListResponse.java @@ -0,0 +1,589 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The response structure for the Network Operations List operation. +*/ +public class NetworkListResponse extends OperationResponse implements Iterable { + private ArrayList virtualNetworkSites; + + /** + * Optional. + * @return The VirtualNetworkSites value. + */ + public ArrayList getVirtualNetworkSites() { + return this.virtualNetworkSites; + } + + /** + * Optional. + * @param virtualNetworkSitesValue The VirtualNetworkSites value. + */ + public void setVirtualNetworkSites(final ArrayList virtualNetworkSitesValue) { + this.virtualNetworkSites = virtualNetworkSitesValue; + } + + /** + * Initializes a new instance of the NetworkListResponse class. + * + */ + public NetworkListResponse() { + super(); + this.virtualNetworkSites = new ArrayList(); + } + + /** + * Gets the sequence of VirtualNetworkSites. + * + */ + public Iterator iterator() { + return this.getVirtualNetworkSites().iterator(); + } + + public static class AddressSpace { + private ArrayList addressPrefixes; + + /** + * Optional. Address spaces, in CIDR format in the virtual network. + * @return The AddressPrefixes value. + */ + public ArrayList getAddressPrefixes() { + return this.addressPrefixes; + } + + /** + * Optional. Address spaces, in CIDR format in the virtual network. + * @param addressPrefixesValue The AddressPrefixes value. + */ + public void setAddressPrefixes(final ArrayList addressPrefixesValue) { + this.addressPrefixes = addressPrefixesValue; + } + + /** + * Initializes a new instance of the AddressSpace class. + * + */ + public AddressSpace() { + this.addressPrefixes = new ArrayList(); + } + } + + /** + * Specifies the type of connection of the local network site. The value of + * this element can be either IPsec or Dedicated. The default value is + * IPsec. + */ + public static class Connection { + private LocalNetworkConnectionType type; + + /** + * Optional. + * @return The Type value. + */ + public LocalNetworkConnectionType getType() { + return this.type; + } + + /** + * Optional. + * @param typeValue The Type value. + */ + public void setType(final LocalNetworkConnectionType typeValue) { + this.type = typeValue; + } + } + + public static class DnsServer { + private InetAddress address; + + /** + * Optional. The IPv4 address of the DNS server. + * @return The Address value. + */ + public InetAddress getAddress() { + return this.address; + } + + /** + * Optional. The IPv4 address of the DNS server. + * @param addressValue The Address value. + */ + public void setAddress(final InetAddress addressValue) { + this.address = addressValue; + } + + private String name; + + /** + * Optional. The name of the DNS server. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the DNS server. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + } + + /** + * Contains gateway references to the local network sites that the virtual + * network can connect to. + */ + public static class Gateway { + private GatewayProfile profile; + + /** + * Optional. The gateway connection size. + * @return The Profile value. + */ + public GatewayProfile getProfile() { + return this.profile; + } + + /** + * Optional. The gateway connection size. + * @param profileValue The Profile value. + */ + public void setProfile(final GatewayProfile profileValue) { + this.profile = profileValue; + } + + private ArrayList sites; + + /** + * Optional. The list of local network sites that the virtual network + * can connect to. + * @return The Sites value. + */ + public ArrayList getSites() { + return this.sites; + } + + /** + * Optional. The list of local network sites that the virtual network + * can connect to. + * @param sitesValue The Sites value. + */ + public void setSites(final ArrayList sitesValue) { + this.sites = sitesValue; + } + + private NetworkListResponse.VPNClientAddressPool vPNClientAddressPool; + + /** + * Optional. The VPN Client Address Pool reserves a pool of IP addresses + * for VPN clients. This object is used for point-to-site connectivity. + * @return The VPNClientAddressPool value. + */ + public NetworkListResponse.VPNClientAddressPool getVPNClientAddressPool() { + return this.vPNClientAddressPool; + } + + /** + * Optional. The VPN Client Address Pool reserves a pool of IP addresses + * for VPN clients. This object is used for point-to-site connectivity. + * @param vPNClientAddressPoolValue The VPNClientAddressPool value. + */ + public void setVPNClientAddressPool(final NetworkListResponse.VPNClientAddressPool vPNClientAddressPoolValue) { + this.vPNClientAddressPool = vPNClientAddressPoolValue; + } + + /** + * Initializes a new instance of the Gateway class. + * + */ + public Gateway() { + this.sites = new ArrayList(); + } + } + + /** + * Contains the list of parameters defining the local network site. + */ + public static class LocalNetworkSite { + private NetworkListResponse.AddressSpace addressSpace; + + /** + * Optional. The address space of the local network site. + * @return The AddressSpace value. + */ + public NetworkListResponse.AddressSpace getAddressSpace() { + return this.addressSpace; + } + + /** + * Optional. The address space of the local network site. + * @param addressSpaceValue The AddressSpace value. + */ + public void setAddressSpace(final NetworkListResponse.AddressSpace addressSpaceValue) { + this.addressSpace = addressSpaceValue; + } + + private ArrayList connections; + + /** + * Optional. Specifies the types of connections to the local network + * site. + * @return The Connections value. + */ + public ArrayList getConnections() { + return this.connections; + } + + /** + * Optional. Specifies the types of connections to the local network + * site. + * @param connectionsValue The Connections value. + */ + public void setConnections(final ArrayList connectionsValue) { + this.connections = connectionsValue; + } + + private String name; + + /** + * Optional. The name of the local network site. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the local network site. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private InetAddress vpnGatewayAddress; + + /** + * Optional. The IPv4 address of the local network site. + * @return The VpnGatewayAddress value. + */ + public InetAddress getVpnGatewayAddress() { + return this.vpnGatewayAddress; + } + + /** + * Optional. The IPv4 address of the local network site. + * @param vpnGatewayAddressValue The VpnGatewayAddress value. + */ + public void setVpnGatewayAddress(final InetAddress vpnGatewayAddressValue) { + this.vpnGatewayAddress = vpnGatewayAddressValue; + } + + /** + * Initializes a new instance of the LocalNetworkSite class. + * + */ + public LocalNetworkSite() { + this.connections = new ArrayList(); + } + } + + public static class Subnet { + private String addressPrefix; + + /** + * Optional. Represents an address space, in CIDR format that defines + * the subnet. + * @return The AddressPrefix value. + */ + public String getAddressPrefix() { + return this.addressPrefix; + } + + /** + * Optional. Represents an address space, in CIDR format that defines + * the subnet. + * @param addressPrefixValue The AddressPrefix value. + */ + public void setAddressPrefix(final String addressPrefixValue) { + this.addressPrefix = addressPrefixValue; + } + + private String name; + + /** + * Optional. Name of the subnet. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Name of the subnet. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + } + + /** + * Contains the collections of parameters used to configure a virtual + * network space that is dedicated to your subscription without overlapping + * with other networks + */ + public static class VirtualNetworkSite { + private NetworkListResponse.AddressSpace addressSpace; + + /** + * Optional. The list of network address spaces for a virtual network + * site. This represents the overall network space contained within the + * virtual network site. + * @return The AddressSpace value. + */ + public NetworkListResponse.AddressSpace getAddressSpace() { + return this.addressSpace; + } + + /** + * Optional. The list of network address spaces for a virtual network + * site. This represents the overall network space contained within the + * virtual network site. + * @param addressSpaceValue The AddressSpace value. + */ + public void setAddressSpace(final NetworkListResponse.AddressSpace addressSpaceValue) { + this.addressSpace = addressSpaceValue; + } + + private String affinityGroup; + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private ArrayList dnsServers; + + /** + * Optional. The list of available DNS Servers associated with the + * virtual network site. + * @return The DnsServers value. + */ + public ArrayList getDnsServers() { + return this.dnsServers; + } + + /** + * Optional. The list of available DNS Servers associated with the + * virtual network site. + * @param dnsServersValue The DnsServers value. + */ + public void setDnsServers(final ArrayList dnsServersValue) { + this.dnsServers = dnsServersValue; + } + + private NetworkListResponse.Gateway gateway; + + /** + * Optional. The gateway that contains a list of Local Network Sites + * which enable the Virtual Network Site to communicate with a + * customer's on-premise networks. + * @return The Gateway value. + */ + public NetworkListResponse.Gateway getGateway() { + return this.gateway; + } + + /** + * Optional. The gateway that contains a list of Local Network Sites + * which enable the Virtual Network Site to communicate with a + * customer's on-premise networks. + * @param gatewayValue The Gateway value. + */ + public void setGateway(final NetworkListResponse.Gateway gatewayValue) { + this.gateway = gatewayValue; + } + + private String id; + + /** + * Optional. A unique string identifier that represents the virtual + * network site. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. A unique string identifier that represents the virtual + * network site. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private String label; + + /** + * Optional. The friendly identifier for the site. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly identifier for the site. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Optional. Name of the virtual network site. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Name of the virtual network site. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String state; + + /** + * Optional. Current status of the virtual network. (Created, Creating, + * Updating, Deleting, or Unavailable.) + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Current status of the virtual network. (Created, Creating, + * Updating, Deleting, or Unavailable.) + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private ArrayList subnets; + + /** + * Optional. The list of network subnets for a virtual network site. All + * network subnets must be contained within the overall virtual network + * address spaces. + * @return The Subnets value. + */ + public ArrayList getSubnets() { + return this.subnets; + } + + /** + * Optional. The list of network subnets for a virtual network site. All + * network subnets must be contained within the overall virtual network + * address spaces. + * @param subnetsValue The Subnets value. + */ + public void setSubnets(final ArrayList subnetsValue) { + this.subnets = subnetsValue; + } + + /** + * Initializes a new instance of the VirtualNetworkSite class. + * + */ + public VirtualNetworkSite() { + this.dnsServers = new ArrayList(); + this.subnets = new ArrayList(); + } + } + + /** + * The VPN Client Address Pool reserves a pool of IP addresses for VPN + * clients. This object is used for point-to-site connectivity. + */ + public static class VPNClientAddressPool { + private ArrayList addressPrefixes; + + /** + * Optional. The CIDR identifiers that identify addresses in the pool. + * @return The AddressPrefixes value. + */ + public ArrayList getAddressPrefixes() { + return this.addressPrefixes; + } + + /** + * Optional. The CIDR identifiers that identify addresses in the pool. + * @param addressPrefixesValue The AddressPrefixes value. + */ + public void setAddressPrefixes(final ArrayList addressPrefixesValue) { + this.addressPrefixes = addressPrefixesValue; + } + + /** + * Initializes a new instance of the VPNClientAddressPool class. + * + */ + public VPNClientAddressPool() { + this.addressPrefixes = new ArrayList(); + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPCreateParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPCreateParameters.java new file mode 100644 index 0000000000000..c336922d2c6dd --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPCreateParameters.java @@ -0,0 +1,121 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Preview Only. Parameters supplied to the Create Reserved IP operation. +*/ +public class NetworkReservedIPCreateParameters { + private String affinityGroup; + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String deploymentName; + + /** + * Optional. The name of the deployment the IP belongs to, if used. + * @return The DeploymentName value. + */ + public String getDeploymentName() { + return this.deploymentName; + } + + /** + * Optional. The name of the deployment the IP belongs to, if used. + * @param deploymentNameValue The DeploymentName value. + */ + public void setDeploymentName(final String deploymentNameValue) { + this.deploymentName = deploymentNameValue; + } + + private String label; + + /** + * Optional. The friendly identifier for the site. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly identifier for the site. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Optional. Name of the reserved IP. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Name of the reserved IP. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String serviceName; + + /** + * Optional. The name of the service the IP belongs to, if used. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The name of the service the IP belongs to, if used. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPGetResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPGetResponse.java new file mode 100644 index 0000000000000..30012b3bf23a7 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPGetResponse.java @@ -0,0 +1,198 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.InetAddress; + +/** +* Preview Only. A reserved IP associated with your subscription. +*/ +public class NetworkReservedIPGetResponse extends OperationResponse { + private InetAddress address; + + /** + * Optional. The IP address of the reserved IP. + * @return The Address value. + */ + public InetAddress getAddress() { + return this.address; + } + + /** + * Optional. The IP address of the reserved IP. + * @param addressValue The Address value. + */ + public void setAddress(final InetAddress addressValue) { + this.address = addressValue; + } + + private String affinityGroup; + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String deploymentName; + + /** + * Optional. The name of the deployment the IP belongs to, if used. + * @return The DeploymentName value. + */ + public String getDeploymentName() { + return this.deploymentName; + } + + /** + * Optional. The name of the deployment the IP belongs to, if used. + * @param deploymentNameValue The DeploymentName value. + */ + public void setDeploymentName(final String deploymentNameValue) { + this.deploymentName = deploymentNameValue; + } + + private String id; + + /** + * Optional. A unique string identifier that represents the reserved IP. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. A unique string identifier that represents the reserved IP. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private boolean inUse; + + /** + * Optional. The indicator of whether the reserved IP is used. + * @return The InUse value. + */ + public boolean isInUse() { + return this.inUse; + } + + /** + * Optional. The indicator of whether the reserved IP is used. + * @param inUseValue The InUse value. + */ + public void setInUse(final boolean inUseValue) { + this.inUse = inUseValue; + } + + private String label; + + /** + * Optional. The friendly identifier of the site. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly identifier of the site. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Optional. Name of the reserved IP. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Name of the reserved IP. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String serviceName; + + /** + * Optional. The name of the service the IP belongs to, if used. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The name of the service the IP belongs to, if used. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private String state; + + /** + * Optional. Current status of the reserved IP. (Created, Creating, + * Updating, Deleting, or Unavailable.) + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Current status of the reserved IP. (Created, Creating, + * Updating, Deleting, or Unavailable.) + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPListResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPListResponse.java new file mode 100644 index 0000000000000..d63f1189be2c3 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkReservedIPListResponse.java @@ -0,0 +1,240 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* Preview Only. The response structure for the Server List operation. +*/ +public class NetworkReservedIPListResponse extends OperationResponse implements Iterable { + private ArrayList reservedIPs; + + /** + * Optional. + * @return The ReservedIPs value. + */ + public ArrayList getReservedIPs() { + return this.reservedIPs; + } + + /** + * Optional. + * @param reservedIPsValue The ReservedIPs value. + */ + public void setReservedIPs(final ArrayList reservedIPsValue) { + this.reservedIPs = reservedIPsValue; + } + + /** + * Initializes a new instance of the NetworkReservedIPListResponse class. + * + */ + public NetworkReservedIPListResponse() { + super(); + this.reservedIPs = new ArrayList(); + } + + /** + * Gets the sequence of ReservedIPs. + * + */ + public Iterator iterator() { + return this.getReservedIPs().iterator(); + } + + /** + * A reserved IP associated with your subscription. + */ + public static class ReservedIP { + private InetAddress address; + + /** + * Optional. The IP address of the reserved IP. + * @return The Address value. + */ + public InetAddress getAddress() { + return this.address; + } + + /** + * Optional. The IP address of the reserved IP. + * @param addressValue The Address value. + */ + public void setAddress(final InetAddress addressValue) { + this.address = addressValue; + } + + private String affinityGroup; + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. An affinity group, which indirectly refers to the location + * where the virtual network exists. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String deploymentName; + + /** + * Optional. The name of the deployment the IP belongs to, if used. + * @return The DeploymentName value. + */ + public String getDeploymentName() { + return this.deploymentName; + } + + /** + * Optional. The name of the deployment the IP belongs to, if used. + * @param deploymentNameValue The DeploymentName value. + */ + public void setDeploymentName(final String deploymentNameValue) { + this.deploymentName = deploymentNameValue; + } + + private String id; + + /** + * Optional. A unique string identifier that represents the reserved IP. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. A unique string identifier that represents the reserved IP. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private boolean inUse; + + /** + * Optional. The indicator of whether the reserved IP is used. + * @return The InUse value. + */ + public boolean isInUse() { + return this.inUse; + } + + /** + * Optional. The indicator of whether the reserved IP is used. + * @param inUseValue The InUse value. + */ + public void setInUse(final boolean inUseValue) { + this.inUse = inUseValue; + } + + private String label; + + /** + * Optional. The friendly identifier for the site. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The friendly identifier for the site. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String name; + + /** + * Optional. Name of the reserved IP. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Name of the reserved IP. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String serviceName; + + /** + * Optional. The name of the service the IP belongs to, if used. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The name of the service the IP belongs to, if used. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private String state; + + /** + * Optional. Current status of the reserved IP. (Created, Creating, + * Updating, Deleting, or Unavailable.) + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Current status of the reserved IP. (Created, Creating, + * Updating, Deleting, or Unavailable.) + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkSetConfigurationParameters.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkSetConfigurationParameters.java new file mode 100644 index 0000000000000..f7bab64fc9f83 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkSetConfigurationParameters.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Parameters supplied to the Set Network Configuration operation. +*/ +public class NetworkSetConfigurationParameters { + private String configuration; + + /** + * Required. The network configuration for this subscription. + * @return The Configuration value. + */ + public String getConfiguration() { + return this.configuration; + } + + /** + * Required. The network configuration for this subscription. + * @param configurationValue The Configuration value. + */ + public void setConfiguration(final String configurationValue) { + this.configuration = configurationValue; + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkStaticIPAvailabilityResponse.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkStaticIPAvailabilityResponse.java new file mode 100644 index 0000000000000..cfe1d3968c6ae --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/NetworkStaticIPAvailabilityResponse.java @@ -0,0 +1,80 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.InetAddress; +import java.util.ArrayList; + +/** +* A response that indicates the availability of a static IP address, and if +* not, provides a list of suggestions. +*/ +public class NetworkStaticIPAvailabilityResponse extends OperationResponse { + private ArrayList availableAddresses; + + /** + * Optional. The list of the available IP addresses. + * @return The AvailableAddresses value. + */ + public ArrayList getAvailableAddresses() { + return this.availableAddresses; + } + + /** + * Optional. The list of the available IP addresses. + * @param availableAddressesValue The AvailableAddresses value. + */ + public void setAvailableAddresses(final ArrayList availableAddressesValue) { + this.availableAddresses = availableAddressesValue; + } + + private boolean isAvailable; + + /** + * Optional. Whether the IP address is available. + * @return The IsAvailable value. + */ + public boolean isAvailable() { + return this.isAvailable; + } + + /** + * Optional. Whether the IP address is available. + * @param isAvailableValue The IsAvailable value. + */ + public void setIsAvailable(final boolean isAvailableValue) { + this.isAvailable = isAvailableValue; + } + + /** + * Initializes a new instance of the NetworkStaticIPAvailabilityResponse + * class. + * + */ + public NetworkStaticIPAvailabilityResponse() { + super(); + this.availableAddresses = new ArrayList(); + } +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ReservedIPState.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ReservedIPState.java new file mode 100644 index 0000000000000..9c373cb69bda6 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/ReservedIPState.java @@ -0,0 +1,36 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +public abstract class ReservedIPState { + public static final String CREATED = "Created"; + + public static final String CREATING = "Creating"; + + public static final String UPDATING = "Updating"; + + public static final String DELETING = "Deleting"; + + public static final String UNAVAILABLE = "Unavailable"; +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/VirtualNetworkState.java b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/VirtualNetworkState.java new file mode 100644 index 0000000000000..bf6962d44c633 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/VirtualNetworkState.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.network.models; + +/** +* Possible values for the Virtual Network State. +*/ +public abstract class VirtualNetworkState { + public static final String CREATED = "Created"; + + public static final String CREATING = "Creating"; + + public static final String UPDATING = "Updating"; + + public static final String DELETING = "Deleting"; + + public static final String UNAVAILABLE = "Unavailable"; +} diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/package.html b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/package.html new file mode 100644 index 0000000000000..cac417ab440c8 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/models/package.html @@ -0,0 +1,5 @@ + + +This package contains the models for the network management client. + + diff --git a/management-network/src/main/java/com/microsoft/windowsazure/management/network/package.html b/management-network/src/main/java/com/microsoft/windowsazure/management/network/package.html new file mode 100644 index 0000000000000..211e4a85b16e6 --- /dev/null +++ b/management-network/src/main/java/com/microsoft/windowsazure/management/network/package.html @@ -0,0 +1,6 @@ + + +This package contains the service network management class, + interface, and associated configuration and utility classes. + + diff --git a/management-network/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/management-network/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..0b73e1ca7f585 --- /dev/null +++ b/management-network/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1 @@ +com.microsoft.windowsazure.management.network.Exports diff --git a/management-network/src/test/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperationsTests.java b/management-network/src/test/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperationsTests.java new file mode 100644 index 0000000000000..ef80ad7c4492f --- /dev/null +++ b/management-network/src/test/java/com/microsoft/windowsazure/management/network/ClientRootCertificateOperationsTests.java @@ -0,0 +1,93 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.network; + +import static org.junit.Assert.*; + +import java.util.ArrayList; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.management.network.models.*; +import com.microsoft.windowsazure.exception.ServiceException; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ClientRootCertificateOperationsTests extends NetworkManagementIntegrationTestBase { + @BeforeClass + public static void setup() throws Exception { + testNetworkName = testNetworkPrefix + randomString(10);; + createService(); + networkOperations = networkManagementClient.getNetworksOperations(); + createNetwork(testNetworkName); + clientRootCertificateOperations = networkManagementClient.getClientRootCertificatesOperations(); + } + + @AfterClass + public static void cleanup() throws Exception { + try { + ClientRootCertificateListResponse ClientRootCertificateListResponse = clientRootCertificateOperations.list(testNetworkName); + ArrayList clientRootCertificatelist = ClientRootCertificateListResponse.getClientRootCertificates(); + for (ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificate : clientRootCertificatelist) { + clientRootCertificateOperations.delete(testNetworkName, clientRootCertificate.getThumbprint()); + } + } catch (ServiceException e) { + } + } + + @Test(expected = ServiceException.class) + public void createClientInvalidRootCertificatesFailed() throws Exception { + String certificateValue = "InvalidRootCertificate"; + // Arrange + ClientRootCertificateCreateParameters createParameters = new ClientRootCertificateCreateParameters(); + createParameters.setCertificate(certificateValue); + + // Act + OperationResponse operationResponse = clientRootCertificateOperations.create(testNetworkName, createParameters); + + // Assert + Assert.assertEquals(201, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void getClientRootCertificates() throws Exception { + ClientRootCertificateListResponse ClientRootCertificateListResponse = networkManagementClient.getClientRootCertificatesOperations().list(testNetworkName); + ArrayList clientRootCertificatelist = ClientRootCertificateListResponse.getClientRootCertificates(); + for (ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificate : clientRootCertificatelist) { + ClientRootCertificateGetResponse clientRootCertificateGetResponse = networkManagementClient.getClientRootCertificatesOperations().get(testNetworkName, clientRootCertificate.getThumbprint()); + Assert.assertEquals(200, clientRootCertificateGetResponse.getStatusCode()); + Assert.assertNotNull(clientRootCertificateGetResponse.getRequestId()); + Assert.assertNotNull(clientRootCertificateGetResponse.getCertificate()); + } + } + + @Test + public void listClientRootCertificatesSuccess() throws Exception { + try { + ClientRootCertificateListResponse ClientRootCertificateListResponse = networkManagementClient.getClientRootCertificatesOperations().list(testNetworkName); + ArrayList clientRootCertificatelist = ClientRootCertificateListResponse.getClientRootCertificates(); + for (ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificate : clientRootCertificatelist) { + assertNotNull(clientRootCertificate.getThumbprint()); + assertNotNull(clientRootCertificate.getExpirationTime()); + assertNotNull(clientRootCertificate.getSubject()); + } + } catch (ServiceException e) { + } + } +} \ No newline at end of file diff --git a/management-network/src/test/java/com/microsoft/windowsazure/management/network/GatewayOperationsTests.java b/management-network/src/test/java/com/microsoft/windowsazure/management/network/GatewayOperationsTests.java new file mode 100644 index 0000000000000..1e7a89647820e --- /dev/null +++ b/management-network/src/test/java/com/microsoft/windowsazure/management/network/GatewayOperationsTests.java @@ -0,0 +1,107 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.network; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.ArrayList; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.management.network.models.*; +import com.microsoft.windowsazure.exception.ServiceException; +import java.util.concurrent.ExecutionException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.xml.sax.SAXException; + +public class GatewayOperationsTests extends NetworkManagementIntegrationTestBase { + + @BeforeClass + public static void setup() throws Exception { + createService(); + networkOperations = networkManagementClient.getNetworksOperations(); + gatewayOperations = networkManagementClient.getGatewaysOperations(); + testNetworkName = testNetworkPrefix + randomString(10); + testGatewayName = testGatewayPrefix + randomString(10); + createNetwork(testNetworkName); + } + + @AfterClass + public static void cleanup() { + deleteNetwork(testNetworkName); + + try { + gatewayOperations.delete(testNetworkName); + } catch (IOException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } catch (ServiceException e) { + e.printStackTrace(); + } + } + + @Test(expected = ExecutionException.class) + public void createGatewayOnEmptyNetworkFailed() throws Exception { + // Arrange + GatewayCreateParameters gatewayCreateParameters = new GatewayCreateParameters(); + gatewayCreateParameters.setGatewayType(GatewayType.StaticRouting); + + // Act + OperationResponse operationResponse = gatewayOperations.create(testNetworkName, gatewayCreateParameters); + + // Assert + Assert.assertEquals(201, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void getGatewaySuccess() throws Exception { + // Act + GatewayGetResponse gatewayGetResponse = gatewayOperations.get(testNetworkName); + // Assert + Assert.assertEquals(200, gatewayGetResponse.getStatusCode()); + Assert.assertNotNull(gatewayGetResponse.getRequestId()); + } + + @Test(expected = ServiceException.class) + public void listGatewayFailedWithInsufficientPermission() throws Exception { + // Arrange + GatewayListConnectionsResponse gatewayListConnectionsResponse = gatewayOperations.listConnections(testNetworkName); + ArrayList gatewayConnectionlist = gatewayListConnectionsResponse.getConnections(); + for (GatewayListConnectionsResponse.GatewayConnection gatewayConnection : gatewayConnectionlist ) { + assertNotNull(gatewayConnection.getAllocatedIPAddresses()); + assertNotNull(gatewayConnection.getConnectivityState()); + assertNotNull(gatewayConnection.getEgressBytesTransferred()); + assertNotNull(gatewayConnection.getIngressBytesTransferred()); + assertNotNull(gatewayConnection.getLastConnectionEstablished()); + assertNotNull(gatewayConnection.getLastEvent()); + assertNotNull(gatewayConnection.getLocalNetworkSiteName()); + } + } +} \ No newline at end of file diff --git a/management-network/src/test/java/com/microsoft/windowsazure/management/network/NetworkManagementIntegrationTestBase.java b/management-network/src/test/java/com/microsoft/windowsazure/management/network/NetworkManagementIntegrationTestBase.java new file mode 100644 index 0000000000000..47ed4bf41891f --- /dev/null +++ b/management-network/src/test/java/com/microsoft/windowsazure/management/network/NetworkManagementIntegrationTestBase.java @@ -0,0 +1,211 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.network; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringWriter; +import java.net.URI; +import java.util.Random; +import java.util.concurrent.ExecutionException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.junit.Assert; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.configuration.*; +import com.microsoft.windowsazure.management.network.models.NetworkGetConfigurationResponse; +import com.microsoft.windowsazure.management.network.models.NetworkSetConfigurationParameters; +import com.microsoft.windowsazure.*; + +public abstract class NetworkManagementIntegrationTestBase { + + protected static NetworkManagementClient networkManagementClient; + protected static NetworkOperations networkOperations; + protected static ReservedIPOperations reservedIPOperations; + protected static GatewayOperations gatewayOperations; + protected static StaticIPOperations staticIPOperations; + protected static ClientRootCertificateOperations clientRootCertificateOperations; + protected static String testNetworkPrefix = "javatestvn"; + protected static String testReservedIPPrefix = "javareservedip"; + protected static String testGatewayPrefix = "javagateway"; + protected static String testNetworkName; + protected static String testGatewayName; + + + protected static void createService() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + networkManagementClient = NetworkManagementService.create(config); + } + + protected static Configuration createConfiguration() throws Exception { + String baseUri = System.getenv(ManagementConfiguration.URI); + return ManagementConfiguration.configure( + baseUri != null ? new URI(baseUri) : null, + System.getenv(ManagementConfiguration.SUBSCRIPTION_ID), + System.getenv(ManagementConfiguration.KEYSTORE_PATH), + System.getenv(ManagementConfiguration.KEYSTORE_PASSWORD), + KeyStoreType.fromString(System.getenv(ManagementConfiguration.KEYSTORE_TYPE))); + } + + protected static void createNetwork(String networkName) throws Exception { + NetworkGetConfigurationResponse operationResponse = networkManagementClient.getNetworksOperations().getConfiguration(); + + //Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + Assert.assertNotNull(operationResponse.getConfiguration()); + + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(new ByteArrayInputStream(operationResponse.getConfiguration().getBytes()))); + + NodeList list = responseDoc.getElementsByTagNameNS("http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration", "VirtualNetworkSite"); + boolean exist = false; + for (int i = 0; i < list.getLength(); i++) { + if (list.item(i).getAttributes().getNamedItem("name").getTextContent().equals(networkName)) { + exist = true; + break; + } + } + + if (!exist) { + Element vnets = (Element) responseDoc.getElementsByTagNameNS("http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration", "VirtualNetworkSites").item(0); + Element vnet = responseDoc.createElementNS("http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration", "VirtualNetworkSite"); + vnet.setAttribute("name", networkName); + vnet.setAttribute("AffinityGroup", "azuresdkci"); + + Element addressSpace = responseDoc.createElementNS("http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration", "AddressSpace"); + vnet.appendChild(addressSpace); + + Element addressPrefix = responseDoc.createElementNS("http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration", "AddressPrefix"); + addressPrefix.setTextContent("10.10.0.0/8"); + addressSpace.appendChild(addressPrefix); + + vnets.appendChild(vnet); + + DOMSource domSource = new DOMSource(responseDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + + NetworkSetConfigurationParameters parameters = new NetworkSetConfigurationParameters(); + parameters.setConfiguration(stringWriter.toString()); + networkOperations.setConfiguration(parameters); + } + } + + protected static void deleteNetwork(String networkName) { + NetworkGetConfigurationResponse operationResponse = null ; + boolean exist = false; + + try { + operationResponse = networkManagementClient.getNetworksOperations().getConfiguration(); + } catch (IOException e) { + } catch (ServiceException e) { + } + + //Assert + if (operationResponse != null) + { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = null; + try { + documentBuilder = documentBuilderFactory.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } + Document responseDoc = null; + try { + responseDoc = documentBuilder.parse(new BOMInputStream(new ByteArrayInputStream(operationResponse.getConfiguration().getBytes()))); + } catch (NullPointerException e) { + } catch (SAXException e) { + } catch (IOException e) { + } + + NodeList virtualNetworkSitelist = responseDoc.getElementsByTagNameNS("http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration", "VirtualNetworkSite"); + + for (int i = 0; i < virtualNetworkSitelist.getLength(); i++) { + if (virtualNetworkSitelist.item(i).getAttributes().getNamedItem("name").getTextContent().equals(networkName)) { + Node oldChild = virtualNetworkSitelist.item(i); + oldChild.getParentNode().removeChild(oldChild); + + exist = true; + break; + } + } + + if (exist) { + DOMSource domSource = new DOMSource(responseDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = null; + try { + transformer = transformerFactory.newTransformer(); + } catch (TransformerConfigurationException e) { + e.printStackTrace(); + } + + try { + transformer.transform(domSource, streamResult); + } catch (TransformerException e) { + e.printStackTrace(); + } + + NetworkSetConfigurationParameters parameters = new NetworkSetConfigurationParameters(); + parameters.setConfiguration(stringWriter.toString()); + try { + networkOperations.setConfiguration(parameters); + } catch (InterruptedException e) { + } catch (ExecutionException e) { + } catch (ServiceException e) { + } catch (IOException e) { + } + } + } + } + + + protected static String randomString(int length) { + Random random = new Random(); + StringBuilder stringBuilder = new StringBuilder(length); + for (int i = 0; i virtualnetwoksitelist = NetworkListResponse.getVirtualNetworkSites(); + for (NetworkListResponse.VirtualNetworkSite networksite : virtualnetwoksitelist) { + assertNotNull(networksite.getName()); + assertNotNull(networksite.getAffinityGroup()); + assertNotNull(networksite.getId()); + assertNotNull(networksite.getState()); + assertNotNull(networksite.getAddressSpace()); + assertNotNull(networksite.getSubnets()); + } + } +} \ No newline at end of file diff --git a/management-network/src/test/java/com/microsoft/windowsazure/management/network/StaticIPOperationsTests.java b/management-network/src/test/java/com/microsoft/windowsazure/management/network/StaticIPOperationsTests.java new file mode 100644 index 0000000000000..9688da2a41326 --- /dev/null +++ b/management-network/src/test/java/com/microsoft/windowsazure/management/network/StaticIPOperationsTests.java @@ -0,0 +1,48 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.network; + +import com.microsoft.windowsazure.exception.ServiceException; +import java.net.InetAddress; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class StaticIPOperationsTests extends NetworkManagementIntegrationTestBase { + + @BeforeClass + public static void setup() throws Exception { + createService(); + networkOperations = networkManagementClient.getNetworksOperations(); + testNetworkName = testNetworkPrefix + randomString(10); + createNetwork(testNetworkName); + staticIPOperations = networkManagementClient.getStaticIPsOperations(); + } + + @AfterClass + public static void cleanup() { + deleteNetwork(testNetworkName); + } + + @Test(expected = ServiceException.class) + public void checkIllegalIPAddressFailed() throws Exception { + InetAddress ipAddress = InetAddress.getLocalHost(); + + // Act + staticIPOperations.check(testNetworkName, ipAddress); + } +} \ No newline at end of file diff --git a/management-sql/pom.xml b/management-sql/pom.xml new file mode 100644 index 0000000000000..ab1b5a58699d2 --- /dev/null +++ b/management-sql/pom.xml @@ -0,0 +1,158 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-management-sql + jar + + Microsoft Azure SQL Management Client API + Microsoft Azure SQL Management SDK Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + 2.1.1 + 3.0.7.RELEASE + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + org.apache.httpcomponents + httpclient + + + javax.inject + javax.inject + + + + + ${project.groupId} + microsoft-azure-api-management-storage + 0.5.0 + test + + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk16 + test + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+
+
diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DacOperations.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DacOperations.java new file mode 100644 index 0000000000000..68c811ce1df09 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DacOperations.java @@ -0,0 +1,134 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.DacExportParameters; +import com.microsoft.windowsazure.management.sql.models.DacGetStatusResponse; +import com.microsoft.windowsazure.management.sql.models.DacImportExportResponse; +import com.microsoft.windowsazure.management.sql.models.DacImportParameters; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* Includes operations for importing and exporting SQL Databases into and out of +* Windows Azure blob storage. +*/ +public interface DacOperations { + /** + * Export DAC into Windows Azure blob storage. + * + * @param serverName Required. The name of the server being exported from. + * @param parameters Optional. Export parameters. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response for an DAC Import/Export request. + */ + DacImportExportResponse exportDatabase(String serverName, DacExportParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Export DAC into Windows Azure blob storage. + * + * @param serverName Required. The name of the server being exported from. + * @param parameters Optional. Export parameters. + * @return Response for an DAC Import/Export request. + */ + Future exportDatabaseAsync(String serverName, DacExportParameters parameters); + + /** + * Gets the status of the DAC. + * + * @param serverName Required. The name of the server. + * @param fullyQualifiedServerName Required. The fully qualified name of the + * server. + * @param username Required. The server's username. + * @param password Required. The server's password. + * @param requestId Required. The request ID of the operation being queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response structure for the DAC GetStatus operation. + */ + DacGetStatusResponse getStatus(String serverName, String fullyQualifiedServerName, String username, String password, String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * Gets the status of the DAC. + * + * @param serverName Required. The name of the server. + * @param fullyQualifiedServerName Required. The fully qualified name of the + * server. + * @param username Required. The server's username. + * @param password Required. The server's password. + * @param requestId Required. The request ID of the operation being queried. + * @return The response structure for the DAC GetStatus operation. + */ + Future getStatusAsync(String serverName, String fullyQualifiedServerName, String username, String password, String requestId); + + /** + * Import DAC from Windows Azure blob storage. + * + * @param serverName Required. The name of the server being imported to. + * @param parameters Optional. Import parameters. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response for an DAC Import/Export request. + */ + DacImportExportResponse importDatabase(String serverName, DacImportParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Import DAC from Windows Azure blob storage. + * + * @param serverName Required. The name of the server being imported to. + * @param parameters Optional. Import parameters. + * @return Response for an DAC Import/Export request. + */ + Future importDatabaseAsync(String serverName, DacImportParameters parameters); +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DacOperationsImpl.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DacOperationsImpl.java new file mode 100644 index 0000000000000..614be7d50e28f --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DacOperationsImpl.java @@ -0,0 +1,732 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.DacExportParameters; +import com.microsoft.windowsazure.management.sql.models.DacGetStatusResponse; +import com.microsoft.windowsazure.management.sql.models.DacImportExportResponse; +import com.microsoft.windowsazure.management.sql.models.DacImportParameters; +import com.microsoft.windowsazure.management.sql.models.StatusInfo; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Includes operations for importing and exporting SQL Databases into and out of +* Windows Azure blob storage. +*/ +public class DacOperationsImpl implements ServiceOperations, DacOperations { + /** + * Initializes a new instance of the DacOperationsImpl class. + * + * @param client Reference to the service client. + */ + DacOperationsImpl(SqlManagementClientImpl client) { + this.client = client; + } + + private SqlManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.sql.SqlManagementClientImpl. + * @return The Client value. + */ + public SqlManagementClientImpl getClient() { + return this.client; + } + + /** + * Export DAC into Windows Azure blob storage. + * + * @param serverName Required. The name of the server being exported from. + * @param parameters Optional. Export parameters. + * @return Response for an DAC Import/Export request. + */ + @Override + public Future exportDatabaseAsync(final String serverName, final DacExportParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DacImportExportResponse call() throws Exception { + return exportDatabase(serverName, parameters); + } + }); + } + + /** + * Export DAC into Windows Azure blob storage. + * + * @param serverName Required. The name of the server being exported from. + * @param parameters Optional. Export parameters. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response for an DAC Import/Export request. + */ + @Override + public DacImportExportResponse exportDatabase(String serverName, DacExportParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (parameters != null) { + if (parameters.getBlobCredentials() != null) { + if (parameters.getBlobCredentials().getStorageAccessKey() == null) { + throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey"); + } + if (parameters.getBlobCredentials().getUri() == null) { + throw new NullPointerException("parameters.BlobCredentials.Uri"); + } + } + if (parameters.getConnectionInfo() != null) { + if (parameters.getConnectionInfo().getDatabaseName() == null) { + throw new NullPointerException("parameters.ConnectionInfo.DatabaseName"); + } + if (parameters.getConnectionInfo().getPassword() == null) { + throw new NullPointerException("parameters.ConnectionInfo.Password"); + } + if (parameters.getConnectionInfo().getServerName() == null) { + throw new NullPointerException("parameters.ConnectionInfo.ServerName"); + } + if (parameters.getConnectionInfo().getUserName() == null) { + throw new NullPointerException("parameters.ConnectionInfo.UserName"); + } + } + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "exportDatabaseAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/DacOperations/Export"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + if (parameters != null) { + Element exportInputElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ExportInput"); + requestDoc.appendChild(exportInputElement); + + if (parameters.getBlobCredentials() != null) { + Element blobCredentialsElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobCredentials"); + exportInputElement.appendChild(blobCredentialsElement); + + Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); + typeAttribute.setValue("BlobStorageAccessKeyCredentials"); + blobCredentialsElement.setAttributeNode(typeAttribute); + + Element uriElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Uri"); + uriElement.appendChild(requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString())); + blobCredentialsElement.appendChild(uriElement); + + Element storageAccessKeyElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StorageAccessKey"); + storageAccessKeyElement.appendChild(requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey())); + blobCredentialsElement.appendChild(storageAccessKeyElement); + } + + if (parameters.getConnectionInfo() != null) { + Element connectionInfoElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ConnectionInfo"); + exportInputElement.appendChild(connectionInfoElement); + + Element databaseNameElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); + databaseNameElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName())); + connectionInfoElement.appendChild(databaseNameElement); + + Element passwordElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword())); + connectionInfoElement.appendChild(passwordElement); + + Element serverNameElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); + serverNameElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName())); + connectionInfoElement.appendChild(serverNameElement); + + Element userNameElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "UserName"); + userNameElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName())); + connectionInfoElement.appendChild(userNameElement); + } + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DacImportExportResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DacImportExportResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "guid"); + if (guidElement != null) { + result.setGuid(guidElement.getTextContent()); + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Gets the status of the DAC. + * + * @param serverName Required. The name of the server. + * @param fullyQualifiedServerName Required. The fully qualified name of the + * server. + * @param username Required. The server's username. + * @param password Required. The server's password. + * @param requestId Required. The request ID of the operation being queried. + * @return The response structure for the DAC GetStatus operation. + */ + @Override + public Future getStatusAsync(final String serverName, final String fullyQualifiedServerName, final String username, final String password, final String requestId) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DacGetStatusResponse call() throws Exception { + return getStatus(serverName, fullyQualifiedServerName, username, password, requestId); + } + }); + } + + /** + * Gets the status of the DAC. + * + * @param serverName Required. The name of the server. + * @param fullyQualifiedServerName Required. The fully qualified name of the + * server. + * @param username Required. The server's username. + * @param password Required. The server's password. + * @param requestId Required. The request ID of the operation being queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The response structure for the DAC GetStatus operation. + */ + @Override + public DacGetStatusResponse getStatus(String serverName, String fullyQualifiedServerName, String username, String password, String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (fullyQualifiedServerName == null) { + throw new NullPointerException("fullyQualifiedServerName"); + } + if (username == null) { + throw new NullPointerException("username"); + } + if (password == null) { + throw new NullPointerException("password"); + } + if (requestId == null) { + throw new NullPointerException("requestId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("fullyQualifiedServerName", fullyQualifiedServerName); + tracingParameters.put("username", username); + tracingParameters.put("password", password); + tracingParameters.put("requestId", requestId); + CloudTracing.enter(invocationId, this, "getStatusAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/DacOperations/Status" + "?"; + url = url + "servername=" + URLEncoder.encode(fullyQualifiedServerName.trim(), "UTF-8"); + url = url + "&" + "username=" + URLEncoder.encode(username.trim(), "UTF-8"); + url = url + "&" + "password=" + URLEncoder.encode(password.trim(), "UTF-8"); + url = url + "&" + "reqId=" + URLEncoder.encode(requestId.trim(), "UTF-8"); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DacGetStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DacGetStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element arrayOfStatusInfoElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ArrayOfStatusInfo"); + if (arrayOfStatusInfoElement != null) { + if (arrayOfStatusInfoElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(arrayOfStatusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StatusInfo").size(); i1 = i1 + 1) { + org.w3c.dom.Element statusInfoElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(arrayOfStatusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StatusInfo").get(i1)); + StatusInfo statusInfoInstance = new StatusInfo(); + result.getStatusInfoList().add(statusInfoInstance); + + Element blobUriElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobUri"); + if (blobUriElement != null) { + URI blobUriInstance; + blobUriInstance = new URI(blobUriElement.getTextContent()); + statusInfoInstance.setBlobUri(blobUriInstance); + } + + Element databaseNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); + if (databaseNameElement != null) { + String databaseNameInstance; + databaseNameInstance = databaseNameElement.getTextContent(); + statusInfoInstance.setDatabaseName(databaseNameInstance); + } + + Element errorMessageElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ErrorMessage"); + if (errorMessageElement != null) { + boolean isNil = false; + Attr nilAttribute = errorMessageElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String errorMessageInstance; + errorMessageInstance = errorMessageElement.getTextContent(); + statusInfoInstance.setErrorMessage(errorMessageInstance); + } + } + + Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "LastModifiedTime"); + if (lastModifiedTimeElement != null) { + Calendar lastModifiedTimeInstance; + lastModifiedTimeInstance = DatatypeConverter.parseDateTime(lastModifiedTimeElement.getTextContent()); + statusInfoInstance.setLastModifiedTime(lastModifiedTimeInstance); + } + + Element queuedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "QueuedTime"); + if (queuedTimeElement != null) { + Calendar queuedTimeInstance; + queuedTimeInstance = DatatypeConverter.parseDateTime(queuedTimeElement.getTextContent()); + statusInfoInstance.setQueuedTime(queuedTimeInstance); + } + + Element requestIdElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "RequestId"); + if (requestIdElement != null) { + String requestIdInstance; + requestIdInstance = requestIdElement.getTextContent(); + statusInfoInstance.setRequestId(requestIdInstance); + } + + Element requestTypeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "RequestType"); + if (requestTypeElement != null) { + String requestTypeInstance; + requestTypeInstance = requestTypeElement.getTextContent(); + statusInfoInstance.setRequestType(requestTypeInstance); + } + + Element serverNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); + if (serverNameElement != null) { + String serverNameInstance; + serverNameInstance = serverNameElement.getTextContent(); + statusInfoInstance.setServerName(serverNameInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Status"); + if (statusElement != null) { + String statusInstance; + statusInstance = statusElement.getTextContent(); + statusInfoInstance.setStatus(statusInstance); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Import DAC from Windows Azure blob storage. + * + * @param serverName Required. The name of the server being imported to. + * @param parameters Optional. Import parameters. + * @return Response for an DAC Import/Export request. + */ + @Override + public Future importDatabaseAsync(final String serverName, final DacImportParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DacImportExportResponse call() throws Exception { + return importDatabase(serverName, parameters); + } + }); + } + + /** + * Import DAC from Windows Azure blob storage. + * + * @param serverName Required. The name of the server being imported to. + * @param parameters Optional. Import parameters. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response for an DAC Import/Export request. + */ + @Override + public DacImportExportResponse importDatabase(String serverName, DacImportParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (parameters != null) { + if (parameters.getBlobCredentials() != null) { + if (parameters.getBlobCredentials().getStorageAccessKey() == null) { + throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey"); + } + if (parameters.getBlobCredentials().getUri() == null) { + throw new NullPointerException("parameters.BlobCredentials.Uri"); + } + } + if (parameters.getConnectionInfo() != null) { + if (parameters.getConnectionInfo().getDatabaseName() == null) { + throw new NullPointerException("parameters.ConnectionInfo.DatabaseName"); + } + if (parameters.getConnectionInfo().getPassword() == null) { + throw new NullPointerException("parameters.ConnectionInfo.Password"); + } + if (parameters.getConnectionInfo().getServerName() == null) { + throw new NullPointerException("parameters.ConnectionInfo.ServerName"); + } + if (parameters.getConnectionInfo().getUserName() == null) { + throw new NullPointerException("parameters.ConnectionInfo.UserName"); + } + } + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "importDatabaseAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/DacOperations/Import"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + if (parameters != null) { + Element importInputElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ImportInput"); + requestDoc.appendChild(importInputElement); + + if (parameters.getAzureEdition() != null) { + Element azureEditionElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "AzureEdition"); + azureEditionElement.appendChild(requestDoc.createTextNode(parameters.getAzureEdition())); + importInputElement.appendChild(azureEditionElement); + } + + if (parameters.getBlobCredentials() != null) { + Element blobCredentialsElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobCredentials"); + importInputElement.appendChild(blobCredentialsElement); + + Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); + typeAttribute.setValue("BlobStorageAccessKeyCredentials"); + blobCredentialsElement.setAttributeNode(typeAttribute); + + Element uriElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Uri"); + uriElement.appendChild(requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString())); + blobCredentialsElement.appendChild(uriElement); + + Element storageAccessKeyElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StorageAccessKey"); + storageAccessKeyElement.appendChild(requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey())); + blobCredentialsElement.appendChild(storageAccessKeyElement); + } + + if (parameters.getConnectionInfo() != null) { + Element connectionInfoElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ConnectionInfo"); + importInputElement.appendChild(connectionInfoElement); + + Element databaseNameElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); + databaseNameElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName())); + connectionInfoElement.appendChild(databaseNameElement); + + Element passwordElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword())); + connectionInfoElement.appendChild(passwordElement); + + Element serverNameElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); + serverNameElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName())); + connectionInfoElement.appendChild(serverNameElement); + + Element userNameElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "UserName"); + userNameElement.appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName())); + connectionInfoElement.appendChild(userNameElement); + } + + Element databaseSizeInGBElement = requestDoc.createElementNS("http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseSizeInGB"); + databaseSizeInGBElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getDatabaseSizeInGB()))); + importInputElement.appendChild(databaseSizeInGBElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DacImportExportResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DacImportExportResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "guid"); + if (guidElement != null) { + result.setGuid(guidElement.getTextContent()); + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperations.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperations.java new file mode 100644 index 0000000000000..0bc43d27989bf --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperations.java @@ -0,0 +1,124 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperationGetResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperationListResponse; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for get/stop SQL +* Databases' operations for a subscription. +*/ +public interface DatabaseOperationOperations { + /** + * Returns information about one operation on a given operation Guid. + * + * @param serverName Required. The name of the SQL Server on which the + * operation was executed. + * @param operationGuid Required. The Guid of the SQL Server database + * operation to be obtained. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the database operation for a given operation + * Guid. + */ + DatabaseOperationGetResponse get(String serverName, String operationGuid) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns information about one operation on a given operation Guid. + * + * @param serverName Required. The name of the SQL Server on which the + * operation was executed. + * @param operationGuid Required. The Guid of the SQL Server database + * operation to be obtained. + * @return Response containing the database operation for a given operation + * Guid. + */ + Future getAsync(String serverName, String operationGuid); + + /** + * Returns the list database operations for a given server and database. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param databaseName Required. The name of the Database to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of database operations for a given + * server or database. + */ + DatabaseOperationListResponse listByDatabase(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns the list database operations for a given server and database. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param databaseName Required. The name of the Database to be queried. + * @return Response containing the list of database operations for a given + * server or database. + */ + Future listByDatabaseAsync(String serverName, String databaseName); + + /** + * Returns the list database operations for a given server. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of database operations for a given + * server or database. + */ + DatabaseOperationListResponse listByServer(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns the list database operations for a given server. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @return Response containing the list of database operations for a given + * server or database. + */ + Future listByServerAsync(String serverName); +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperationsImpl.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperationsImpl.java new file mode 100644 index 0000000000000..8e035f922c506 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperationsImpl.java @@ -0,0 +1,789 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperation; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperationGetResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperationListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for get/stop SQL +* Databases' operations for a subscription. +*/ +public class DatabaseOperationOperationsImpl implements ServiceOperations, DatabaseOperationOperations { + /** + * Initializes a new instance of the DatabaseOperationOperationsImpl class. + * + * @param client Reference to the service client. + */ + DatabaseOperationOperationsImpl(SqlManagementClientImpl client) { + this.client = client; + } + + private SqlManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.sql.SqlManagementClientImpl. + * @return The Client value. + */ + public SqlManagementClientImpl getClient() { + return this.client; + } + + /** + * Returns information about one operation on a given operation Guid. + * + * @param serverName Required. The name of the SQL Server on which the + * operation was executed. + * @param operationGuid Required. The Guid of the SQL Server database + * operation to be obtained. + * @return Response containing the database operation for a given operation + * Guid. + */ + @Override + public Future getAsync(final String serverName, final String operationGuid) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseOperationGetResponse call() throws Exception { + return get(serverName, operationGuid); + } + }); + } + + /** + * Returns information about one operation on a given operation Guid. + * + * @param serverName Required. The name of the SQL Server on which the + * operation was executed. + * @param operationGuid Required. The Guid of the SQL Server database + * operation to be obtained. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the database operation for a given operation + * Guid. + */ + @Override + public DatabaseOperationGetResponse get(String serverName, String operationGuid) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (operationGuid == null) { + throw new NullPointerException("operationGuid"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("operationGuid", operationGuid); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databaseoperations/" + operationGuid.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseOperationGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseOperationGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement != null) { + DatabaseOperation serviceResourceInstance = new DatabaseOperation(); + result.setDatabaseOperation(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + String selfLinkInstance; + selfLinkInstance = selfLinkElement.getTextContent(); + serviceResourceInstance.setSelfLink(selfLinkInstance); + } + + Element parentLinkElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement != null) { + String parentLinkInstance; + parentLinkInstance = parentLinkElement.getTextContent(); + serviceResourceInstance.setParentLink(parentLinkInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + serviceResourceInstance.setId(idInstance); + } + + Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "StateId"); + if (stateIdElement != null) { + int stateIdInstance; + stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent()); + serviceResourceInstance.setStateId(stateIdInstance); + } + + Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SessionActivityId"); + if (sessionActivityIdElement != null) { + String sessionActivityIdInstance; + sessionActivityIdInstance = sessionActivityIdElement.getTextContent(); + serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance); + } + + Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "DatabaseName"); + if (databaseNameElement != null) { + String databaseNameInstance; + databaseNameInstance = databaseNameElement.getTextContent(); + serviceResourceInstance.setDatabaseName(databaseNameInstance); + } + + Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "PercentComplete"); + if (percentCompleteElement != null) { + int percentCompleteInstance; + percentCompleteInstance = DatatypeConverter.parseInt(percentCompleteElement.getTextContent()); + serviceResourceInstance.setPercentComplete(percentCompleteInstance); + } + + Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ErrorCode"); + if (errorCodeElement != null) { + int errorCodeInstance; + errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent()); + serviceResourceInstance.setErrorCode(errorCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + String errorInstance; + errorInstance = errorElement.getTextContent(); + serviceResourceInstance.setError(errorInstance); + } + + Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ErrorSeverity"); + if (errorSeverityElement != null) { + int errorSeverityInstance; + errorSeverityInstance = DatatypeConverter.parseInt(errorSeverityElement.getTextContent()); + serviceResourceInstance.setErrorSeverity(errorSeverityInstance); + } + + Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ErrorState"); + if (errorStateElement != null) { + int errorStateInstance; + errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent()); + serviceResourceInstance.setErrorState(errorStateInstance); + } + + Element startTimeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); + if (startTimeElement != null) { + Calendar startTimeInstance; + startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); + serviceResourceInstance.setStartTime(startTimeInstance); + } + + Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "LastModifyTime"); + if (lastModifyTimeElement != null) { + Calendar lastModifyTimeInstance; + lastModifyTimeInstance = DatatypeConverter.parseDateTime(lastModifyTimeElement.getTextContent()); + serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns the list database operations for a given server and database. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param databaseName Required. The name of the Database to be queried. + * @return Response containing the list of database operations for a given + * server or database. + */ + @Override + public Future listByDatabaseAsync(final String serverName, final String databaseName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseOperationListResponse call() throws Exception { + return listByDatabase(serverName, databaseName); + } + }); + } + + /** + * Returns the list database operations for a given server and database. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param databaseName Required. The name of the Database to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of database operations for a given + * server or database. + */ + @Override + public DatabaseOperationListResponse listByDatabase(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (databaseName == null) { + throw new NullPointerException("databaseName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("databaseName", databaseName); + CloudTracing.enter(invocationId, this, "listByDatabaseAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databaseoperations" + "?"; + url = url + "databaseName=" + URLEncoder.encode(databaseName.trim(), "UTF-8"); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseOperationListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseOperationListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResources"); + if (serviceResourcesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i1 = i1 + 1) { + org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i1)); + DatabaseOperation serviceResourceInstance = new DatabaseOperation(); + result.getDatabaseOperations().add(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + String selfLinkInstance; + selfLinkInstance = selfLinkElement.getTextContent(); + serviceResourceInstance.setSelfLink(selfLinkInstance); + } + + Element parentLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement != null) { + String parentLinkInstance; + parentLinkInstance = parentLinkElement.getTextContent(); + serviceResourceInstance.setParentLink(parentLinkInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + serviceResourceInstance.setId(idInstance); + } + + Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StateId"); + if (stateIdElement != null) { + int stateIdInstance; + stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent()); + serviceResourceInstance.setStateId(stateIdInstance); + } + + Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SessionActivityId"); + if (sessionActivityIdElement != null) { + String sessionActivityIdInstance; + sessionActivityIdInstance = sessionActivityIdElement.getTextContent(); + serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance); + } + + Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "DatabaseName"); + if (databaseNameElement != null) { + String databaseNameInstance; + databaseNameInstance = databaseNameElement.getTextContent(); + serviceResourceInstance.setDatabaseName(databaseNameInstance); + } + + Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "PercentComplete"); + if (percentCompleteElement != null) { + int percentCompleteInstance; + percentCompleteInstance = DatatypeConverter.parseInt(percentCompleteElement.getTextContent()); + serviceResourceInstance.setPercentComplete(percentCompleteInstance); + } + + Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorCode"); + if (errorCodeElement != null) { + int errorCodeInstance; + errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent()); + serviceResourceInstance.setErrorCode(errorCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + String errorInstance; + errorInstance = errorElement.getTextContent(); + serviceResourceInstance.setError(errorInstance); + } + + Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorSeverity"); + if (errorSeverityElement != null) { + int errorSeverityInstance; + errorSeverityInstance = DatatypeConverter.parseInt(errorSeverityElement.getTextContent()); + serviceResourceInstance.setErrorSeverity(errorSeverityInstance); + } + + Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorState"); + if (errorStateElement != null) { + int errorStateInstance; + errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent()); + serviceResourceInstance.setErrorState(errorStateInstance); + } + + Element startTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); + if (startTimeElement != null) { + Calendar startTimeInstance; + startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); + serviceResourceInstance.setStartTime(startTimeInstance); + } + + Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "LastModifyTime"); + if (lastModifyTimeElement != null) { + Calendar lastModifyTimeInstance; + lastModifyTimeInstance = DatatypeConverter.parseDateTime(lastModifyTimeElement.getTextContent()); + serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns the list database operations for a given server. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @return Response containing the list of database operations for a given + * server or database. + */ + @Override + public Future listByServerAsync(final String serverName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseOperationListResponse call() throws Exception { + return listByServer(serverName); + } + }); + } + + /** + * Returns the list database operations for a given server. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of database operations for a given + * server or database. + */ + @Override + public DatabaseOperationListResponse listByServer(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + CloudTracing.enter(invocationId, this, "listByServerAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databaseoperations" + "?" + "contentview=generic"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseOperationListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseOperationListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResources"); + if (serviceResourcesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i1 = i1 + 1) { + org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i1)); + DatabaseOperation serviceResourceInstance = new DatabaseOperation(); + result.getDatabaseOperations().add(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + String selfLinkInstance; + selfLinkInstance = selfLinkElement.getTextContent(); + serviceResourceInstance.setSelfLink(selfLinkInstance); + } + + Element parentLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement != null) { + String parentLinkInstance; + parentLinkInstance = parentLinkElement.getTextContent(); + serviceResourceInstance.setParentLink(parentLinkInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + serviceResourceInstance.setId(idInstance); + } + + Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StateId"); + if (stateIdElement != null) { + int stateIdInstance; + stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent()); + serviceResourceInstance.setStateId(stateIdInstance); + } + + Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SessionActivityId"); + if (sessionActivityIdElement != null) { + String sessionActivityIdInstance; + sessionActivityIdInstance = sessionActivityIdElement.getTextContent(); + serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance); + } + + Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "DatabaseName"); + if (databaseNameElement != null) { + String databaseNameInstance; + databaseNameInstance = databaseNameElement.getTextContent(); + serviceResourceInstance.setDatabaseName(databaseNameInstance); + } + + Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "PercentComplete"); + if (percentCompleteElement != null) { + int percentCompleteInstance; + percentCompleteInstance = DatatypeConverter.parseInt(percentCompleteElement.getTextContent()); + serviceResourceInstance.setPercentComplete(percentCompleteInstance); + } + + Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorCode"); + if (errorCodeElement != null) { + int errorCodeInstance; + errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent()); + serviceResourceInstance.setErrorCode(errorCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + String errorInstance; + errorInstance = errorElement.getTextContent(); + serviceResourceInstance.setError(errorInstance); + } + + Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorSeverity"); + if (errorSeverityElement != null) { + int errorSeverityInstance; + errorSeverityInstance = DatatypeConverter.parseInt(errorSeverityElement.getTextContent()); + serviceResourceInstance.setErrorSeverity(errorSeverityInstance); + } + + Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorState"); + if (errorStateElement != null) { + int errorStateInstance; + errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent()); + serviceResourceInstance.setErrorState(errorStateInstance); + } + + Element startTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); + if (startTimeElement != null) { + Calendar startTimeInstance; + startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); + serviceResourceInstance.setStartTime(startTimeInstance); + } + + Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "LastModifyTime"); + if (lastModifyTimeElement != null) { + Calendar lastModifyTimeInstance; + lastModifyTimeInstance = DatatypeConverter.parseDateTime(lastModifyTimeElement.getTextContent()); + serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperations.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperations.java new file mode 100644 index 0000000000000..5fe90edeaa93b --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperations.java @@ -0,0 +1,234 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseGetEventLogsParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseGetEventLogsResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseGetResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseListResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseUpdateParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseUpdateResponse; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for managing SQL +* Databases for a subscription. +*/ +public interface DatabaseOperations { + /** + * Creates a database in a SQL Server database server. + * + * @param serverName Required. The name of the SQL Server where the database + * will be created. + * @param parameters Required. The parameters for the create database + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the database create response. + */ + DatabaseCreateResponse create(String serverName, DatabaseCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Creates a database in a SQL Server database server. + * + * @param serverName Required. The name of the SQL Server where the database + * will be created. + * @param parameters Required. The parameters for the create database + * operation. + * @return Response containing the database create response. + */ + Future createAsync(String serverName, DatabaseCreateParameters parameters); + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server on which the database + * is found. + * @param databaseName Required. The name of the database to be deleted. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String serverName, String databaseName) throws IOException, ServiceException; + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server on which the database + * is found. + * @param databaseName Required. The name of the database to be deleted. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String serverName, String databaseName); + + /** + * Returns information about a SQL Server database. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the database get response. + */ + DatabaseGetResponse get(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns information about a SQL Server database. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @return Response containing the database get response. + */ + Future getAsync(String serverName, String databaseName); + + /** + * Returns information about a SQL Server database event logs. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the get event logs + * database operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + DatabaseGetEventLogsResponse getEventLogs(String serverName, String databaseName, DatabaseGetEventLogsParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns information about a SQL Server database event logs. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the get event logs + * database operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future getEventLogsAsync(String serverName, String databaseName, DatabaseGetEventLogsParameters parameters); + + /** + * Returns the list SQL Server databases. + * + * @param serverName Required. The name of the database server to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of databases for a given server. + */ + DatabaseListResponse list(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns the list SQL Server databases. + * + * @param serverName Required. The name of the database server to be queried. + * @return Response containing the list of databases for a given server. + */ + Future listAsync(String serverName); + + /** + * Updates SQL Server database information. + * + * @param serverName Required. The name of the SQL Server where the database + * is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the update database + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the database update response. + */ + DatabaseUpdateResponse update(String serverName, String databaseName, DatabaseUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Updates SQL Server database information. + * + * @param serverName Required. The name of the SQL Server where the database + * is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the update database + * operation. + * @return Response containing the database update response. + */ + Future updateAsync(String serverName, String databaseName, DatabaseUpdateParameters parameters); +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationsImpl.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationsImpl.java new file mode 100644 index 0000000000000..e6981e29d0687 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/DatabaseOperationsImpl.java @@ -0,0 +1,1567 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.Database; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseEventLog; +import com.microsoft.windowsazure.management.sql.models.DatabaseGetEventLogsParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseGetEventLogsResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseGetResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseListResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseUpdateParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseUpdateResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.TimeZone; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for managing SQL +* Databases for a subscription. +*/ +public class DatabaseOperationsImpl implements ServiceOperations, DatabaseOperations { + /** + * Initializes a new instance of the DatabaseOperationsImpl class. + * + * @param client Reference to the service client. + */ + DatabaseOperationsImpl(SqlManagementClientImpl client) { + this.client = client; + } + + private SqlManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.sql.SqlManagementClientImpl. + * @return The Client value. + */ + public SqlManagementClientImpl getClient() { + return this.client; + } + + /** + * Creates a database in a SQL Server database server. + * + * @param serverName Required. The name of the SQL Server where the database + * will be created. + * @param parameters Required. The parameters for the create database + * operation. + * @return Response containing the database create response. + */ + @Override + public Future createAsync(final String serverName, final DatabaseCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseCreateResponse call() throws Exception { + return create(serverName, parameters); + } + }); + } + + /** + * Creates a database in a SQL Server database server. + * + * @param serverName Required. The name of the SQL Server where the database + * will be created. + * @param parameters Required. The parameters for the create database + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the database create response. + */ + @Override + public DatabaseCreateResponse create(String serverName, DatabaseCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getEdition() == null) { + throw new NullPointerException("parameters.Edition"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databases"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); + requestDoc.appendChild(serviceResourceElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + serviceResourceElement.appendChild(nameElement); + + Element editionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Edition"); + editionElement.appendChild(requestDoc.createTextNode(parameters.getEdition())); + serviceResourceElement.appendChild(editionElement); + + Element maxSizeGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MaxSizeGB"); + maxSizeGBElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getMaximumDatabaseSizeInGB()))); + serviceResourceElement.appendChild(maxSizeGBElement); + + if (parameters.getCollationName() != null) { + Element collationNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CollationName"); + collationNameElement.appendChild(requestDoc.createTextNode(parameters.getCollationName())); + serviceResourceElement.appendChild(collationNameElement); + } + + if (parameters.getServiceObjectiveId() != null) { + Element serviceObjectiveIdElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId"); + serviceObjectiveIdElement.appendChild(requestDoc.createTextNode(parameters.getServiceObjectiveId())); + serviceResourceElement.appendChild(serviceObjectiveIdElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseCreateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseCreateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement2 != null) { + Database serviceResourceInstance = new Database(); + result.setDatabase(serviceResourceInstance); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + int idInstance; + idInstance = DatatypeConverter.parseInt(idElement.getTextContent()); + serviceResourceInstance.setId(idInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element editionElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Edition"); + if (editionElement2 != null) { + String editionInstance; + editionInstance = editionElement2.getTextContent(); + serviceResourceInstance.setEdition(editionInstance); + } + + Element maxSizeGBElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "MaxSizeGB"); + if (maxSizeGBElement2 != null) { + int maxSizeGBInstance; + maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement2.getTextContent()); + serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance); + } + + Element collationNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "CollationName"); + if (collationNameElement2 != null) { + String collationNameInstance; + collationNameInstance = collationNameElement2.getTextContent(); + serviceResourceInstance.setCollationName(collationNameInstance); + } + + Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "CreationDate"); + if (creationDateElement != null) { + Calendar creationDateInstance; + creationDateInstance = DatatypeConverter.parseDateTime(creationDateElement.getTextContent()); + serviceResourceInstance.setCreationDate(creationDateInstance); + } + + Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "IsFederationRoot"); + if (isFederationRootElement != null) { + boolean isFederationRootInstance; + isFederationRootInstance = DatatypeConverter.parseBoolean(isFederationRootElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsFederationRoot(isFederationRootInstance); + } + + Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "IsSystemObject"); + if (isSystemObjectElement != null) { + boolean isSystemObjectInstance; + isSystemObjectInstance = DatatypeConverter.parseBoolean(isSystemObjectElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsSystemObject(isSystemObjectInstance); + } + + Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SizeMB"); + if (sizeMBElement != null) { + String sizeMBInstance; + sizeMBInstance = sizeMBElement.getTextContent(); + serviceResourceInstance.setSizeMB(sizeMBInstance); + } + + Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorCode"); + if (serviceObjectiveAssignmentErrorCodeElement != null) { + String serviceObjectiveAssignmentErrorCodeInstance; + serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(serviceObjectiveAssignmentErrorCodeInstance); + } + + Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorDescription"); + if (serviceObjectiveAssignmentErrorDescriptionElement != null) { + String serviceObjectiveAssignmentErrorDescriptionInstance; + serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(serviceObjectiveAssignmentErrorDescriptionInstance); + } + + Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentState"); + if (serviceObjectiveAssignmentStateElement != null) { + String serviceObjectiveAssignmentStateInstance; + serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance); + } + + Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentStateDescription"); + if (serviceObjectiveAssignmentStateDescriptionElement != null) { + String serviceObjectiveAssignmentStateDescriptionInstance; + serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(serviceObjectiveAssignmentStateDescriptionInstance); + } + + Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentSuccessDate"); + if (serviceObjectiveAssignmentSuccessDateElement != null) { + String serviceObjectiveAssignmentSuccessDateInstance; + serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(serviceObjectiveAssignmentSuccessDateInstance); + } + + Element serviceObjectiveIdElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId"); + if (serviceObjectiveIdElement2 != null) { + String serviceObjectiveIdInstance; + serviceObjectiveIdInstance = serviceObjectiveIdElement2.getTextContent(); + serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server on which the database + * is found. + * @param databaseName Required. The name of the database to be deleted. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String serverName, final String databaseName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(serverName, databaseName); + } + }); + } + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server on which the database + * is found. + * @param databaseName Required. The name of the database to be deleted. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String serverName, String databaseName) throws IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (databaseName == null) { + throw new NullPointerException("databaseName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("databaseName", databaseName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databases/" + databaseName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns information about a SQL Server database. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @return Response containing the database get response. + */ + @Override + public Future getAsync(final String serverName, final String databaseName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseGetResponse call() throws Exception { + return get(serverName, databaseName); + } + }); + } + + /** + * Returns information about a SQL Server database. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the database get response. + */ + @Override + public DatabaseGetResponse get(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (databaseName == null) { + throw new NullPointerException("databaseName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("databaseName", databaseName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databases/" + databaseName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement != null) { + Database serviceResourceInstance = new Database(); + result.setDatabase(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + int idInstance; + idInstance = DatatypeConverter.parseInt(idElement.getTextContent()); + serviceResourceInstance.setId(idInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element editionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Edition"); + if (editionElement != null) { + String editionInstance; + editionInstance = editionElement.getTextContent(); + serviceResourceInstance.setEdition(editionInstance); + } + + Element maxSizeGBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "MaxSizeGB"); + if (maxSizeGBElement != null) { + int maxSizeGBInstance; + maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement.getTextContent()); + serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance); + } + + Element collationNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "CollationName"); + if (collationNameElement != null) { + String collationNameInstance; + collationNameInstance = collationNameElement.getTextContent(); + serviceResourceInstance.setCollationName(collationNameInstance); + } + + Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "CreationDate"); + if (creationDateElement != null) { + Calendar creationDateInstance; + creationDateInstance = DatatypeConverter.parseDateTime(creationDateElement.getTextContent()); + serviceResourceInstance.setCreationDate(creationDateInstance); + } + + Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsFederationRoot"); + if (isFederationRootElement != null) { + boolean isFederationRootInstance; + isFederationRootInstance = DatatypeConverter.parseBoolean(isFederationRootElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsFederationRoot(isFederationRootInstance); + } + + Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsSystemObject"); + if (isSystemObjectElement != null) { + boolean isSystemObjectInstance; + isSystemObjectInstance = DatatypeConverter.parseBoolean(isSystemObjectElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsSystemObject(isSystemObjectInstance); + } + + Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SizeMB"); + if (sizeMBElement != null) { + String sizeMBInstance; + sizeMBInstance = sizeMBElement.getTextContent(); + serviceResourceInstance.setSizeMB(sizeMBInstance); + } + + Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorCode"); + if (serviceObjectiveAssignmentErrorCodeElement != null) { + String serviceObjectiveAssignmentErrorCodeInstance; + serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(serviceObjectiveAssignmentErrorCodeInstance); + } + + Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorDescription"); + if (serviceObjectiveAssignmentErrorDescriptionElement != null) { + String serviceObjectiveAssignmentErrorDescriptionInstance; + serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(serviceObjectiveAssignmentErrorDescriptionInstance); + } + + Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentState"); + if (serviceObjectiveAssignmentStateElement != null) { + String serviceObjectiveAssignmentStateInstance; + serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance); + } + + Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentStateDescription"); + if (serviceObjectiveAssignmentStateDescriptionElement != null) { + String serviceObjectiveAssignmentStateDescriptionInstance; + serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(serviceObjectiveAssignmentStateDescriptionInstance); + } + + Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentSuccessDate"); + if (serviceObjectiveAssignmentSuccessDateElement != null) { + String serviceObjectiveAssignmentSuccessDateInstance; + serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(serviceObjectiveAssignmentSuccessDateInstance); + } + + Element serviceObjectiveIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId"); + if (serviceObjectiveIdElement != null) { + String serviceObjectiveIdInstance; + serviceObjectiveIdInstance = serviceObjectiveIdElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns information about a SQL Server database event logs. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the get event logs + * database operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future getEventLogsAsync(final String serverName, final String databaseName, final DatabaseGetEventLogsParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseGetEventLogsResponse call() throws Exception { + return getEventLogs(serverName, databaseName, parameters); + } + }); + } + + /** + * Returns information about a SQL Server database event logs. + * + * @param serverName Required. The name of the SQL Server on which the + * database is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the get event logs + * database operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public DatabaseGetEventLogsResponse getEventLogs(String serverName, String databaseName, DatabaseGetEventLogsParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (databaseName == null) { + throw new NullPointerException("databaseName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getEventTypes() == null) { + throw new NullPointerException("parameters.EventTypes"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("databaseName", databaseName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "getEventLogsAsync", tracingParameters); + } + + // Construct URL + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databases/" + databaseName.trim() + "/events" + "?"; + url = url + "startDate=" + URLEncoder.encode(simpleDateFormat.format(parameters.getStartDate().getTime()), "UTF-8"); + url = url + "&" + "intervalSizeInMinutes=" + URLEncoder.encode(Integer.toString(parameters.getIntervalSizeInMinutes()), "UTF-8"); + url = url + "&" + "eventTypes=" + URLEncoder.encode(parameters.getEventTypes().trim(), "UTF-8"); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseGetEventLogsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseGetEventLogsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResources"); + if (serviceResourcesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i1 = i1 + 1) { + org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i1)); + DatabaseEventLog serviceResourceInstance = new DatabaseEventLog(); + result.getEventLogs().add(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + String selfLinkInstance; + selfLinkInstance = selfLinkElement.getTextContent(); + serviceResourceInstance.setSelfLink(selfLinkInstance); + } + + Element parentLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement != null) { + String parentLinkInstance; + parentLinkInstance = parentLinkElement.getTextContent(); + serviceResourceInstance.setParentLink(parentLinkInstance); + } + + Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "DatabaseName"); + if (databaseNameElement != null) { + String databaseNameInstance; + databaseNameInstance = databaseNameElement.getTextContent(); + serviceResourceInstance.setDatabaseName(databaseNameInstance); + } + + Element startTimeUtcElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StartTimeUtc"); + if (startTimeUtcElement != null) { + Calendar startTimeUtcInstance; + startTimeUtcInstance = DatatypeConverter.parseDateTime(startTimeUtcElement.getTextContent()); + serviceResourceInstance.setStartTimeUtc(startTimeUtcInstance); + } + + Element intervalSizeInMinutesElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IntervalSizeInMinutes"); + if (intervalSizeInMinutesElement != null) { + int intervalSizeInMinutesInstance; + intervalSizeInMinutesInstance = DatatypeConverter.parseInt(intervalSizeInMinutesElement.getTextContent()); + serviceResourceInstance.setIntervalSizeInMinutes(intervalSizeInMinutesInstance); + } + + Element eventCategoryElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "EventCategory"); + if (eventCategoryElement != null) { + String eventCategoryInstance; + eventCategoryInstance = eventCategoryElement.getTextContent(); + serviceResourceInstance.setEventCategory(eventCategoryInstance); + } + + Element eventTypeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "EventType"); + if (eventTypeElement != null) { + String eventTypeInstance; + eventTypeInstance = eventTypeElement.getTextContent(); + serviceResourceInstance.setEventType(eventTypeInstance); + } + + Element eventSubtypeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "EventSubtype"); + if (eventSubtypeElement != null) { + String eventSubtypeInstance; + eventSubtypeInstance = eventSubtypeElement.getTextContent(); + serviceResourceInstance.setEventSubtype(eventSubtypeInstance); + } + + Element eventSubtypeDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "EventSubtypeDescription"); + if (eventSubtypeDescriptionElement != null) { + String eventSubtypeDescriptionInstance; + eventSubtypeDescriptionInstance = eventSubtypeDescriptionElement.getTextContent(); + serviceResourceInstance.setEventSubtypeDescription(eventSubtypeDescriptionInstance); + } + + Element numberOfEventsElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "NumberOfEvents"); + if (numberOfEventsElement != null) { + int numberOfEventsInstance; + numberOfEventsInstance = DatatypeConverter.parseInt(numberOfEventsElement.getTextContent()); + serviceResourceInstance.setNumberOfEvents(numberOfEventsInstance); + } + + Element severityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Severity"); + if (severityElement != null) { + int severityInstance; + severityInstance = DatatypeConverter.parseInt(severityElement.getTextContent()); + serviceResourceInstance.setSeverity(severityInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + serviceResourceInstance.setDescription(descriptionInstance); + } + + Element additionalDataElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "AdditionalData"); + if (additionalDataElement != null) { + boolean isNil = false; + Attr nilAttribute = additionalDataElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String additionalDataInstance; + additionalDataInstance = additionalDataElement.getTextContent(); + serviceResourceInstance.setAdditionalData(additionalDataInstance); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns the list SQL Server databases. + * + * @param serverName Required. The name of the database server to be queried. + * @return Response containing the list of databases for a given server. + */ + @Override + public Future listAsync(final String serverName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseListResponse call() throws Exception { + return list(serverName); + } + }); + } + + /** + * Returns the list SQL Server databases. + * + * @param serverName Required. The name of the database server to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of databases for a given server. + */ + @Override + public DatabaseListResponse list(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databases" + "?" + "contentview=generic"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResources"); + if (serviceResourcesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i1 = i1 + 1) { + org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i1)); + Database serviceResourceInstance = new Database(); + result.getDatabases().add(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + int idInstance; + idInstance = DatatypeConverter.parseInt(idElement.getTextContent()); + serviceResourceInstance.setId(idInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element editionElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Edition"); + if (editionElement != null) { + String editionInstance; + editionInstance = editionElement.getTextContent(); + serviceResourceInstance.setEdition(editionInstance); + } + + Element maxSizeGBElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "MaxSizeGB"); + if (maxSizeGBElement != null) { + int maxSizeGBInstance; + maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement.getTextContent()); + serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance); + } + + Element collationNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "CollationName"); + if (collationNameElement != null) { + String collationNameInstance; + collationNameInstance = collationNameElement.getTextContent(); + serviceResourceInstance.setCollationName(collationNameInstance); + } + + Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "CreationDate"); + if (creationDateElement != null) { + Calendar creationDateInstance; + creationDateInstance = DatatypeConverter.parseDateTime(creationDateElement.getTextContent()); + serviceResourceInstance.setCreationDate(creationDateInstance); + } + + Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsFederationRoot"); + if (isFederationRootElement != null) { + boolean isFederationRootInstance; + isFederationRootInstance = DatatypeConverter.parseBoolean(isFederationRootElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsFederationRoot(isFederationRootInstance); + } + + Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsSystemObject"); + if (isSystemObjectElement != null) { + boolean isSystemObjectInstance; + isSystemObjectInstance = DatatypeConverter.parseBoolean(isSystemObjectElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsSystemObject(isSystemObjectInstance); + } + + Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SizeMB"); + if (sizeMBElement != null) { + String sizeMBInstance; + sizeMBInstance = sizeMBElement.getTextContent(); + serviceResourceInstance.setSizeMB(sizeMBInstance); + } + + Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorCode"); + if (serviceObjectiveAssignmentErrorCodeElement != null) { + String serviceObjectiveAssignmentErrorCodeInstance; + serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(serviceObjectiveAssignmentErrorCodeInstance); + } + + Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorDescription"); + if (serviceObjectiveAssignmentErrorDescriptionElement != null) { + String serviceObjectiveAssignmentErrorDescriptionInstance; + serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(serviceObjectiveAssignmentErrorDescriptionInstance); + } + + Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentState"); + if (serviceObjectiveAssignmentStateElement != null) { + String serviceObjectiveAssignmentStateInstance; + serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance); + } + + Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentStateDescription"); + if (serviceObjectiveAssignmentStateDescriptionElement != null) { + String serviceObjectiveAssignmentStateDescriptionInstance; + serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(serviceObjectiveAssignmentStateDescriptionInstance); + } + + Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentSuccessDate"); + if (serviceObjectiveAssignmentSuccessDateElement != null) { + String serviceObjectiveAssignmentSuccessDateInstance; + serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(serviceObjectiveAssignmentSuccessDateInstance); + } + + Element serviceObjectiveIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId"); + if (serviceObjectiveIdElement != null) { + String serviceObjectiveIdInstance; + serviceObjectiveIdInstance = serviceObjectiveIdElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Updates SQL Server database information. + * + * @param serverName Required. The name of the SQL Server where the database + * is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the update database + * operation. + * @return Response containing the database update response. + */ + @Override + public Future updateAsync(final String serverName, final String databaseName, final DatabaseUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public DatabaseUpdateResponse call() throws Exception { + return update(serverName, databaseName, parameters); + } + }); + } + + /** + * Updates SQL Server database information. + * + * @param serverName Required. The name of the SQL Server where the database + * is housed. + * @param databaseName Required. The name of the SQL Server database to be + * obtained. + * @param parameters Required. The parameters for the update database + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the database update response. + */ + @Override + public DatabaseUpdateResponse update(String serverName, String databaseName, DatabaseUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (databaseName == null) { + throw new NullPointerException("databaseName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getCollationName() == null) { + throw new NullPointerException("parameters.CollationName"); + } + if (parameters.getEdition() == null) { + throw new NullPointerException("parameters.Edition"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("databaseName", databaseName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/databases/" + databaseName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); + requestDoc.appendChild(serviceResourceElement); + + if (parameters.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + serviceResourceElement.appendChild(nameElement); + } + + Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); + idElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getId()))); + serviceResourceElement.appendChild(idElement); + + Element editionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Edition"); + editionElement.appendChild(requestDoc.createTextNode(parameters.getEdition())); + serviceResourceElement.appendChild(editionElement); + + Element maxSizeGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MaxSizeGB"); + maxSizeGBElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getMaximumDatabaseSizeInGB()))); + serviceResourceElement.appendChild(maxSizeGBElement); + + Element collationNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CollationName"); + collationNameElement.appendChild(requestDoc.createTextNode(parameters.getCollationName())); + serviceResourceElement.appendChild(collationNameElement); + + if (parameters.getServiceObjectiveId() != null) { + Element serviceObjectiveIdElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId"); + serviceObjectiveIdElement.appendChild(requestDoc.createTextNode(parameters.getServiceObjectiveId())); + serviceResourceElement.appendChild(serviceObjectiveIdElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + DatabaseUpdateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new DatabaseUpdateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement2 != null) { + Database serviceResourceInstance = new Database(); + result.setDatabase(serviceResourceInstance); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element idElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement2 != null) { + int idInstance; + idInstance = DatatypeConverter.parseInt(idElement2.getTextContent()); + serviceResourceInstance.setId(idInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element editionElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Edition"); + if (editionElement2 != null) { + String editionInstance; + editionInstance = editionElement2.getTextContent(); + serviceResourceInstance.setEdition(editionInstance); + } + + Element maxSizeGBElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "MaxSizeGB"); + if (maxSizeGBElement2 != null) { + int maxSizeGBInstance; + maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement2.getTextContent()); + serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance); + } + + Element collationNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "CollationName"); + if (collationNameElement2 != null) { + String collationNameInstance; + collationNameInstance = collationNameElement2.getTextContent(); + serviceResourceInstance.setCollationName(collationNameInstance); + } + + Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "CreationDate"); + if (creationDateElement != null) { + Calendar creationDateInstance; + creationDateInstance = DatatypeConverter.parseDateTime(creationDateElement.getTextContent()); + serviceResourceInstance.setCreationDate(creationDateInstance); + } + + Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "IsFederationRoot"); + if (isFederationRootElement != null) { + boolean isFederationRootInstance; + isFederationRootInstance = DatatypeConverter.parseBoolean(isFederationRootElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsFederationRoot(isFederationRootInstance); + } + + Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "IsSystemObject"); + if (isSystemObjectElement != null) { + boolean isSystemObjectInstance; + isSystemObjectInstance = DatatypeConverter.parseBoolean(isSystemObjectElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsSystemObject(isSystemObjectInstance); + } + + Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SizeMB"); + if (sizeMBElement != null) { + String sizeMBInstance; + sizeMBInstance = sizeMBElement.getTextContent(); + serviceResourceInstance.setSizeMB(sizeMBInstance); + } + + Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorCode"); + if (serviceObjectiveAssignmentErrorCodeElement != null) { + String serviceObjectiveAssignmentErrorCodeInstance; + serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(serviceObjectiveAssignmentErrorCodeInstance); + } + + Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorDescription"); + if (serviceObjectiveAssignmentErrorDescriptionElement != null) { + String serviceObjectiveAssignmentErrorDescriptionInstance; + serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(serviceObjectiveAssignmentErrorDescriptionInstance); + } + + Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentState"); + if (serviceObjectiveAssignmentStateElement != null) { + String serviceObjectiveAssignmentStateInstance; + serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance); + } + + Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentStateDescription"); + if (serviceObjectiveAssignmentStateDescriptionElement != null) { + String serviceObjectiveAssignmentStateDescriptionInstance; + serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(serviceObjectiveAssignmentStateDescriptionInstance); + } + + Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentSuccessDate"); + if (serviceObjectiveAssignmentSuccessDateElement != null) { + String serviceObjectiveAssignmentSuccessDateInstance; + serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement.getTextContent(); + serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(serviceObjectiveAssignmentSuccessDateInstance); + } + + Element serviceObjectiveIdElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId"); + if (serviceObjectiveIdElement2 != null) { + String serviceObjectiveIdInstance; + serviceObjectiveIdInstance = serviceObjectiveIdElement2.getTextContent(); + serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/Exports.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/Exports.java new file mode 100644 index 0000000000000..af13c18201f09 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/Exports.java @@ -0,0 +1,31 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.Builder; + +/** + * The Class Exports. + */ +public class Exports implements Builder.Exports { + /* (non-Javadoc) + * @see com.microsoft.windowsazure.services.core.Builder.Exports#register(com.microsoft.windowsazure.services.core.Builder.Registry) + */ + @Override + public void register(Builder.Registry registry) { + // provide contract implementation + registry.add(SqlManagementClient.class, SqlManagementClientImpl.class); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperations.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperations.java new file mode 100644 index 0000000000000..6b33c3a4a9e2b --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperations.java @@ -0,0 +1,231 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleCreateParameters; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleCreateResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleGetResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleListResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleUpdateParameters; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleUpdateResponse; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Windows Azure SQL Database Management API includes operations for +* managing the server-level firewall rules for SQL Database servers.You cannot +* manage the database-level firewall rules using the Windows Azure SQL +* Database Management API; they can only be managed by running the +* Transact-SQL statements against the master or individual user databases. +* (see http://msdn.microsoft.com/en-us/library/windowsazure/gg715276.aspx for +* more information) +*/ +public interface FirewallRuleOperations { + /** + * Adds a new server-level firewall rule for a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param parameters Required. Parameters for the Create Firewall Rule + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the firewall rule create response. + */ + FirewallRuleCreateResponse create(String serverName, FirewallRuleCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Adds a new server-level firewall rule for a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param parameters Required. Parameters for the Create Firewall Rule + * operation. + * @return Response containing the firewall rule create response. + */ + Future createAsync(String serverName, FirewallRuleCreateParameters parameters); + + /** + * Deletes a server-level firewall rule from a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715277.aspx for + * more information) + * + * @param serverName Required. The name of the server that will be have new + * firewall rule applied to it. + * @param ruleName Required. The name of the new firewall rule. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String serverName, String ruleName) throws IOException, ServiceException; + + /** + * Deletes a server-level firewall rule from a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715277.aspx for + * more information) + * + * @param serverName Required. The name of the server that will be have new + * firewall rule applied to it. + * @param ruleName Required. The name of the new firewall rule. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String serverName, String ruleName); + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @param ruleName Required. The name of the rule for which the call is + * being made. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + FirewallRuleGetResponse get(String serverName, String ruleName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @param ruleName Required. The name of the rule for which the call is + * being made. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future getAsync(String serverName, String ruleName); + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + FirewallRuleListResponse list(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future listAsync(String serverName); + + /** + * Updates an existing server-level firewall rule for a SQL Database server + * that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param ruleName Required. The name of the firewall rule to be updated. + * @param parameters Required. Parameters for the Update Firewall Rule + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the firewall rule update response. + */ + FirewallRuleUpdateResponse update(String serverName, String ruleName, FirewallRuleUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Updates an existing server-level firewall rule for a SQL Database server + * that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param ruleName Required. The name of the firewall rule to be updated. + * @param parameters Required. Parameters for the Update Firewall Rule + * operation. + * @return Response containing the firewall rule update response. + */ + Future updateAsync(String serverName, String ruleName, FirewallRuleUpdateParameters parameters); +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperationsImpl.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperationsImpl.java new file mode 100644 index 0000000000000..3324bd59ff350 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperationsImpl.java @@ -0,0 +1,942 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.FirewallRule; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleCreateParameters; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleCreateResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleGetResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleListResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleUpdateParameters; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleUpdateResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Windows Azure SQL Database Management API includes operations for +* managing the server-level firewall rules for SQL Database servers.You cannot +* manage the database-level firewall rules using the Windows Azure SQL +* Database Management API; they can only be managed by running the +* Transact-SQL statements against the master or individual user databases. +* (see http://msdn.microsoft.com/en-us/library/windowsazure/gg715276.aspx for +* more information) +*/ +public class FirewallRuleOperationsImpl implements ServiceOperations, FirewallRuleOperations { + /** + * Initializes a new instance of the FirewallRuleOperationsImpl class. + * + * @param client Reference to the service client. + */ + FirewallRuleOperationsImpl(SqlManagementClientImpl client) { + this.client = client; + } + + private SqlManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.sql.SqlManagementClientImpl. + * @return The Client value. + */ + public SqlManagementClientImpl getClient() { + return this.client; + } + + /** + * Adds a new server-level firewall rule for a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param parameters Required. Parameters for the Create Firewall Rule + * operation. + * @return Response containing the firewall rule create response. + */ + @Override + public Future createAsync(final String serverName, final FirewallRuleCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public FirewallRuleCreateResponse call() throws Exception { + return create(serverName, parameters); + } + }); + } + + /** + * Adds a new server-level firewall rule for a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param parameters Required. Parameters for the Create Firewall Rule + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the firewall rule create response. + */ + @Override + public FirewallRuleCreateResponse create(String serverName, FirewallRuleCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getEndIPAddress() == null) { + throw new NullPointerException("parameters.EndIPAddress"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + if (parameters.getStartIPAddress() == null) { + throw new NullPointerException("parameters.StartIPAddress"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/firewallrules"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); + requestDoc.appendChild(serviceResourceElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + serviceResourceElement.appendChild(nameElement); + + Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StartIPAddress"); + startIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress())); + serviceResourceElement.appendChild(startIPAddressElement); + + Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EndIPAddress"); + endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress())); + serviceResourceElement.appendChild(endIPAddressElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + FirewallRuleCreateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new FirewallRuleCreateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement2 != null) { + FirewallRule serviceResourceInstance = new FirewallRule(); + result.setFirewallRule(serviceResourceInstance); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "StartIPAddress"); + if (startIPAddressElement2 != null) { + InetAddress startIPAddressInstance; + startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent()); + serviceResourceInstance.setStartIPAddress(startIPAddressInstance); + } + + Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "EndIPAddress"); + if (endIPAddressElement2 != null) { + InetAddress endIPAddressInstance; + endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent()); + serviceResourceInstance.setEndIPAddress(endIPAddressInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Deletes a server-level firewall rule from a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715277.aspx for + * more information) + * + * @param serverName Required. The name of the server that will be have new + * firewall rule applied to it. + * @param ruleName Required. The name of the new firewall rule. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String serverName, final String ruleName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(serverName, ruleName); + } + }); + } + + /** + * Deletes a server-level firewall rule from a SQL Database server that + * belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715277.aspx for + * more information) + * + * @param serverName Required. The name of the server that will be have new + * firewall rule applied to it. + * @param ruleName Required. The name of the new firewall rule. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String serverName, String ruleName) throws IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (ruleName == null) { + throw new NullPointerException("ruleName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("ruleName", ruleName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/firewallrules/" + ruleName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @param ruleName Required. The name of the rule for which the call is + * being made. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future getAsync(final String serverName, final String ruleName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public FirewallRuleGetResponse call() throws Exception { + return get(serverName, ruleName); + } + }); + } + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @param ruleName Required. The name of the rule for which the call is + * being made. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public FirewallRuleGetResponse get(String serverName, String ruleName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (ruleName == null) { + throw new NullPointerException("ruleName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("ruleName", ruleName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/firewallrules/" + ruleName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + FirewallRuleGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new FirewallRuleGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement != null) { + FirewallRule serviceResourceInstance = new FirewallRule(); + result.setFirewallRule(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element startIPAddressElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "StartIPAddress"); + if (startIPAddressElement != null) { + InetAddress startIPAddressInstance; + startIPAddressInstance = InetAddress.getByName(startIPAddressElement.getTextContent()); + serviceResourceInstance.setStartIPAddress(startIPAddressInstance); + } + + Element endIPAddressElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "EndIPAddress"); + if (endIPAddressElement != null) { + InetAddress endIPAddressInstance; + endIPAddressInstance = InetAddress.getByName(endIPAddressElement.getTextContent()); + serviceResourceInstance.setEndIPAddress(endIPAddressInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future listAsync(final String serverName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public FirewallRuleListResponse call() throws Exception { + return list(serverName); + } + }); + } + + /** + * Returns a list of all the server-level firewall rules for a SQL Database + * server that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715278.aspx for + * more information) + * + * @param serverName Required. The name of the server for which the call is + * being made. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public FirewallRuleListResponse list(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/firewallrules"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + FirewallRuleListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new FirewallRuleListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResources"); + if (serviceResourcesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i1 = i1 + 1) { + org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i1)); + FirewallRule serviceResourceInstance = new FirewallRule(); + result.getFirewallRules().add(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element startIPAddressElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StartIPAddress"); + if (startIPAddressElement != null) { + InetAddress startIPAddressInstance; + startIPAddressInstance = InetAddress.getByName(startIPAddressElement.getTextContent()); + serviceResourceInstance.setStartIPAddress(startIPAddressInstance); + } + + Element endIPAddressElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "EndIPAddress"); + if (endIPAddressElement != null) { + InetAddress endIPAddressInstance; + endIPAddressInstance = InetAddress.getByName(endIPAddressElement.getTextContent()); + serviceResourceInstance.setEndIPAddress(endIPAddressInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Updates an existing server-level firewall rule for a SQL Database server + * that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param ruleName Required. The name of the firewall rule to be updated. + * @param parameters Required. Parameters for the Update Firewall Rule + * operation. + * @return Response containing the firewall rule update response. + */ + @Override + public Future updateAsync(final String serverName, final String ruleName, final FirewallRuleUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public FirewallRuleUpdateResponse call() throws Exception { + return update(serverName, ruleName, parameters); + } + }); + } + + /** + * Updates an existing server-level firewall rule for a SQL Database server + * that belongs to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715280.aspx for + * more information) + * + * @param serverName Required. The name of the SQL database server to which + * this rule will be applied. + * @param ruleName Required. The name of the firewall rule to be updated. + * @param parameters Required. Parameters for the Update Firewall Rule + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return Response containing the firewall rule update response. + */ + @Override + public FirewallRuleUpdateResponse update(String serverName, String ruleName, FirewallRuleUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (ruleName == null) { + throw new NullPointerException("ruleName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getEndIPAddress() == null) { + throw new NullPointerException("parameters.EndIPAddress"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + if (parameters.getStartIPAddress() == null) { + throw new NullPointerException("parameters.StartIPAddress"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("ruleName", ruleName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/firewallrules/" + ruleName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); + requestDoc.appendChild(serviceResourceElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + serviceResourceElement.appendChild(nameElement); + + Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StartIPAddress"); + startIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress())); + serviceResourceElement.appendChild(startIPAddressElement); + + Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EndIPAddress"); + endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress())); + serviceResourceElement.appendChild(endIPAddressElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + FirewallRuleUpdateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new FirewallRuleUpdateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement2 != null) { + FirewallRule serviceResourceInstance = new FirewallRule(); + result.setFirewallRule(serviceResourceInstance); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "StartIPAddress"); + if (startIPAddressElement2 != null) { + InetAddress startIPAddressInstance; + startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent()); + serviceResourceInstance.setStartIPAddress(startIPAddressInstance); + } + + Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "EndIPAddress"); + if (endIPAddressElement2 != null) { + InetAddress endIPAddressInstance; + endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent()); + serviceResourceInstance.setEndIPAddress(endIPAddressInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServerOperations.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServerOperations.java new file mode 100644 index 0000000000000..45301ebd8e0e8 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServerOperations.java @@ -0,0 +1,168 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.ServerChangeAdministratorPasswordParameters; +import com.microsoft.windowsazure.management.sql.models.ServerCreateParameters; +import com.microsoft.windowsazure.management.sql.models.ServerCreateResponse; +import com.microsoft.windowsazure.management.sql.models.ServerListResponse; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for managing SQL Database +* servers for a subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg715271.aspx for more +* information) +*/ +public interface ServerOperations { + /** + * Sets the administrative password of a SQL Database server for a + * subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715272.aspx for + * more information) + * + * @param serverName Required. The server that will have the change made to + * the administrative user. + * @param parameters Required. Parameters for the Manage Administrator + * Password operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse changeAdministratorPassword(String serverName, ServerChangeAdministratorPasswordParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Sets the administrative password of a SQL Database server for a + * subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715272.aspx for + * more information) + * + * @param serverName Required. The server that will have the change made to + * the administrative user. + * @param parameters Required. Parameters for the Manage Administrator + * Password operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future changeAdministratorPasswordAsync(String serverName, ServerChangeAdministratorPasswordParameters parameters); + + /** + * Adds a new SQL Database server to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715274.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Server + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The response returned from the Create Server operation. + */ + ServerCreateResponse create(ServerCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Adds a new SQL Database server to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715274.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Server + * operation. + * @return The response returned from the Create Server operation. + */ + Future createAsync(ServerCreateParameters parameters); + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server to be deleted. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String serverName) throws IOException, ServiceException; + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server to be deleted. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String serverName); + + /** + * Returns all SQL Database servers that are provisioned for a subscription. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg715269.aspx + * for more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response structure for the Server List operation. + */ + ServerListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns all SQL Database servers that are provisioned for a subscription. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg715269.aspx + * for more information) + * + * @return The response structure for the Server List operation. + */ + Future listAsync(); +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServerOperationsImpl.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServerOperationsImpl.java new file mode 100644 index 0000000000000..3aad245740a20 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServerOperationsImpl.java @@ -0,0 +1,654 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.Server; +import com.microsoft.windowsazure.management.sql.models.ServerChangeAdministratorPasswordParameters; +import com.microsoft.windowsazure.management.sql.models.ServerCreateParameters; +import com.microsoft.windowsazure.management.sql.models.ServerCreateResponse; +import com.microsoft.windowsazure.management.sql.models.ServerListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for managing SQL Database +* servers for a subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg715271.aspx for more +* information) +*/ +public class ServerOperationsImpl implements ServiceOperations, ServerOperations { + /** + * Initializes a new instance of the ServerOperationsImpl class. + * + * @param client Reference to the service client. + */ + ServerOperationsImpl(SqlManagementClientImpl client) { + this.client = client; + } + + private SqlManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.sql.SqlManagementClientImpl. + * @return The Client value. + */ + public SqlManagementClientImpl getClient() { + return this.client; + } + + /** + * Sets the administrative password of a SQL Database server for a + * subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715272.aspx for + * more information) + * + * @param serverName Required. The server that will have the change made to + * the administrative user. + * @param parameters Required. Parameters for the Manage Administrator + * Password operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future changeAdministratorPasswordAsync(final String serverName, final ServerChangeAdministratorPasswordParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return changeAdministratorPassword(serverName, parameters); + } + }); + } + + /** + * Sets the administrative password of a SQL Database server for a + * subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715272.aspx for + * more information) + * + * @param serverName Required. The server that will have the change made to + * the administrative user. + * @param parameters Required. Parameters for the Manage Administrator + * Password operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse changeAdministratorPassword(String serverName, ServerChangeAdministratorPasswordParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getNewPassword() == null) { + throw new NullPointerException("parameters.NewPassword"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "changeAdministratorPasswordAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "?" + "op=ResetPassword"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element administratorLoginPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword"); + requestDoc.appendChild(administratorLoginPasswordElement); + + administratorLoginPasswordElement.appendChild(requestDoc.createTextNode(parameters.getNewPassword())); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Adds a new SQL Database server to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715274.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Server + * operation. + * @return The response returned from the Create Server operation. + */ + @Override + public Future createAsync(final ServerCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServerCreateResponse call() throws Exception { + return create(parameters); + } + }); + } + + /** + * Adds a new SQL Database server to a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715274.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Server + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The response returned from the Create Server operation. + */ + @Override + public ServerCreateResponse create(ServerCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getAdministratorPassword() == null) { + throw new NullPointerException("parameters.AdministratorPassword"); + } + if (parameters.getAdministratorUserName() == null) { + throw new NullPointerException("parameters.AdministratorUserName"); + } + if (parameters.getLocation() == null) { + throw new NullPointerException("parameters.Location"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element serverElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "Server"); + requestDoc.appendChild(serverElement); + + Element administratorLoginElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLogin"); + administratorLoginElement.appendChild(requestDoc.createTextNode(parameters.getAdministratorUserName())); + serverElement.appendChild(administratorLoginElement); + + Element administratorLoginPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword"); + administratorLoginPasswordElement.appendChild(requestDoc.createTextNode(parameters.getAdministratorPassword())); + serverElement.appendChild(administratorLoginPasswordElement); + + Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "Location"); + locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation())); + serverElement.appendChild(locationElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServerCreateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServerCreateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element serverNameElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/sqlazure/2010/12/", "ServerName"); + if (serverNameElement != null) { + result.setServerName(serverNameElement.getTextContent()); + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server to be deleted. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String serverName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(serverName); + } + }); + } + + /** + * Drops a SQL Database server from a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx for + * more information) + * + * @param serverName Required. The name of the server to be deleted. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String serverName) throws IOException, ServiceException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns all SQL Database servers that are provisioned for a subscription. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg715269.aspx + * for more information) + * + * @return The response structure for the Server List operation. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServerListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * Returns all SQL Database servers that are provisioned for a subscription. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg715269.aspx + * for more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response structure for the Server List operation. + */ + @Override + public ServerListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServerListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServerListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serversSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/sqlazure/2010/12/", "Servers"); + if (serversSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serversSequenceElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Server").size(); i1 = i1 + 1) { + org.w3c.dom.Element serversElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serversSequenceElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Server").get(i1)); + Server serverInstance = new Server(); + result.getServers().add(serverInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serversElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serverInstance.setName(nameInstance); + } + + Element administratorLoginElement = XmlUtility.getElementByTagNameNS(serversElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLogin"); + if (administratorLoginElement != null) { + String administratorLoginInstance; + administratorLoginInstance = administratorLoginElement.getTextContent(); + serverInstance.setAdministratorUserName(administratorLoginInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(serversElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + serverInstance.setLocation(locationInstance); + } + + Element featuresSequenceElement = XmlUtility.getElementByTagNameNS(serversElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Features"); + if (featuresSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(featuresSequenceElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Feature").size(); i2 = i2 + 1) { + org.w3c.dom.Element featuresElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(featuresSequenceElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Feature").get(i2)); + String featuresKey = XmlUtility.getElementByTagNameNS(featuresElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Name").getTextContent(); + String featuresValue = XmlUtility.getElementByTagNameNS(featuresElement, "http://schemas.microsoft.com/sqlazure/2010/12/", "Value").getTextContent(); + serverInstance.getFeatures().put(featuresKey, featuresValue); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveOperations.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveOperations.java new file mode 100644 index 0000000000000..b79fed7f58bc0 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveOperations.java @@ -0,0 +1,94 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.ServiceObjectiveGetResponse; +import com.microsoft.windowsazure.management.sql.models.ServiceObjectiveListResponse; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for getting Service +* Objective for a subscription. +*/ +public interface ServiceObjectiveOperations { + /** + * Returns information about a certain Service Objective on a given Id. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param serviceObjectiveId Required. The Id of the Service Objective to be + * obtained. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the service objective for a given server and + * service objective Id. + */ + ServiceObjectiveGetResponse get(String serverName, String serviceObjectiveId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns information about a certain Service Objective on a given Id. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param serviceObjectiveId Required. The Id of the Service Objective to be + * obtained. + * @return Response containing the service objective for a given server and + * service objective Id. + */ + Future getAsync(String serverName, String serviceObjectiveId); + + /** + * Returns information about all Service Objectives on a database server. + * + * @param serverName Required. The name of the database server to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of service objective for a given + * server. + */ + ServiceObjectiveListResponse list(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Returns information about all Service Objectives on a database server. + * + * @param serverName Required. The name of the database server to be queried. + * @return Response containing the list of service objective for a given + * server. + */ + Future listAsync(String serverName); +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveOperationsImpl.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveOperationsImpl.java new file mode 100644 index 0000000000000..6192b77d4d9ba --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveOperationsImpl.java @@ -0,0 +1,605 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.ServiceObjective; +import com.microsoft.windowsazure.management.sql.models.ServiceObjectiveGetResponse; +import com.microsoft.windowsazure.management.sql.models.ServiceObjectiveListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The SQL Database Management API includes operations for getting Service +* Objective for a subscription. +*/ +public class ServiceObjectiveOperationsImpl implements ServiceOperations, ServiceObjectiveOperations { + /** + * Initializes a new instance of the ServiceObjectiveOperationsImpl class. + * + * @param client Reference to the service client. + */ + ServiceObjectiveOperationsImpl(SqlManagementClientImpl client) { + this.client = client; + } + + private SqlManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.sql.SqlManagementClientImpl. + * @return The Client value. + */ + public SqlManagementClientImpl getClient() { + return this.client; + } + + /** + * Returns information about a certain Service Objective on a given Id. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param serviceObjectiveId Required. The Id of the Service Objective to be + * obtained. + * @return Response containing the service objective for a given server and + * service objective Id. + */ + @Override + public Future getAsync(final String serverName, final String serviceObjectiveId) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServiceObjectiveGetResponse call() throws Exception { + return get(serverName, serviceObjectiveId); + } + }); + } + + /** + * Returns information about a certain Service Objective on a given Id. + * + * @param serverName Required. The name of the SQL Server to be queried. + * @param serviceObjectiveId Required. The Id of the Service Objective to be + * obtained. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the service objective for a given server and + * service objective Id. + */ + @Override + public ServiceObjectiveGetResponse get(String serverName, String serviceObjectiveId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + if (serviceObjectiveId == null) { + throw new NullPointerException("serviceObjectiveId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + tracingParameters.put("serviceObjectiveId", serviceObjectiveId); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/serviceobjectives/" + serviceObjectiveId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServiceObjectiveGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServiceObjectiveGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); + if (serviceResourceElement != null) { + ServiceObjective serviceResourceInstance = new ServiceObjective(); + result.setServiceObjective(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + String selfLinkInstance; + selfLinkInstance = selfLinkElement.getTextContent(); + serviceResourceInstance.setSelfLink(selfLinkInstance); + } + + Element parentLinkElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement != null) { + String parentLinkInstance; + parentLinkInstance = parentLinkElement.getTextContent(); + serviceResourceInstance.setParentLink(parentLinkInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + serviceResourceInstance.setId(idInstance); + } + + Element isDefaultElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsDefault"); + if (isDefaultElement != null) { + boolean isDefaultInstance; + isDefaultInstance = DatatypeConverter.parseBoolean(isDefaultElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsDefault(isDefaultInstance); + } + + Element isSystemElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsSystem"); + if (isSystemElement != null) { + boolean isSystemInstance; + isSystemInstance = DatatypeConverter.parseBoolean(isSystemElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsSystem(isSystemInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + serviceResourceInstance.setDescription(descriptionInstance); + } + + Element enabledElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Enabled"); + if (enabledElement != null) { + boolean enabledInstance; + enabledInstance = DatatypeConverter.parseBoolean(enabledElement.getTextContent().toLowerCase()); + serviceResourceInstance.setEnabled(enabledInstance); + } + + Element dimensionSettingsSequenceElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "DimensionSettings"); + if (dimensionSettingsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dimensionSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i1 = i1 + 1) { + org.w3c.dom.Element dimensionSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dimensionSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i1)); + ServiceObjective.DimensionSettingResponse serviceResourceInstance2 = new ServiceObjective.DimensionSettingResponse(); + serviceResourceInstance.getDimensionSettings().add(serviceResourceInstance2); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + serviceResourceInstance2.setName(nameInstance2); + } + + Element typeElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement2 != null) { + String typeInstance2; + typeInstance2 = typeElement2.getTextContent(); + serviceResourceInstance2.setType(typeInstance2); + } + + Element stateElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement2 != null) { + String stateInstance2; + stateInstance2 = stateElement2.getTextContent(); + serviceResourceInstance2.setState(stateInstance2); + } + + Element selfLinkElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement2 != null) { + String selfLinkInstance2; + selfLinkInstance2 = selfLinkElement2.getTextContent(); + serviceResourceInstance2.setSelfLink(selfLinkInstance2); + } + + Element parentLinkElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement2 != null) { + String parentLinkInstance2; + parentLinkInstance2 = parentLinkElement2.getTextContent(); + serviceResourceInstance2.setParentLink(parentLinkInstance2); + } + + Element idElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement2 != null) { + String idInstance2; + idInstance2 = idElement2.getTextContent(); + serviceResourceInstance2.setId(idInstance2); + } + + Element descriptionElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement2 != null) { + String descriptionInstance2; + descriptionInstance2 = descriptionElement2.getTextContent(); + serviceResourceInstance2.setDescription(descriptionInstance2); + } + + Element ordinalElement = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Ordinal"); + if (ordinalElement != null) { + byte ordinalInstance; + ordinalInstance = DatatypeConverter.parseByte(ordinalElement.getTextContent()); + serviceResourceInstance2.setOrdinal(ordinalInstance); + } + + Element isDefaultElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "IsDefault"); + if (isDefaultElement2 != null) { + boolean isDefaultInstance2; + isDefaultInstance2 = DatatypeConverter.parseBoolean(isDefaultElement2.getTextContent().toLowerCase()); + serviceResourceInstance2.setIsDefault(isDefaultInstance2); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Returns information about all Service Objectives on a database server. + * + * @param serverName Required. The name of the database server to be queried. + * @return Response containing the list of service objective for a given + * server. + */ + @Override + public Future listAsync(final String serverName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServiceObjectiveListResponse call() throws Exception { + return list(serverName); + } + }); + } + + /** + * Returns information about all Service Objectives on a database server. + * + * @param serverName Required. The name of the database server to be queried. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return Response containing the list of service objective for a given + * server. + */ + @Override + public ServiceObjectiveListResponse list(String serverName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (serverName == null) { + throw new NullPointerException("serverName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("serverName", serverName); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = this.getClient().getCredentials().getSubscriptionId().trim() + "/services/sqlservers/servers/" + serverName.trim() + "/serviceobjectives"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServiceObjectiveListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServiceObjectiveListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResources"); + if (serviceResourcesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i1 = i1 + 1) { + org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serviceResourcesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i1)); + ServiceObjective serviceResourceInstance = new ServiceObjective(); + result.getServiceObjectives().add(serviceResourceInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serviceResourceInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + serviceResourceInstance.setType(typeInstance); + } + + Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + serviceResourceInstance.setState(stateInstance); + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + String selfLinkInstance; + selfLinkInstance = selfLinkElement.getTextContent(); + serviceResourceInstance.setSelfLink(selfLinkInstance); + } + + Element parentLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement != null) { + String parentLinkInstance; + parentLinkInstance = parentLinkElement.getTextContent(); + serviceResourceInstance.setParentLink(parentLinkInstance); + } + + Element idElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + serviceResourceInstance.setId(idInstance); + } + + Element isDefaultElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsDefault"); + if (isDefaultElement != null) { + boolean isDefaultInstance; + isDefaultInstance = DatatypeConverter.parseBoolean(isDefaultElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsDefault(isDefaultInstance); + } + + Element isSystemElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsSystem"); + if (isSystemElement != null) { + boolean isSystemInstance; + isSystemInstance = DatatypeConverter.parseBoolean(isSystemElement.getTextContent().toLowerCase()); + serviceResourceInstance.setIsSystem(isSystemInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + serviceResourceInstance.setDescription(descriptionInstance); + } + + Element enabledElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Enabled"); + if (enabledElement != null) { + boolean enabledInstance; + enabledInstance = DatatypeConverter.parseBoolean(enabledElement.getTextContent().toLowerCase()); + serviceResourceInstance.setEnabled(enabledInstance); + } + + Element dimensionSettingsSequenceElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "DimensionSettings"); + if (dimensionSettingsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dimensionSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").size(); i2 = i2 + 1) { + org.w3c.dom.Element dimensionSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(dimensionSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServiceResource").get(i2)); + ServiceObjective.DimensionSettingResponse serviceResourceInstance2 = new ServiceObjective.DimensionSettingResponse(); + serviceResourceInstance.getDimensionSettings().add(serviceResourceInstance2); + + Element nameElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + serviceResourceInstance2.setName(nameInstance2); + } + + Element typeElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement2 != null) { + String typeInstance2; + typeInstance2 = typeElement2.getTextContent(); + serviceResourceInstance2.setType(typeInstance2); + } + + Element stateElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement2 != null) { + String stateInstance2; + stateInstance2 = stateElement2.getTextContent(); + serviceResourceInstance2.setState(stateInstance2); + } + + Element selfLinkElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement2 != null) { + String selfLinkInstance2; + selfLinkInstance2 = selfLinkElement2.getTextContent(); + serviceResourceInstance2.setSelfLink(selfLinkInstance2); + } + + Element parentLinkElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "ParentLink"); + if (parentLinkElement2 != null) { + String parentLinkInstance2; + parentLinkInstance2 = parentLinkElement2.getTextContent(); + serviceResourceInstance2.setParentLink(parentLinkInstance2); + } + + Element idElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement2 != null) { + String idInstance2; + idInstance2 = idElement2.getTextContent(); + serviceResourceInstance2.setId(idInstance2); + } + + Element descriptionElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement2 != null) { + String descriptionInstance2; + descriptionInstance2 = descriptionElement2.getTextContent(); + serviceResourceInstance2.setDescription(descriptionInstance2); + } + + Element ordinalElement = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "Ordinal"); + if (ordinalElement != null) { + byte ordinalInstance; + ordinalInstance = DatatypeConverter.parseByte(ordinalElement.getTextContent()); + serviceResourceInstance2.setOrdinal(ordinalInstance); + } + + Element isDefaultElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement, "http://schemas.microsoft.com/windowsazure", "IsDefault"); + if (isDefaultElement2 != null) { + boolean isDefaultInstance2; + isDefaultInstance2 = DatatypeConverter.parseBoolean(isDefaultElement2.getTextContent().toLowerCase()); + serviceResourceInstance2.setIsDefault(isDefaultInstance2); + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementClient.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementClient.java new file mode 100644 index 0000000000000..70ca7406a9b83 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementClient.java @@ -0,0 +1,104 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.FilterableService; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import java.io.Closeable; +import java.net.URI; + +/** +* The SQL Database Management API is a REST API for managing SQL Database +* servers and the firewall rules associated with SQL Database servers. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg715283.aspx for more +* information) +*/ +public interface SqlManagementClient extends Closeable, FilterableService { + /** + * The URI used as the base for all SQL requests. + * @return The BaseUri value. + */ + URI getBaseUri(); + + /** + * When you create a Windows Azure subscription, it is uniquely identified + * by a subscription ID. The subscription ID forms part of the URI for + * every call that you make to the Service Management API. The Windows + * Azure Service ManagementAPI use mutual authentication of management + * certificates over SSL to ensure that a request made to the service is + * secure. No anonymous requests are allowed. + * @return The Credentials value. + */ + SubscriptionCloudCredentials getCredentials(); + + /** + * Includes operations for importing and exporting SQL Databases into and + * out of Windows Azure blob storage. + * @return The DacOperations value. + */ + DacOperations getDacOperations(); + + /** + * The SQL Database Management API includes operations for get/stop SQL + * Databases' operations for a subscription. + * @return The DatabaseOperationsOperations value. + */ + DatabaseOperationOperations getDatabaseOperationsOperations(); + + /** + * The SQL Database Management API includes operations for managing SQL + * Databases for a subscription. + * @return The DatabasesOperations value. + */ + DatabaseOperations getDatabasesOperations(); + + /** + * The Windows Azure SQL Database Management API includes operations for + * managing the server-level firewall rules for SQL Database servers.You + * cannot manage the database-level firewall rules using the Windows Azure + * SQL Database Management API; they can only be managed by running the + * Transact-SQL statements against the master or individual user + * databases. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715276.aspx for + * more information) + * @return The FirewallRulesOperations value. + */ + FirewallRuleOperations getFirewallRulesOperations(); + + /** + * The SQL Database Management API includes operations for managing SQL + * Database servers for a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715271.aspx for + * more information) + * @return The ServersOperations value. + */ + ServerOperations getServersOperations(); + + /** + * The SQL Database Management API includes operations for getting Service + * Objective for a subscription. + * @return The ServiceObjectivesOperations value. + */ + ServiceObjectiveOperations getServiceObjectivesOperations(); +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementClientImpl.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementClientImpl.java new file mode 100644 index 0000000000000..ddb5933c12d41 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementClientImpl.java @@ -0,0 +1,224 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.core.ServiceClient; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutorService; +import javax.inject.Inject; +import javax.inject.Named; +import org.apache.http.impl.client.HttpClientBuilder; + +/** +* The SQL Database Management API is a REST API for managing SQL Database +* servers and the firewall rules associated with SQL Database servers. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg715283.aspx for more +* information) +*/ +public class SqlManagementClientImpl extends ServiceClient implements SqlManagementClient { + private URI baseUri; + + /** + * The URI used as the base for all SQL requests. + * @return The BaseUri value. + */ + public URI getBaseUri() { + return this.baseUri; + } + + private SubscriptionCloudCredentials credentials; + + /** + * When you create a Windows Azure subscription, it is uniquely identified + * by a subscription ID. The subscription ID forms part of the URI for + * every call that you make to the Service Management API. The Windows + * Azure Service ManagementAPI use mutual authentication of management + * certificates over SSL to ensure that a request made to the service is + * secure. No anonymous requests are allowed. + * @return The Credentials value. + */ + public SubscriptionCloudCredentials getCredentials() { + return this.credentials; + } + + private DacOperations dac; + + /** + * Includes operations for importing and exporting SQL Databases into and + * out of Windows Azure blob storage. + * @return The DacOperations value. + */ + public DacOperations getDacOperations() { + return this.dac; + } + + private DatabaseOperationOperations databaseOperations; + + /** + * The SQL Database Management API includes operations for get/stop SQL + * Databases' operations for a subscription. + * @return The DatabaseOperationsOperations value. + */ + public DatabaseOperationOperations getDatabaseOperationsOperations() { + return this.databaseOperations; + } + + private DatabaseOperations databases; + + /** + * The SQL Database Management API includes operations for managing SQL + * Databases for a subscription. + * @return The DatabasesOperations value. + */ + public DatabaseOperations getDatabasesOperations() { + return this.databases; + } + + private FirewallRuleOperations firewallRules; + + /** + * The Windows Azure SQL Database Management API includes operations for + * managing the server-level firewall rules for SQL Database servers.You + * cannot manage the database-level firewall rules using the Windows Azure + * SQL Database Management API; they can only be managed by running the + * Transact-SQL statements against the master or individual user + * databases. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715276.aspx for + * more information) + * @return The FirewallRulesOperations value. + */ + public FirewallRuleOperations getFirewallRulesOperations() { + return this.firewallRules; + } + + private ServerOperations servers; + + /** + * The SQL Database Management API includes operations for managing SQL + * Database servers for a subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715271.aspx for + * more information) + * @return The ServersOperations value. + */ + public ServerOperations getServersOperations() { + return this.servers; + } + + private ServiceObjectiveOperations serviceObjectives; + + /** + * The SQL Database Management API includes operations for getting Service + * Objective for a subscription. + * @return The ServiceObjectivesOperations value. + */ + public ServiceObjectiveOperations getServiceObjectivesOperations() { + return this.serviceObjectives; + } + + /** + * Initializes a new instance of the SqlManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + private SqlManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) { + super(httpBuilder, executorService); + this.dac = new DacOperationsImpl(this); + this.databaseOperations = new DatabaseOperationOperationsImpl(this); + this.databases = new DatabaseOperationsImpl(this); + this.firewallRules = new FirewallRuleOperationsImpl(this); + this.servers = new ServerOperationsImpl(this); + this.serviceObjectives = new ServiceObjectiveOperationsImpl(this); + } + + /** + * Initializes a new instance of the SqlManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create a Windows Azure + * subscription, it is uniquely identified by a subscription ID. The + * subscription ID forms part of the URI for every call that you make to + * the Service Management API. The Windows Azure Service ManagementAPI use + * mutual authentication of management certificates over SSL to ensure that + * a request made to the service is secure. No anonymous requests are + * allowed. + * @param baseUri Required. The URI used as the base for all SQL requests. + */ + @Inject + public SqlManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } else { + this.credentials = credentials; + } + if (baseUri == null) { + try { + this.baseUri = new URI("https://management.core.windows.net"); + } + catch (URISyntaxException ex) { + } + } else { + this.baseUri = baseUri; + } + } + + /** + * Initializes a new instance of the SqlManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create a Windows Azure + * subscription, it is uniquely identified by a subscription ID. The + * subscription ID forms part of the URI for every call that you make to + * the Service Management API. The Windows Azure Service ManagementAPI use + * mutual authentication of management certificates over SSL to ensure that + * a request made to the service is secure. No anonymous requests are + * allowed. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + */ + public SqlManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } + this.credentials = credentials; + this.baseUri = new URI("https://management.core.windows.net"); + } + + /** + * Initializes a new instance of the SqlManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + protected SqlManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) { + return new SqlManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri()); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementService.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementService.java new file mode 100644 index 0000000000000..1a6bc14cd9a62 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/SqlManagementService.java @@ -0,0 +1,74 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.Configuration; + +/** + * + * Access service management functionality. + * + */ +public final class SqlManagementService { + private SqlManagementService() { + // class is not instantiated + } + + /** + * Creates an instance of the SqlManagementClient API. + * @return An instance of the SqlManagementClient API. + */ + public static SqlManagementClient create() { + return Configuration.getInstance().create(SqlManagementClient.class); + } + + /** + * Creates an instance of the SqlManagementClient API using the + * specified configuration. + * + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the SqlManagementClient API. + */ + public static SqlManagementClient create(final Configuration config) { + return config.create(SqlManagementClient.class); + } + + /** + * Creates an instance of the SqlManagementClient API. + * + * @param profile A String object that representing the profile + * of the service management service. + * @return An instance of the SqlManagementClient API. + */ + public static SqlManagementClient create(final String profile) { + return Configuration.getInstance().create(profile, + SqlManagementClient.class); + } + + /** + * Creates an instance of the ManagementClient API using the + * specified configuration. + * + * @param profile The profile. + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the SqlManagementClient API. + */ + public static SqlManagementClient create(final String profile, + final Configuration config) { + return config.create(profile, SqlManagementClient.class); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacExportParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacExportParameters.java new file mode 100644 index 0000000000000..f1f671a64b54d --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacExportParameters.java @@ -0,0 +1,187 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.net.URI; + +/** +* Parameters supplied to the DAC Export operation. +*/ +public class DacExportParameters { + private DacExportParameters.BlobCredentialsParameter blobCredentials; + + /** + * Optional. Gets or sets credentials for getting the DAC. + * @return The BlobCredentials value. + */ + public DacExportParameters.BlobCredentialsParameter getBlobCredentials() { + return this.blobCredentials; + } + + /** + * Optional. Gets or sets credentials for getting the DAC. + * @param blobCredentialsValue The BlobCredentials value. + */ + public void setBlobCredentials(final DacExportParameters.BlobCredentialsParameter blobCredentialsValue) { + this.blobCredentials = blobCredentialsValue; + } + + private DacExportParameters.ConnectionInfoParameter connectionInfo; + + /** + * Optional. Gets or sets connection information for the SQL Server Database. + * @return The ConnectionInfo value. + */ + public DacExportParameters.ConnectionInfoParameter getConnectionInfo() { + return this.connectionInfo; + } + + /** + * Optional. Gets or sets connection information for the SQL Server Database. + * @param connectionInfoValue The ConnectionInfo value. + */ + public void setConnectionInfo(final DacExportParameters.ConnectionInfoParameter connectionInfoValue) { + this.connectionInfo = connectionInfoValue; + } + + /** + * Credentials for getting the DAC. + */ + public static class BlobCredentialsParameter { + private String storageAccessKey; + + /** + * Required. Gets or sets the key for the Windows Azure Storage account. + * @return The StorageAccessKey value. + */ + public String getStorageAccessKey() { + return this.storageAccessKey; + } + + /** + * Required. Gets or sets the key for the Windows Azure Storage account. + * @param storageAccessKeyValue The StorageAccessKey value. + */ + public void setStorageAccessKey(final String storageAccessKeyValue) { + this.storageAccessKey = storageAccessKeyValue; + } + + private URI uri; + + /** + * Required. Gets or sets the URI of the DAC file stored in Windows + * Azure Blob Storage. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Required. Gets or sets the URI of the DAC file stored in Windows + * Azure Blob Storage. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + } + + /** + * Connection information for the SQL Server Database. + */ + public static class ConnectionInfoParameter { + private String databaseName; + + /** + * Required. Gets or sets the name of the database. + * @return The DatabaseName value. + */ + public String getDatabaseName() { + return this.databaseName; + } + + /** + * Required. Gets or sets the name of the database. + * @param databaseNameValue The DatabaseName value. + */ + public void setDatabaseName(final String databaseNameValue) { + this.databaseName = databaseNameValue; + } + + private String password; + + /** + * Required. Gets or sets the password for the database user. + * @return The Password value. + */ + public String getPassword() { + return this.password; + } + + /** + * Required. Gets or sets the password for the database user. + * @param passwordValue The Password value. + */ + public void setPassword(final String passwordValue) { + this.password = passwordValue; + } + + private String serverName; + + /** + * Required. Gets or sets the SQL server name. + * @return The ServerName value. + */ + public String getServerName() { + return this.serverName; + } + + /** + * Required. Gets or sets the SQL server name. + * @param serverNameValue The ServerName value. + */ + public void setServerName(final String serverNameValue) { + this.serverName = serverNameValue; + } + + private String userName; + + /** + * Required. Gets or sets the username of the database user. + * @return The UserName value. + */ + public String getUserName() { + return this.userName; + } + + /** + * Required. Gets or sets the username of the database user. + * @param userNameValue The UserName value. + */ + public void setUserName(final String userNameValue) { + this.userName = userNameValue; + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacGetStatusResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacGetStatusResponse.java new file mode 100644 index 0000000000000..c0363c7479039 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacGetStatusResponse.java @@ -0,0 +1,70 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The response structure for the DAC GetStatus operation. +*/ +public class DacGetStatusResponse extends OperationResponse implements Iterable { + private ArrayList statusInfoList; + + /** + * Optional. Gets or sets the list of statuses relevant to this + * import/export request. + * @return The StatusInfoList value. + */ + public ArrayList getStatusInfoList() { + return this.statusInfoList; + } + + /** + * Optional. Gets or sets the list of statuses relevant to this + * import/export request. + * @param statusInfoListValue The StatusInfoList value. + */ + public void setStatusInfoList(final ArrayList statusInfoListValue) { + this.statusInfoList = statusInfoListValue; + } + + /** + * Initializes a new instance of the DacGetStatusResponse class. + * + */ + public DacGetStatusResponse() { + super(); + this.statusInfoList = new ArrayList(); + } + + /** + * Gets the sequence of StatusInfoList. + * + */ + public Iterator iterator() { + return this.getStatusInfoList().iterator(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacImportExportResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacImportExportResponse.java new file mode 100644 index 0000000000000..6f2e439a86c3a --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacImportExportResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response for an DAC Import/Export request. +*/ +public class DacImportExportResponse extends OperationResponse { + private String guid; + + /** + * Optional. Gets or sets the operation's identifier. + * @return The Guid value. + */ + public String getGuid() { + return this.guid; + } + + /** + * Optional. Gets or sets the operation's identifier. + * @param guidValue The Guid value. + */ + public void setGuid(final String guidValue) { + this.guid = guidValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacImportParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacImportParameters.java new file mode 100644 index 0000000000000..0ab9530a344ec --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DacImportParameters.java @@ -0,0 +1,223 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.net.URI; + +/** +* Parameters supplied to the DAC Import operation. +*/ +public class DacImportParameters { + private String azureEdition; + + /** + * Optional. The edition of this database. + * @return The AzureEdition value. + */ + public String getAzureEdition() { + return this.azureEdition; + } + + /** + * Optional. The edition of this database. + * @param azureEditionValue The AzureEdition value. + */ + public void setAzureEdition(final String azureEditionValue) { + this.azureEdition = azureEditionValue; + } + + private DacImportParameters.BlobCredentialsParameter blobCredentials; + + /** + * Optional. Gets or sets credentials for getting the DAC. + * @return The BlobCredentials value. + */ + public DacImportParameters.BlobCredentialsParameter getBlobCredentials() { + return this.blobCredentials; + } + + /** + * Optional. Gets or sets credentials for getting the DAC. + * @param blobCredentialsValue The BlobCredentials value. + */ + public void setBlobCredentials(final DacImportParameters.BlobCredentialsParameter blobCredentialsValue) { + this.blobCredentials = blobCredentialsValue; + } + + private DacImportParameters.ConnectionInfoParameter connectionInfo; + + /** + * Optional. Gets or sets connection information for the SQL Server Database. + * @return The ConnectionInfo value. + */ + public DacImportParameters.ConnectionInfoParameter getConnectionInfo() { + return this.connectionInfo; + } + + /** + * Optional. Gets or sets connection information for the SQL Server Database. + * @param connectionInfoValue The ConnectionInfo value. + */ + public void setConnectionInfo(final DacImportParameters.ConnectionInfoParameter connectionInfoValue) { + this.connectionInfo = connectionInfoValue; + } + + private int databaseSizeInGB; + + /** + * Optional. Gets or sets the size of this database. + * @return The DatabaseSizeInGB value. + */ + public int getDatabaseSizeInGB() { + return this.databaseSizeInGB; + } + + /** + * Optional. Gets or sets the size of this database. + * @param databaseSizeInGBValue The DatabaseSizeInGB value. + */ + public void setDatabaseSizeInGB(final int databaseSizeInGBValue) { + this.databaseSizeInGB = databaseSizeInGBValue; + } + + /** + * Credentials for getting the DAC. + */ + public static class BlobCredentialsParameter { + private String storageAccessKey; + + /** + * Required. Gets or sets the key for the Windows Azure Storage account. + * @return The StorageAccessKey value. + */ + public String getStorageAccessKey() { + return this.storageAccessKey; + } + + /** + * Required. Gets or sets the key for the Windows Azure Storage account. + * @param storageAccessKeyValue The StorageAccessKey value. + */ + public void setStorageAccessKey(final String storageAccessKeyValue) { + this.storageAccessKey = storageAccessKeyValue; + } + + private URI uri; + + /** + * Required. Gets or sets the URI of the DAC file stored in Windows + * Azure Blob Storage. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Required. Gets or sets the URI of the DAC file stored in Windows + * Azure Blob Storage. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + } + + /** + * Connection information for the SQL Server Database. + */ + public static class ConnectionInfoParameter { + private String databaseName; + + /** + * Required. Gets or sets the name of the database. + * @return The DatabaseName value. + */ + public String getDatabaseName() { + return this.databaseName; + } + + /** + * Required. Gets or sets the name of the database. + * @param databaseNameValue The DatabaseName value. + */ + public void setDatabaseName(final String databaseNameValue) { + this.databaseName = databaseNameValue; + } + + private String password; + + /** + * Required. Gets or sets the password for the database user. + * @return The Password value. + */ + public String getPassword() { + return this.password; + } + + /** + * Required. Gets or sets the password for the database user. + * @param passwordValue The Password value. + */ + public void setPassword(final String passwordValue) { + this.password = passwordValue; + } + + private String serverName; + + /** + * Required. Gets or sets the SQL server name. + * @return The ServerName value. + */ + public String getServerName() { + return this.serverName; + } + + /** + * Required. Gets or sets the SQL server name. + * @param serverNameValue The ServerName value. + */ + public void setServerName(final String serverNameValue) { + this.serverName = serverNameValue; + } + + private String userName; + + /** + * Required. Gets or sets the username of the database user. + * @return The UserName value. + */ + public String getUserName() { + return this.userName; + } + + /** + * Required. Gets or sets the username of the database user. + * @param userNameValue The UserName value. + */ + public void setUserName(final String userNameValue) { + this.userName = userNameValue; + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/Database.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/Database.java new file mode 100644 index 0000000000000..373aea9694526 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/Database.java @@ -0,0 +1,346 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.util.Calendar; + +/** +* SQL Server database. +*/ +public class Database { + private String collationName; + + /** + * Optional. Gets or sets the database resource's collation name. + * @return The CollationName value. + */ + public String getCollationName() { + return this.collationName; + } + + /** + * Optional. Gets or sets the database resource's collation name. + * @param collationNameValue The CollationName value. + */ + public void setCollationName(final String collationNameValue) { + this.collationName = collationNameValue; + } + + private Calendar creationDate; + + /** + * Optional. Gets or sets the date this database was created. + * @return The CreationDate value. + */ + public Calendar getCreationDate() { + return this.creationDate; + } + + /** + * Optional. Gets or sets the date this database was created. + * @param creationDateValue The CreationDate value. + */ + public void setCreationDate(final Calendar creationDateValue) { + this.creationDate = creationDateValue; + } + + private String edition; + + /** + * Optional. Gets or sets the database resource's edition. + * @return The Edition value. + */ + public String getEdition() { + return this.edition; + } + + /** + * Optional. Gets or sets the database resource's edition. + * @param editionValue The Edition value. + */ + public void setEdition(final String editionValue) { + this.edition = editionValue; + } + + private int id; + + /** + * Optional. Gets or sets the id of the database. + * @return The Id value. + */ + public int getId() { + return this.id; + } + + /** + * Optional. Gets or sets the id of the database. + * @param idValue The Id value. + */ + public void setId(final int idValue) { + this.id = idValue; + } + + private boolean isFederationRoot; + + /** + * Optional. Gets or sets a value indicating whether the database is a + * federation root. + * @return The IsFederationRoot value. + */ + public boolean isFederationRoot() { + return this.isFederationRoot; + } + + /** + * Optional. Gets or sets a value indicating whether the database is a + * federation root. + * @param isFederationRootValue The IsFederationRoot value. + */ + public void setIsFederationRoot(final boolean isFederationRootValue) { + this.isFederationRoot = isFederationRootValue; + } + + private boolean isSystemObject; + + /** + * Optional. Gets or sets a value indicating whether the database is a + * system object. + * @return The IsSystemObject value. + */ + public boolean isSystemObject() { + return this.isSystemObject; + } + + /** + * Optional. Gets or sets a value indicating whether the database is a + * system object. + * @param isSystemObjectValue The IsSystemObject value. + */ + public void setIsSystemObject(final boolean isSystemObjectValue) { + this.isSystemObject = isSystemObjectValue; + } + + private int maximumDatabaseSizeInGB; + + /** + * Optional. Gets or sets the maximum size of this database, in Gigabytes. + * @return The MaximumDatabaseSizeInGB value. + */ + public int getMaximumDatabaseSizeInGB() { + return this.maximumDatabaseSizeInGB; + } + + /** + * Optional. Gets or sets the maximum size of this database, in Gigabytes. + * @param maximumDatabaseSizeInGBValue The MaximumDatabaseSizeInGB value. + */ + public void setMaximumDatabaseSizeInGB(final int maximumDatabaseSizeInGBValue) { + this.maximumDatabaseSizeInGB = maximumDatabaseSizeInGBValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of the database. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of the database. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String serviceObjectiveAssignmentErrorCode; + + /** + * Optional. Gets or sets the error code for this service objective. + * @return The ServiceObjectiveAssignmentErrorCode value. + */ + public String getServiceObjectiveAssignmentErrorCode() { + return this.serviceObjectiveAssignmentErrorCode; + } + + /** + * Optional. Gets or sets the error code for this service objective. + * @param serviceObjectiveAssignmentErrorCodeValue The + * ServiceObjectiveAssignmentErrorCode value. + */ + public void setServiceObjectiveAssignmentErrorCode(final String serviceObjectiveAssignmentErrorCodeValue) { + this.serviceObjectiveAssignmentErrorCode = serviceObjectiveAssignmentErrorCodeValue; + } + + private String serviceObjectiveAssignmentErrorDescription; + + /** + * Optional. Gets or sets the error description, if any. + * @return The ServiceObjectiveAssignmentErrorDescription value. + */ + public String getServiceObjectiveAssignmentErrorDescription() { + return this.serviceObjectiveAssignmentErrorDescription; + } + + /** + * Optional. Gets or sets the error description, if any. + * @param serviceObjectiveAssignmentErrorDescriptionValue The + * ServiceObjectiveAssignmentErrorDescription value. + */ + public void setServiceObjectiveAssignmentErrorDescription(final String serviceObjectiveAssignmentErrorDescriptionValue) { + this.serviceObjectiveAssignmentErrorDescription = serviceObjectiveAssignmentErrorDescriptionValue; + } + + private String serviceObjectiveAssignmentState; + + /** + * Optional. Gets or sets the state of the current assignment. + * @return The ServiceObjectiveAssignmentState value. + */ + public String getServiceObjectiveAssignmentState() { + return this.serviceObjectiveAssignmentState; + } + + /** + * Optional. Gets or sets the state of the current assignment. + * @param serviceObjectiveAssignmentStateValue The + * ServiceObjectiveAssignmentState value. + */ + public void setServiceObjectiveAssignmentState(final String serviceObjectiveAssignmentStateValue) { + this.serviceObjectiveAssignmentState = serviceObjectiveAssignmentStateValue; + } + + private String serviceObjectiveAssignmentStateDescription; + + /** + * Optional. Gets or sets the state description. + * @return The ServiceObjectiveAssignmentStateDescription value. + */ + public String getServiceObjectiveAssignmentStateDescription() { + return this.serviceObjectiveAssignmentStateDescription; + } + + /** + * Optional. Gets or sets the state description. + * @param serviceObjectiveAssignmentStateDescriptionValue The + * ServiceObjectiveAssignmentStateDescription value. + */ + public void setServiceObjectiveAssignmentStateDescription(final String serviceObjectiveAssignmentStateDescriptionValue) { + this.serviceObjectiveAssignmentStateDescription = serviceObjectiveAssignmentStateDescriptionValue; + } + + private String serviceObjectiveAssignmentSuccessDate; + + /** + * Optional. Gets or sets the date the service's assignment succeeded. + * @return The ServiceObjectiveAssignmentSuccessDate value. + */ + public String getServiceObjectiveAssignmentSuccessDate() { + return this.serviceObjectiveAssignmentSuccessDate; + } + + /** + * Optional. Gets or sets the date the service's assignment succeeded. + * @param serviceObjectiveAssignmentSuccessDateValue The + * ServiceObjectiveAssignmentSuccessDate value. + */ + public void setServiceObjectiveAssignmentSuccessDate(final String serviceObjectiveAssignmentSuccessDateValue) { + this.serviceObjectiveAssignmentSuccessDate = serviceObjectiveAssignmentSuccessDateValue; + } + + private String serviceObjectiveId; + + /** + * Optional. Gets or sets the id of this service objective. + * @return The ServiceObjectiveId value. + */ + public String getServiceObjectiveId() { + return this.serviceObjectiveId; + } + + /** + * Optional. Gets or sets the id of this service objective. + * @param serviceObjectiveIdValue The ServiceObjectiveId value. + */ + public void setServiceObjectiveId(final String serviceObjectiveIdValue) { + this.serviceObjectiveId = serviceObjectiveIdValue; + } + + private String sizeMB; + + /** + * Optional. Gets or sets the size of this database in megabytes (MB). + * @return The SizeMB value. + */ + public String getSizeMB() { + return this.sizeMB; + } + + /** + * Optional. Gets or sets the size of this database in megabytes (MB). + * @param sizeMBValue The SizeMB value. + */ + public void setSizeMB(final String sizeMBValue) { + this.sizeMB = sizeMBValue; + } + + private String state; + + /** + * Optional. Gets or sets the state of the database. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Gets or sets the state of the database. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private String type; + + /** + * Optional. Gets or sets the type of resource. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. Gets or sets the type of resource. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseCreateParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseCreateParameters.java new file mode 100644 index 0000000000000..9607984489203 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseCreateParameters.java @@ -0,0 +1,119 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +/** +* Parameters supplied to the Create Database operation. +*/ +public class DatabaseCreateParameters { + private String collationName; + + /** + * Optional. Gets or sets the collation name for the new database. + * @return The CollationName value. + */ + public String getCollationName() { + return this.collationName; + } + + /** + * Optional. Gets or sets the collation name for the new database. + * @param collationNameValue The CollationName value. + */ + public void setCollationName(final String collationNameValue) { + this.collationName = collationNameValue; + } + + private String edition; + + /** + * Required. Gets or sets the edition for the new database. + * @return The Edition value. + */ + public String getEdition() { + return this.edition; + } + + /** + * Required. Gets or sets the edition for the new database. + * @param editionValue The Edition value. + */ + public void setEdition(final String editionValue) { + this.edition = editionValue; + } + + private int maximumDatabaseSizeInGB; + + /** + * Required. Gets or sets the maximum size of this database, in Gigabytes. + * @return The MaximumDatabaseSizeInGB value. + */ + public int getMaximumDatabaseSizeInGB() { + return this.maximumDatabaseSizeInGB; + } + + /** + * Required. Gets or sets the maximum size of this database, in Gigabytes. + * @param maximumDatabaseSizeInGBValue The MaximumDatabaseSizeInGB value. + */ + public void setMaximumDatabaseSizeInGB(final int maximumDatabaseSizeInGBValue) { + this.maximumDatabaseSizeInGB = maximumDatabaseSizeInGBValue; + } + + private String name; + + /** + * Required. Gets or sets the name for the new database. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. Gets or sets the name for the new database. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String serviceObjectiveId; + + /** + * Optional. Gets or sets the id of this service objective. + * @return The ServiceObjectiveId value. + */ + public String getServiceObjectiveId() { + return this.serviceObjectiveId; + } + + /** + * Optional. Gets or sets the id of this service objective. + * @param serviceObjectiveIdValue The ServiceObjectiveId value. + */ + public void setServiceObjectiveId(final String serviceObjectiveIdValue) { + this.serviceObjectiveId = serviceObjectiveIdValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseCreateResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseCreateResponse.java new file mode 100644 index 0000000000000..583878354adc9 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseCreateResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response containing the database create response. +*/ +public class DatabaseCreateResponse extends OperationResponse { + private Database database; + + /** + * Optional. + * @return The Database value. + */ + public Database getDatabase() { + return this.database; + } + + /** + * Optional. + * @param databaseValue The Database value. + */ + public void setDatabase(final Database databaseValue) { + this.database = databaseValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseEditions.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseEditions.java new file mode 100644 index 0000000000000..4dfb6fd0bc544 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseEditions.java @@ -0,0 +1,44 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +/** +* Specifies the edition of the SQL database. +*/ +public abstract class DatabaseEditions { + /** + * The Web Edition Database is best suited for small Web applications and + * workgroup or departmental applications. This edition supports a database + * with a maximum size of 1 or 5 GB of data. + */ + public static final String WEB = "Web"; + + /** + * The Business Edition Database is best suited for independent software + * vendors (ISVs), line-of-business (LOB) applications, and enterprise + * applications. This edition supports a database of up to 150 GB of data, + * in 10GB increments up to 50GB, and then 50 GB increments. + */ + public static final String BUSINESS = "Business"; +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseEventLog.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseEventLog.java new file mode 100644 index 0000000000000..9153681c99670 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseEventLog.java @@ -0,0 +1,316 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.util.Calendar; + +public class DatabaseEventLog { + private String additionalData; + + /** + * Optional. Gets or sets the additional data of the event log. + * @return The AdditionalData value. + */ + public String getAdditionalData() { + return this.additionalData; + } + + /** + * Optional. Gets or sets the additional data of the event log. + * @param additionalDataValue The AdditionalData value. + */ + public void setAdditionalData(final String additionalDataValue) { + this.additionalData = additionalDataValue; + } + + private String databaseName; + + /** + * Optional. Gets or sets the database name of the event log. + * @return The DatabaseName value. + */ + public String getDatabaseName() { + return this.databaseName; + } + + /** + * Optional. Gets or sets the database name of the event log. + * @param databaseNameValue The DatabaseName value. + */ + public void setDatabaseName(final String databaseNameValue) { + this.databaseName = databaseNameValue; + } + + private String description; + + /** + * Optional. Gets or sets the description of the event log. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Gets or sets the description of the event log. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String eventCategory; + + /** + * Optional. Gets or sets the event category of the event log. + * @return The EventCategory value. + */ + public String getEventCategory() { + return this.eventCategory; + } + + /** + * Optional. Gets or sets the event category of the event log. + * @param eventCategoryValue The EventCategory value. + */ + public void setEventCategory(final String eventCategoryValue) { + this.eventCategory = eventCategoryValue; + } + + private String eventSubtype; + + /** + * Optional. Gets or sets the event sub type of the event log. + * @return The EventSubtype value. + */ + public String getEventSubtype() { + return this.eventSubtype; + } + + /** + * Optional. Gets or sets the event sub type of the event log. + * @param eventSubtypeValue The EventSubtype value. + */ + public void setEventSubtype(final String eventSubtypeValue) { + this.eventSubtype = eventSubtypeValue; + } + + private String eventSubtypeDescription; + + /** + * Optional. Gets or sets the event sub type description of the event log. + * @return The EventSubtypeDescription value. + */ + public String getEventSubtypeDescription() { + return this.eventSubtypeDescription; + } + + /** + * Optional. Gets or sets the event sub type description of the event log. + * @param eventSubtypeDescriptionValue The EventSubtypeDescription value. + */ + public void setEventSubtypeDescription(final String eventSubtypeDescriptionValue) { + this.eventSubtypeDescription = eventSubtypeDescriptionValue; + } + + private String eventType; + + /** + * Optional. Gets or sets the event type of the event log. + * @return The EventType value. + */ + public String getEventType() { + return this.eventType; + } + + /** + * Optional. Gets or sets the event type of the event log. + * @param eventTypeValue The EventType value. + */ + public void setEventType(final String eventTypeValue) { + this.eventType = eventTypeValue; + } + + private int intervalSizeInMinutes; + + /** + * Optional. Gets or sets the interval size in minutes of the event log. + * @return The IntervalSizeInMinutes value. + */ + public int getIntervalSizeInMinutes() { + return this.intervalSizeInMinutes; + } + + /** + * Optional. Gets or sets the interval size in minutes of the event log. + * @param intervalSizeInMinutesValue The IntervalSizeInMinutes value. + */ + public void setIntervalSizeInMinutes(final int intervalSizeInMinutesValue) { + this.intervalSizeInMinutes = intervalSizeInMinutesValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of the event log. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of the event log. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private int numberOfEvents; + + /** + * Optional. Gets or sets the number of events of the event log. + * @return The NumberOfEvents value. + */ + public int getNumberOfEvents() { + return this.numberOfEvents; + } + + /** + * Optional. Gets or sets the number of events of the event log. + * @param numberOfEventsValue The NumberOfEvents value. + */ + public void setNumberOfEvents(final int numberOfEventsValue) { + this.numberOfEvents = numberOfEventsValue; + } + + private String parentLink; + + /** + * Optional. Gets or sets the self link of the event log. + * @return The ParentLink value. + */ + public String getParentLink() { + return this.parentLink; + } + + /** + * Optional. Gets or sets the self link of the event log. + * @param parentLinkValue The ParentLink value. + */ + public void setParentLink(final String parentLinkValue) { + this.parentLink = parentLinkValue; + } + + private String selfLink; + + /** + * Optional. Gets or sets the self link of the event log. + * @return The SelfLink value. + */ + public String getSelfLink() { + return this.selfLink; + } + + /** + * Optional. Gets or sets the self link of the event log. + * @param selfLinkValue The SelfLink value. + */ + public void setSelfLink(final String selfLinkValue) { + this.selfLink = selfLinkValue; + } + + private int severity; + + /** + * Optional. Gets or sets the severity of the event log. + * @return The Severity value. + */ + public int getSeverity() { + return this.severity; + } + + /** + * Optional. Gets or sets the severity of the event log. + * @param severityValue The Severity value. + */ + public void setSeverity(final int severityValue) { + this.severity = severityValue; + } + + private Calendar startTimeUtc; + + /** + * Optional. Gets or sets the start time of the event log. + * @return The StartTimeUtc value. + */ + public Calendar getStartTimeUtc() { + return this.startTimeUtc; + } + + /** + * Optional. Gets or sets the start time of the event log. + * @param startTimeUtcValue The StartTimeUtc value. + */ + public void setStartTimeUtc(final Calendar startTimeUtcValue) { + this.startTimeUtc = startTimeUtcValue; + } + + private String state; + + /** + * Optional. Gets or sets the state of the event log. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Gets or sets the state of the event log. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private String type; + + /** + * Optional. Gets or sets the type of the event log. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. Gets or sets the type of the event log. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetEventLogsParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetEventLogsParameters.java new file mode 100644 index 0000000000000..e4382fca407cc --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetEventLogsParameters.java @@ -0,0 +1,85 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.util.Calendar; + +/** +* Parameters supplied to the get database event logs operation. +*/ +public class DatabaseGetEventLogsParameters { + private String eventTypes; + + /** + * Required. Gets or sets the event types. + * @return The EventTypes value. + */ + public String getEventTypes() { + return this.eventTypes; + } + + /** + * Required. Gets or sets the event types. + * @param eventTypesValue The EventTypes value. + */ + public void setEventTypes(final String eventTypesValue) { + this.eventTypes = eventTypesValue; + } + + private int intervalSizeInMinutes; + + /** + * Required. Gets or sets the interval size in minutes. + * @return The IntervalSizeInMinutes value. + */ + public int getIntervalSizeInMinutes() { + return this.intervalSizeInMinutes; + } + + /** + * Required. Gets or sets the interval size in minutes. + * @param intervalSizeInMinutesValue The IntervalSizeInMinutes value. + */ + public void setIntervalSizeInMinutes(final int intervalSizeInMinutesValue) { + this.intervalSizeInMinutes = intervalSizeInMinutesValue; + } + + private Calendar startDate; + + /** + * Required. Gets or sets the start date. + * @return The StartDate value. + */ + public Calendar getStartDate() { + return this.startDate; + } + + /** + * Required. Gets or sets the start date. + * @param startDateValue The StartDate value. + */ + public void setStartDate(final Calendar startDateValue) { + this.startDate = startDateValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetEventLogsResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetEventLogsResponse.java new file mode 100644 index 0000000000000..d80477f17a7a1 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetEventLogsResponse.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* A standard service response including an HTTP status code and request ID. +*/ +public class DatabaseGetEventLogsResponse extends OperationResponse implements Iterable { + private ArrayList eventLogs; + + /** + * Optional. Gets or sets the SQL Server database event logs. + * @return The EventLogs value. + */ + public ArrayList getEventLogs() { + return this.eventLogs; + } + + /** + * Optional. Gets or sets the SQL Server database event logs. + * @param eventLogsValue The EventLogs value. + */ + public void setEventLogs(final ArrayList eventLogsValue) { + this.eventLogs = eventLogsValue; + } + + /** + * Initializes a new instance of the DatabaseGetEventLogsResponse class. + * + */ + public DatabaseGetEventLogsResponse() { + super(); + this.eventLogs = new ArrayList(); + } + + /** + * Gets the sequence of EventLogs. + * + */ + public Iterator iterator() { + return this.getEventLogs().iterator(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetResponse.java new file mode 100644 index 0000000000000..b75f6b700b75c --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseGetResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response containing the database get response. +*/ +public class DatabaseGetResponse extends OperationResponse { + private Database database; + + /** + * Optional. + * @return The Database value. + */ + public Database getDatabase() { + return this.database; + } + + /** + * Optional. + * @param databaseValue The Database value. + */ + public void setDatabase(final Database databaseValue) { + this.database = databaseValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseListResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseListResponse.java new file mode 100644 index 0000000000000..1dbbe78b80b5e --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseListResponse.java @@ -0,0 +1,70 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* Response containing the list of databases for a given server. +*/ +public class DatabaseListResponse extends OperationResponse implements Iterable { + private ArrayList databases; + + /** + * Optional. Gets or sets the SQL Server databases that are housed in a + * server. + * @return The Databases value. + */ + public ArrayList getDatabases() { + return this.databases; + } + + /** + * Optional. Gets or sets the SQL Server databases that are housed in a + * server. + * @param databasesValue The Databases value. + */ + public void setDatabases(final ArrayList databasesValue) { + this.databases = databasesValue; + } + + /** + * Initializes a new instance of the DatabaseListResponse class. + * + */ + public DatabaseListResponse() { + super(); + this.databases = new ArrayList(); + } + + /** + * Gets the sequence of Databases. + * + */ + public Iterator iterator() { + return this.getDatabases().iterator(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperation.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperation.java new file mode 100644 index 0000000000000..722db7cd8eb7a --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperation.java @@ -0,0 +1,331 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.util.Calendar; + +/** +* Database operation. +*/ +public class DatabaseOperation { + private String databaseName; + + /** + * Optional. Gets or sets the name of the SQL Database on which the + * operation is performed. + * @return The DatabaseName value. + */ + public String getDatabaseName() { + return this.databaseName; + } + + /** + * Optional. Gets or sets the name of the SQL Database on which the + * operation is performed. + * @param databaseNameValue The DatabaseName value. + */ + public void setDatabaseName(final String databaseNameValue) { + this.databaseName = databaseNameValue; + } + + private String error; + + /** + * Optional. Gets or sets the description of the error that occurred during + * a failed operation. + * @return The Error value. + */ + public String getError() { + return this.error; + } + + /** + * Optional. Gets or sets the description of the error that occurred during + * a failed operation. + * @param errorValue The Error value. + */ + public void setError(final String errorValue) { + this.error = errorValue; + } + + private int errorCode; + + /** + * Optional. Gets or sets the code indicating the error that occurred during + * a failed operation. + * @return The ErrorCode value. + */ + public int getErrorCode() { + return this.errorCode; + } + + /** + * Optional. Gets or sets the code indicating the error that occurred during + * a failed operation. + * @param errorCodeValue The ErrorCode value. + */ + public void setErrorCode(final int errorCodeValue) { + this.errorCode = errorCodeValue; + } + + private int errorSeverity; + + /** + * Optional. Gets or sets the severity level of the error that occurred + * during a failed operation. + * @return The ErrorSeverity value. + */ + public int getErrorSeverity() { + return this.errorSeverity; + } + + /** + * Optional. Gets or sets the severity level of the error that occurred + * during a failed operation. + * @param errorSeverityValue The ErrorSeverity value. + */ + public void setErrorSeverity(final int errorSeverityValue) { + this.errorSeverity = errorSeverityValue; + } + + private int errorState; + + /** + * Optional. Gets or sets the error state. + * @return The ErrorState value. + */ + public int getErrorState() { + return this.errorState; + } + + /** + * Optional. Gets or sets the error state. + * @param errorStateValue The ErrorState value. + */ + public void setErrorState(final int errorStateValue) { + this.errorState = errorStateValue; + } + + private String id; + + /** + * Optional. Gets or sets unique identifier of the operation.. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. Gets or sets unique identifier of the operation.. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private Calendar lastModifyTime; + + /** + * Optional. Gets or sets the timestamp when the record was last modified + * for a long running operation. + * @return The LastModifyTime value. + */ + public Calendar getLastModifyTime() { + return this.lastModifyTime; + } + + /** + * Optional. Gets or sets the timestamp when the record was last modified + * for a long running operation. + * @param lastModifyTimeValue The LastModifyTime value. + */ + public void setLastModifyTime(final Calendar lastModifyTimeValue) { + this.lastModifyTime = lastModifyTimeValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of the operation. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of the operation. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String parentLink; + + /** + * Optional. Gets or sets the ParentLink of the operation. + * @return The ParentLink value. + */ + public String getParentLink() { + return this.parentLink; + } + + /** + * Optional. Gets or sets the ParentLink of the operation. + * @param parentLinkValue The ParentLink value. + */ + public void setParentLink(final String parentLinkValue) { + this.parentLink = parentLinkValue; + } + + private int percentComplete; + + /** + * Optional. Gets or sets the percentage of operation that has completed. + * @return The PercentComplete value. + */ + public int getPercentComplete() { + return this.percentComplete; + } + + /** + * Optional. Gets or sets the percentage of operation that has completed. + * @param percentCompleteValue The PercentComplete value. + */ + public void setPercentComplete(final int percentCompleteValue) { + this.percentComplete = percentCompleteValue; + } + + private String selfLink; + + /** + * Optional. Gets or sets the SelfLink of the operation. + * @return The SelfLink value. + */ + public String getSelfLink() { + return this.selfLink; + } + + /** + * Optional. Gets or sets the SelfLink of the operation. + * @param selfLinkValue The SelfLink value. + */ + public void setSelfLink(final String selfLinkValue) { + this.selfLink = selfLinkValue; + } + + private String sessionActivityId; + + /** + * Optional. Gets or sets session scoped ID of the operation. + * @return The SessionActivityId value. + */ + public String getSessionActivityId() { + return this.sessionActivityId; + } + + /** + * Optional. Gets or sets session scoped ID of the operation. + * @param sessionActivityIdValue The SessionActivityId value. + */ + public void setSessionActivityId(final String sessionActivityIdValue) { + this.sessionActivityId = sessionActivityIdValue; + } + + private Calendar startTime; + + /** + * Optional. Gets or sets the timestamp when the operation started. + * @return The StartTime value. + */ + public Calendar getStartTime() { + return this.startTime; + } + + /** + * Optional. Gets or sets the timestamp when the operation started. + * @param startTimeValue The StartTime value. + */ + public void setStartTime(final Calendar startTimeValue) { + this.startTime = startTimeValue; + } + + private String state; + + /** + * Optional. Gets or sets the state of the operation. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Gets or sets the state of the operation. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private int stateId; + + /** + * Optional. Gets or sets current state of the long running operation in + * numeric format. + * @return The StateId value. + */ + public int getStateId() { + return this.stateId; + } + + /** + * Optional. Gets or sets current state of the long running operation in + * numeric format. + * @param stateIdValue The StateId value. + */ + public void setStateId(final int stateIdValue) { + this.stateId = stateIdValue; + } + + private String type; + + /** + * Optional. Gets or sets the type of resource. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. Gets or sets the type of resource. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperationGetResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperationGetResponse.java new file mode 100644 index 0000000000000..1e3f4a9fe1ce3 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperationGetResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response containing the database operation for a given operation Guid. +*/ +public class DatabaseOperationGetResponse extends OperationResponse { + private DatabaseOperation databaseOperation; + + /** + * Optional. + * @return The DatabaseOperation value. + */ + public DatabaseOperation getDatabaseOperation() { + return this.databaseOperation; + } + + /** + * Optional. + * @param databaseOperationValue The DatabaseOperation value. + */ + public void setDatabaseOperation(final DatabaseOperation databaseOperationValue) { + this.databaseOperation = databaseOperationValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperationListResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperationListResponse.java new file mode 100644 index 0000000000000..ba6b3df8a88c2 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseOperationListResponse.java @@ -0,0 +1,69 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* Response containing the list of database operations for a given server or +* database. +*/ +public class DatabaseOperationListResponse extends OperationResponse implements Iterable { + private ArrayList databaseOperations; + + /** + * Optional. Gets or sets the list of database operations' response. + * @return The DatabaseOperations value. + */ + public ArrayList getDatabaseOperations() { + return this.databaseOperations; + } + + /** + * Optional. Gets or sets the list of database operations' response. + * @param databaseOperationsValue The DatabaseOperations value. + */ + public void setDatabaseOperations(final ArrayList databaseOperationsValue) { + this.databaseOperations = databaseOperationsValue; + } + + /** + * Initializes a new instance of the DatabaseOperationListResponse class. + * + */ + public DatabaseOperationListResponse() { + super(); + this.databaseOperations = new ArrayList(); + } + + /** + * Gets the sequence of DatabaseOperations. + * + */ + public Iterator iterator() { + return this.getDatabaseOperations().iterator(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseUpdateParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseUpdateParameters.java new file mode 100644 index 0000000000000..50c3e23ac2aca --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseUpdateParameters.java @@ -0,0 +1,137 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +/** +* Parameters supplied to the Create Database operation. +*/ +public class DatabaseUpdateParameters { + private String collationName; + + /** + * Required. Gets or sets the collation name for the new database. + * @return The CollationName value. + */ + public String getCollationName() { + return this.collationName; + } + + /** + * Required. Gets or sets the collation name for the new database. + * @param collationNameValue The CollationName value. + */ + public void setCollationName(final String collationNameValue) { + this.collationName = collationNameValue; + } + + private String edition; + + /** + * Required. Gets or sets the edition for the new database. + * @return The Edition value. + */ + public String getEdition() { + return this.edition; + } + + /** + * Required. Gets or sets the edition for the new database. + * @param editionValue The Edition value. + */ + public void setEdition(final String editionValue) { + this.edition = editionValue; + } + + private int id; + + /** + * Optional. Gets or sets the id of the database. + * @return The Id value. + */ + public int getId() { + return this.id; + } + + /** + * Optional. Gets or sets the id of the database. + * @param idValue The Id value. + */ + public void setId(final int idValue) { + this.id = idValue; + } + + private int maximumDatabaseSizeInGB; + + /** + * Required. Gets or sets the maximum size of this database, in Gigabytes. + * @return The MaximumDatabaseSizeInGB value. + */ + public int getMaximumDatabaseSizeInGB() { + return this.maximumDatabaseSizeInGB; + } + + /** + * Required. Gets or sets the maximum size of this database, in Gigabytes. + * @param maximumDatabaseSizeInGBValue The MaximumDatabaseSizeInGB value. + */ + public void setMaximumDatabaseSizeInGB(final int maximumDatabaseSizeInGBValue) { + this.maximumDatabaseSizeInGB = maximumDatabaseSizeInGBValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of the database. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of the database. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String serviceObjectiveId; + + /** + * Optional. Gets or sets the id of this service objective. + * @return The ServiceObjectiveId value. + */ + public String getServiceObjectiveId() { + return this.serviceObjectiveId; + } + + /** + * Optional. Gets or sets the id of this service objective. + * @param serviceObjectiveIdValue The ServiceObjectiveId value. + */ + public void setServiceObjectiveId(final String serviceObjectiveIdValue) { + this.serviceObjectiveId = serviceObjectiveIdValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseUpdateResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseUpdateResponse.java new file mode 100644 index 0000000000000..b109c0e8cfcbf --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/DatabaseUpdateResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response containing the database update response. +*/ +public class DatabaseUpdateResponse extends OperationResponse { + private Database database; + + /** + * Optional. + * @return The Database value. + */ + public Database getDatabase() { + return this.database; + } + + /** + * Optional. + * @param databaseValue The Database value. + */ + public void setDatabase(final Database databaseValue) { + this.database = databaseValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRule.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRule.java new file mode 100644 index 0000000000000..ed39e9d70f065 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRule.java @@ -0,0 +1,103 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.net.InetAddress; + +/** +* Firewall rule. +*/ +public class FirewallRule { + private InetAddress endIPAddress; + + /** + * Optional. Gets or sets the ending IP address applied to this rule. + * @return The EndIPAddress value. + */ + public InetAddress getEndIPAddress() { + return this.endIPAddress; + } + + /** + * Optional. Gets or sets the ending IP address applied to this rule. + * @param endIPAddressValue The EndIPAddress value. + */ + public void setEndIPAddress(final InetAddress endIPAddressValue) { + this.endIPAddress = endIPAddressValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of the Firewall Rule. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of the Firewall Rule. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private InetAddress startIPAddress; + + /** + * Optional. Gets or sets the beginning IP address applied to this rule. + * @return The StartIPAddress value. + */ + public InetAddress getStartIPAddress() { + return this.startIPAddress; + } + + /** + * Optional. Gets or sets the beginning IP address applied to this rule. + * @param startIPAddressValue The StartIPAddress value. + */ + public void setStartIPAddress(final InetAddress startIPAddressValue) { + this.startIPAddress = startIPAddressValue; + } + + private String type; + + /** + * Optional. Gets or sets the type of resource. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. Gets or sets the type of resource. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleCreateParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleCreateParameters.java new file mode 100644 index 0000000000000..2c1379f4c02f8 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleCreateParameters.java @@ -0,0 +1,89 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.net.InetAddress; + +/** +* The parameters for the Create Firewall Rule operation. +*/ +public class FirewallRuleCreateParameters { + private InetAddress endIPAddress; + + /** + * Required. Gets or sets the ending IP address applied to this firewall + * rule. + * @return The EndIPAddress value. + */ + public InetAddress getEndIPAddress() { + return this.endIPAddress; + } + + /** + * Required. Gets or sets the ending IP address applied to this firewall + * rule. + * @param endIPAddressValue The EndIPAddress value. + */ + public void setEndIPAddress(final InetAddress endIPAddressValue) { + this.endIPAddress = endIPAddressValue; + } + + private String name; + + /** + * Required. Gets or sets the name of this firewall rule. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. Gets or sets the name of this firewall rule. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private InetAddress startIPAddress; + + /** + * Required. Gets or sets the beginning IP address applied to this firewall + * rule. + * @return The StartIPAddress value. + */ + public InetAddress getStartIPAddress() { + return this.startIPAddress; + } + + /** + * Required. Gets or sets the beginning IP address applied to this firewall + * rule. + * @param startIPAddressValue The StartIPAddress value. + */ + public void setStartIPAddress(final InetAddress startIPAddressValue) { + this.startIPAddress = startIPAddressValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleCreateResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleCreateResponse.java new file mode 100644 index 0000000000000..013dbf0b0a90f --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleCreateResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response containing the firewall rule create response. +*/ +public class FirewallRuleCreateResponse extends OperationResponse { + private FirewallRule firewallRule; + + /** + * Optional. + * @return The FirewallRule value. + */ + public FirewallRule getFirewallRule() { + return this.firewallRule; + } + + /** + * Optional. + * @param firewallRuleValue The FirewallRule value. + */ + public void setFirewallRule(final FirewallRule firewallRuleValue) { + this.firewallRule = firewallRuleValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleGetResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleGetResponse.java new file mode 100644 index 0000000000000..22eef19cb0e10 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleGetResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* A standard service response including an HTTP status code and request ID. +*/ +public class FirewallRuleGetResponse extends OperationResponse { + private FirewallRule firewallRule; + + /** + * Optional. Gets or sets the firewall rule for this SQL Database Server. + * @return The FirewallRule value. + */ + public FirewallRule getFirewallRule() { + return this.firewallRule; + } + + /** + * Optional. Gets or sets the firewall rule for this SQL Database Server. + * @param firewallRuleValue The FirewallRule value. + */ + public void setFirewallRule(final FirewallRule firewallRuleValue) { + this.firewallRule = firewallRuleValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleListResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleListResponse.java new file mode 100644 index 0000000000000..5d73fabe22984 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleListResponse.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* A standard service response including an HTTP status code and request ID. +*/ +public class FirewallRuleListResponse extends OperationResponse implements Iterable { + private ArrayList firewallRules; + + /** + * Optional. Gets or sets the firewall rules for this SQL Database Server. + * @return The FirewallRules value. + */ + public ArrayList getFirewallRules() { + return this.firewallRules; + } + + /** + * Optional. Gets or sets the firewall rules for this SQL Database Server. + * @param firewallRulesValue The FirewallRules value. + */ + public void setFirewallRules(final ArrayList firewallRulesValue) { + this.firewallRules = firewallRulesValue; + } + + /** + * Initializes a new instance of the FirewallRuleListResponse class. + * + */ + public FirewallRuleListResponse() { + super(); + this.firewallRules = new ArrayList(); + } + + /** + * Gets the sequence of FirewallRules. + * + */ + public Iterator iterator() { + return this.getFirewallRules().iterator(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleUpdateParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleUpdateParameters.java new file mode 100644 index 0000000000000..0d64392ba7ef2 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleUpdateParameters.java @@ -0,0 +1,89 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.net.InetAddress; + +/** +* The parameters for the Create Firewall Rule operation. +*/ +public class FirewallRuleUpdateParameters { + private InetAddress endIPAddress; + + /** + * Required. Gets or sets the ending IP address applied to this firewall + * rule. + * @return The EndIPAddress value. + */ + public InetAddress getEndIPAddress() { + return this.endIPAddress; + } + + /** + * Required. Gets or sets the ending IP address applied to this firewall + * rule. + * @param endIPAddressValue The EndIPAddress value. + */ + public void setEndIPAddress(final InetAddress endIPAddressValue) { + this.endIPAddress = endIPAddressValue; + } + + private String name; + + /** + * Required. Gets or sets the name of this firewall rule. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. Gets or sets the name of this firewall rule. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private InetAddress startIPAddress; + + /** + * Required. Gets or sets the beginning IP address applied to this firewall + * rule. + * @return The StartIPAddress value. + */ + public InetAddress getStartIPAddress() { + return this.startIPAddress; + } + + /** + * Required. Gets or sets the beginning IP address applied to this firewall + * rule. + * @param startIPAddressValue The StartIPAddress value. + */ + public void setStartIPAddress(final InetAddress startIPAddressValue) { + this.startIPAddress = startIPAddressValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleUpdateResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleUpdateResponse.java new file mode 100644 index 0000000000000..580a53f4c7d80 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/FirewallRuleUpdateResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response containing the firewall rule update response. +*/ +public class FirewallRuleUpdateResponse extends OperationResponse { + private FirewallRule firewallRule; + + /** + * Optional. + * @return The FirewallRule value. + */ + public FirewallRule getFirewallRule() { + return this.firewallRule; + } + + /** + * Optional. + * @param firewallRuleValue The FirewallRule value. + */ + public void setFirewallRule(final FirewallRule firewallRuleValue) { + this.firewallRule = firewallRuleValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/Server.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/Server.java new file mode 100644 index 0000000000000..3dd55bd0ed576 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/Server.java @@ -0,0 +1,117 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.util.HashMap; + +/** +* An individual server in your Windows Azure subscription. +*/ +public class Server { + private String administratorUserName; + + /** + * Optional. Gets or sets the name of an administrator for this server. + * @return The AdministratorUserName value. + */ + public String getAdministratorUserName() { + return this.administratorUserName; + } + + /** + * Optional. Gets or sets the name of an administrator for this server. + * @param administratorUserNameValue The AdministratorUserName value. + */ + public void setAdministratorUserName(final String administratorUserNameValue) { + this.administratorUserName = administratorUserNameValue; + } + + private HashMap features; + + /** + * Optional. Gets or sets the list of features and the type of database + * server for an individual server. + * @return The Features value. + */ + public HashMap getFeatures() { + return this.features; + } + + /** + * Optional. Gets or sets the list of features and the type of database + * server for an individual server. + * @param featuresValue The Features value. + */ + public void setFeatures(final HashMap featuresValue) { + this.features = featuresValue; + } + + private String location; + + /** + * Optional. Gets or sets the name of a data center location that is valid + * for your subscription. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. Gets or sets the name of a data center location that is valid + * for your subscription. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of a SQL Server running in your + * subscription. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of a SQL Server running in your + * subscription. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + /** + * Initializes a new instance of the Server class. + * + */ + public Server() { + this.features = new HashMap(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerChangeAdministratorPasswordParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerChangeAdministratorPasswordParameters.java new file mode 100644 index 0000000000000..3d15bac8ec0b8 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerChangeAdministratorPasswordParameters.java @@ -0,0 +1,47 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +/** +* Parameters supplied to the Manage Administrator Password operation. +*/ +public class ServerChangeAdministratorPasswordParameters { + private String newPassword; + + /** + * Required. Gets or sets new password for the administrator. + * @return The NewPassword value. + */ + public String getNewPassword() { + return this.newPassword; + } + + /** + * Required. Gets or sets new password for the administrator. + * @param newPasswordValue The NewPassword value. + */ + public void setNewPassword(final String newPasswordValue) { + this.newPassword = newPasswordValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerCreateParameters.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerCreateParameters.java new file mode 100644 index 0000000000000..52f70ebfdd3f9 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerCreateParameters.java @@ -0,0 +1,83 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +/** +* Parameters supplied to the Create Server operation. +*/ +public class ServerCreateParameters { + private String administratorPassword; + + /** + * Required. Gets or sets the administrator password. + * @return The AdministratorPassword value. + */ + public String getAdministratorPassword() { + return this.administratorPassword; + } + + /** + * Required. Gets or sets the administrator password. + * @param administratorPasswordValue The AdministratorPassword value. + */ + public void setAdministratorPassword(final String administratorPasswordValue) { + this.administratorPassword = administratorPasswordValue; + } + + private String administratorUserName; + + /** + * Required. Gets or sets the administrator username. + * @return The AdministratorUserName value. + */ + public String getAdministratorUserName() { + return this.administratorUserName; + } + + /** + * Required. Gets or sets the administrator username. + * @param administratorUserNameValue The AdministratorUserName value. + */ + public void setAdministratorUserName(final String administratorUserNameValue) { + this.administratorUserName = administratorUserNameValue; + } + + private String location; + + /** + * Required. Gets or sets the region in which this server will be created. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Required. Gets or sets the region in which this server will be created. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerCreateResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerCreateResponse.java new file mode 100644 index 0000000000000..84eb0f836ad10 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerCreateResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The response returned from the Create Server operation. +*/ +public class ServerCreateResponse extends OperationResponse { + private String serverName; + + /** + * Optional. Gets or sets the name of the server that was created. + * @return The ServerName value. + */ + public String getServerName() { + return this.serverName; + } + + /** + * Optional. Gets or sets the name of the server that was created. + * @param serverNameValue The ServerName value. + */ + public void setServerName(final String serverNameValue) { + this.serverName = serverNameValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerListResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerListResponse.java new file mode 100644 index 0000000000000..bc2b9ed5794b9 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServerListResponse.java @@ -0,0 +1,70 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The response structure for the Server List operation. +*/ +public class ServerListResponse extends OperationResponse implements Iterable { + private ArrayList servers; + + /** + * Optional. Gets or sets the SQL Servers that are valid for your + * subscription. + * @return The Servers value. + */ + public ArrayList getServers() { + return this.servers; + } + + /** + * Optional. Gets or sets the SQL Servers that are valid for your + * subscription. + * @param serversValue The Servers value. + */ + public void setServers(final ArrayList serversValue) { + this.servers = serversValue; + } + + /** + * Initializes a new instance of the ServerListResponse class. + * + */ + public ServerListResponse() { + super(); + this.servers = new ArrayList(); + } + + /** + * Gets the sequence of Servers. + * + */ + public Iterator iterator() { + return this.getServers().iterator(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjective.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjective.java new file mode 100644 index 0000000000000..882afd661978b --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjective.java @@ -0,0 +1,412 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.util.ArrayList; + +/** +* Service objective. +*/ +public class ServiceObjective { + private String description; + + /** + * Optional. Gets or sets the service objective description. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Gets or sets the service objective description. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private ArrayList dimensionSettings; + + /** + * Optional. Gets or sets the service objective dimension settings. + * @return The DimensionSettings value. + */ + public ArrayList getDimensionSettings() { + return this.dimensionSettings; + } + + /** + * Optional. Gets or sets the service objective dimension settings. + * @param dimensionSettingsValue The DimensionSettings value. + */ + public void setDimensionSettings(final ArrayList dimensionSettingsValue) { + this.dimensionSettings = dimensionSettingsValue; + } + + private boolean enabled; + + /** + * Optional. Gets or sets a value indicating whether the service objective + * is enabled. + * @return The Enabled value. + */ + public boolean isEnabled() { + return this.enabled; + } + + /** + * Optional. Gets or sets a value indicating whether the service objective + * is enabled. + * @param enabledValue The Enabled value. + */ + public void setEnabled(final boolean enabledValue) { + this.enabled = enabledValue; + } + + private String id; + + /** + * Optional. Gets or sets the service objective id. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. Gets or sets the service objective id. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private boolean isDefault; + + /** + * Optional. Gets or sets a value indicating whether the service objective + * is the default objective. + * @return The IsDefault value. + */ + public boolean isDefault() { + return this.isDefault; + } + + /** + * Optional. Gets or sets a value indicating whether the service objective + * is the default objective. + * @param isDefaultValue The IsDefault value. + */ + public void setIsDefault(final boolean isDefaultValue) { + this.isDefault = isDefaultValue; + } + + private boolean isSystem; + + /** + * Optional. Gets or sets a value indicating whether the service objective + * is a system objective. + * @return The IsSystem value. + */ + public boolean isSystem() { + return this.isSystem; + } + + /** + * Optional. Gets or sets a value indicating whether the service objective + * is a system objective. + * @param isSystemValue The IsSystem value. + */ + public void setIsSystem(final boolean isSystemValue) { + this.isSystem = isSystemValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of the service objective. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of the service objective. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String parentLink; + + /** + * Optional. Gets or sets the ParentLink of the service objective. + * @return The ParentLink value. + */ + public String getParentLink() { + return this.parentLink; + } + + /** + * Optional. Gets or sets the ParentLink of the service objective. + * @param parentLinkValue The ParentLink value. + */ + public void setParentLink(final String parentLinkValue) { + this.parentLink = parentLinkValue; + } + + private String selfLink; + + /** + * Optional. Gets or sets the SelfLink of the service objective. + * @return The SelfLink value. + */ + public String getSelfLink() { + return this.selfLink; + } + + /** + * Optional. Gets or sets the SelfLink of the service objective. + * @param selfLinkValue The SelfLink value. + */ + public void setSelfLink(final String selfLinkValue) { + this.selfLink = selfLinkValue; + } + + private String state; + + /** + * Optional. Gets or sets the state of the service objective. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Gets or sets the state of the service objective. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private String type; + + /** + * Optional. Gets or sets the type of resource. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. Gets or sets the type of resource. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + + /** + * Initializes a new instance of the ServiceObjective class. + * + */ + public ServiceObjective() { + this.dimensionSettings = new ArrayList(); + } + + /** + * Dimension setting. + */ + public static class DimensionSettingResponse { + private String description; + + /** + * Optional. Gets or sets the dimension setting description. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Gets or sets the dimension setting description. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String id; + + /** + * Optional. Gets or sets the dimension setting id. + * @return The Id value. + */ + public String getId() { + return this.id; + } + + /** + * Optional. Gets or sets the dimension setting id. + * @param idValue The Id value. + */ + public void setId(final String idValue) { + this.id = idValue; + } + + private boolean isDefault; + + /** + * Optional. Gets or sets a value indicating whether the dimension + * setting is the default setting. + * @return The IsDefault value. + */ + public boolean isDefault() { + return this.isDefault; + } + + /** + * Optional. Gets or sets a value indicating whether the dimension + * setting is the default setting. + * @param isDefaultValue The IsDefault value. + */ + public void setIsDefault(final boolean isDefaultValue) { + this.isDefault = isDefaultValue; + } + + private String name; + + /** + * Optional. Gets or sets the name of the dimension setting. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Gets or sets the name of the dimension setting. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private byte ordinal; + + /** + * Optional. Gets or sets the dimension setting ordinal position. + * @return The Ordinal value. + */ + public byte getOrdinal() { + return this.ordinal; + } + + /** + * Optional. Gets or sets the dimension setting ordinal position. + * @param ordinalValue The Ordinal value. + */ + public void setOrdinal(final byte ordinalValue) { + this.ordinal = ordinalValue; + } + + private String parentLink; + + /** + * Optional. Gets or sets the ParentLink of the dimension setting. + * @return The ParentLink value. + */ + public String getParentLink() { + return this.parentLink; + } + + /** + * Optional. Gets or sets the ParentLink of the dimension setting. + * @param parentLinkValue The ParentLink value. + */ + public void setParentLink(final String parentLinkValue) { + this.parentLink = parentLinkValue; + } + + private String selfLink; + + /** + * Optional. Gets or sets the SelfLink of the dimension setting. + * @return The SelfLink value. + */ + public String getSelfLink() { + return this.selfLink; + } + + /** + * Optional. Gets or sets the SelfLink of the dimension setting. + * @param selfLinkValue The SelfLink value. + */ + public void setSelfLink(final String selfLinkValue) { + this.selfLink = selfLinkValue; + } + + private String state; + + /** + * Optional. Gets or sets the state of the dimension setting. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. Gets or sets the state of the dimension setting. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private String type; + + /** + * Optional. Gets or sets the type of resource. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. Gets or sets the type of resource. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjectiveGetResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjectiveGetResponse.java new file mode 100644 index 0000000000000..fc4eb55c1c80a --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjectiveGetResponse.java @@ -0,0 +1,50 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* Response containing the service objective for a given server and service +* objective Id. +*/ +public class ServiceObjectiveGetResponse extends OperationResponse { + private ServiceObjective serviceObjective; + + /** + * Optional. + * @return The ServiceObjective value. + */ + public ServiceObjective getServiceObjective() { + return this.serviceObjective; + } + + /** + * Optional. + * @param serviceObjectiveValue The ServiceObjective value. + */ + public void setServiceObjective(final ServiceObjective serviceObjectiveValue) { + this.serviceObjective = serviceObjectiveValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjectiveListResponse.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjectiveListResponse.java new file mode 100644 index 0000000000000..e6e8408b8502a --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/ServiceObjectiveListResponse.java @@ -0,0 +1,70 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* Response containing the list of service objective for a given server. +*/ +public class ServiceObjectiveListResponse extends OperationResponse implements Iterable { + private ArrayList serviceObjectives; + + /** + * Optional. Gets or sets the list of Service Objectives that are existing + * in a server. + * @return The ServiceObjectives value. + */ + public ArrayList getServiceObjectives() { + return this.serviceObjectives; + } + + /** + * Optional. Gets or sets the list of Service Objectives that are existing + * in a server. + * @param serviceObjectivesValue The ServiceObjectives value. + */ + public void setServiceObjectives(final ArrayList serviceObjectivesValue) { + this.serviceObjectives = serviceObjectivesValue; + } + + /** + * Initializes a new instance of the ServiceObjectiveListResponse class. + * + */ + public ServiceObjectiveListResponse() { + super(); + this.serviceObjectives = new ArrayList(); + } + + /** + * Gets the sequence of ServiceObjectives. + * + */ + public Iterator iterator() { + return this.getServiceObjectives().iterator(); + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/StatusInfo.java b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/StatusInfo.java new file mode 100644 index 0000000000000..8fc3943a751df --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/StatusInfo.java @@ -0,0 +1,206 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.sql.models; + +import java.net.URI; +import java.util.Calendar; + +/** +* Status of a DAC import. +*/ +public class StatusInfo { + private URI blobUri; + + /** + * Optional. Gets or sets the URI of the DAC file stored in Windows Azure + * Blob Storage to be imported. + * @return The BlobUri value. + */ + public URI getBlobUri() { + return this.blobUri; + } + + /** + * Optional. Gets or sets the URI of the DAC file stored in Windows Azure + * Blob Storage to be imported. + * @param blobUriValue The BlobUri value. + */ + public void setBlobUri(final URI blobUriValue) { + this.blobUri = blobUriValue; + } + + private String databaseName; + + /** + * Optional. Gets or sets the name of the database into which this DAC will + * be imported. + * @return The DatabaseName value. + */ + public String getDatabaseName() { + return this.databaseName; + } + + /** + * Optional. Gets or sets the name of the database into which this DAC will + * be imported. + * @param databaseNameValue The DatabaseName value. + */ + public void setDatabaseName(final String databaseNameValue) { + this.databaseName = databaseNameValue; + } + + private String errorMessage; + + /** + * Optional. Gets or sets the error message of the request if the request + * failed in some way. + * @return The ErrorMessage value. + */ + public String getErrorMessage() { + return this.errorMessage; + } + + /** + * Optional. Gets or sets the error message of the request if the request + * failed in some way. + * @param errorMessageValue The ErrorMessage value. + */ + public void setErrorMessage(final String errorMessageValue) { + this.errorMessage = errorMessageValue; + } + + private Calendar lastModifiedTime; + + /** + * Optional. Gets or sets the last time the status changed. + * @return The LastModifiedTime value. + */ + public Calendar getLastModifiedTime() { + return this.lastModifiedTime; + } + + /** + * Optional. Gets or sets the last time the status changed. + * @param lastModifiedTimeValue The LastModifiedTime value. + */ + public void setLastModifiedTime(final Calendar lastModifiedTimeValue) { + this.lastModifiedTime = lastModifiedTimeValue; + } + + private Calendar queuedTime; + + /** + * Optional. Gets or sets the time at which the import/export request was + * queued and the process initiated. + * @return The QueuedTime value. + */ + public Calendar getQueuedTime() { + return this.queuedTime; + } + + /** + * Optional. Gets or sets the time at which the import/export request was + * queued and the process initiated. + * @param queuedTimeValue The QueuedTime value. + */ + public void setQueuedTime(final Calendar queuedTimeValue) { + this.queuedTime = queuedTimeValue; + } + + private String requestId; + + /** + * Optional. Gets or sets the request ID of this import/export request, so + * that it can be tracked with future calls to GetStatus. + * @return The RequestId value. + */ + public String getRequestId() { + return this.requestId; + } + + /** + * Optional. Gets or sets the request ID of this import/export request, so + * that it can be tracked with future calls to GetStatus. + * @param requestIdValue The RequestId value. + */ + public void setRequestId(final String requestIdValue) { + this.requestId = requestIdValue; + } + + private String requestType; + + /** + * Optional. Gets or sets the type (Import/Export) of this request. + * @return The RequestType value. + */ + public String getRequestType() { + return this.requestType; + } + + /** + * Optional. Gets or sets the type (Import/Export) of this request. + * @param requestTypeValue The RequestType value. + */ + public void setRequestType(final String requestTypeValue) { + this.requestType = requestTypeValue; + } + + private String serverName; + + /** + * Optional. Gets or sets the name of the SQL database server into which + * this DAC will be imported or from which it will be exported. + * @return The ServerName value. + */ + public String getServerName() { + return this.serverName; + } + + /** + * Optional. Gets or sets the name of the SQL database server into which + * this DAC will be imported or from which it will be exported. + * @param serverNameValue The ServerName value. + */ + public void setServerName(final String serverNameValue) { + this.serverName = serverNameValue; + } + + private String status; + + /** + * Optional. Gets or sets the status of the import/export request. + * @return The Status value. + */ + public String getStatus() { + return this.status; + } + + /** + * Optional. Gets or sets the status of the import/export request. + * @param statusValue The Status value. + */ + public void setStatus(final String statusValue) { + this.status = statusValue; + } +} diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/package.html b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/package.html new file mode 100644 index 0000000000000..eed771a6f4c61 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/models/package.html @@ -0,0 +1,5 @@ + + +This package contains the models for the sql management service. + + diff --git a/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/package.html b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/package.html new file mode 100644 index 0000000000000..b911899ba3764 --- /dev/null +++ b/management-sql/src/main/java/com/microsoft/windowsazure/management/sql/package.html @@ -0,0 +1,6 @@ + + +This package contains the sql management class, + interface, and associated configuration and utility classes. + + diff --git a/management-sql/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/management-sql/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..d77f08cbd8fa5 --- /dev/null +++ b/management-sql/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1 @@ +com.microsoft.windowsazure.management.sql.Exports diff --git a/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DacOperationsIntegrationTest.java b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DacOperationsIntegrationTest.java new file mode 100644 index 0000000000000..d03820bc9c426 --- /dev/null +++ b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DacOperationsIntegrationTest.java @@ -0,0 +1,110 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.junit.*; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.DacExportParameters; +import com.microsoft.windowsazure.management.sql.models.DacImportParameters; +import com.microsoft.windowsazure.management.storage.models.StorageAccount; + +public class DacOperationsIntegrationTest extends SqlManagementIntegrationTestBase { + + private static StorageAccount storageAccount; + + @BeforeClass + public static void setup() throws Exception { + createService(); + createStorageService(); + databaseOperations = sqlManagementClient.getDatabasesOperations(); + serverOperations = sqlManagementClient.getServersOperations(); + dacOperations = sqlManagementClient.getDacOperations(); + storageAccount = createStorageAccount(testStorageAccountPrefix+randomString(10)); + } + + @AfterClass + public static void cleanup() { + for (String databaseName : databaseToBeRemoved.keySet()) { + String serverName = databaseToBeRemoved.get(databaseName); + try { + databaseOperations.delete(serverName, databaseName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + + databaseToBeRemoved.clear(); + + for (String serverName : serverToBeRemoved) { + try { + serverOperations.delete(serverName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + + serverToBeRemoved.clear(); + + try { + storageManagementClient.getStorageAccountsOperations().delete(storageAccount.getName()); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + + @Test + @Ignore("temporary disable because of long running ") + public void importDatabaseSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // arrange + String serverName = createServer(); + String azureEditionValue = "sqlazure"; + URI uriValue = storageAccount.getUri(); + String accessKey = getStorageKey(storageAccount.getName()); + DacImportParameters.BlobCredentialsParameter blobCredentialsValue = new DacImportParameters.BlobCredentialsParameter(); + blobCredentialsValue.setStorageAccessKey(accessKey); + blobCredentialsValue.setUri(uriValue); + + // act + DacImportParameters dacImportParameters = new DacImportParameters(); + dacImportParameters.setAzureEdition(azureEditionValue); + dacImportParameters.setBlobCredentials(blobCredentialsValue); + dacOperations.importDatabase(serverName, dacImportParameters); + } + + @Test + @Ignore("temporary disable because of long running ") + public void exportDatabaseSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // arrange + String serverName = createServer(); + URI uriValue = storageAccount.getUri(); + DacExportParameters.BlobCredentialsParameter blobCredentialsValue = new DacExportParameters.BlobCredentialsParameter(); + String accessKey = getStorageKey(storageAccount.getName()); + blobCredentialsValue.setStorageAccessKey(accessKey); + blobCredentialsValue.setUri(uriValue); + + // act + DacExportParameters dacExportParameters = new DacExportParameters(); + dacExportParameters.setBlobCredentials(blobCredentialsValue); + dacOperations.exportDatabase(serverName, dacExportParameters); + } +} \ No newline at end of file diff --git a/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperationsIntegrationTest.java b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperationsIntegrationTest.java new file mode 100644 index 0000000000000..80b959f05b069 --- /dev/null +++ b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DatabaseOperationOperationsIntegrationTest.java @@ -0,0 +1,88 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.junit.*; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperation; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperationGetResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseOperationListResponse; + +public class DatabaseOperationOperationsIntegrationTest extends SqlManagementIntegrationTestBase { + + private static Map databaseToBeRemoved = new HashMap(); + private static DatabaseOperationOperations databaseOperationOperations; + + @BeforeClass + public static void setup() throws Exception { + createService(); + databaseOperations = sqlManagementClient.getDatabasesOperations(); + serverOperations = sqlManagementClient.getServersOperations(); + databaseOperationOperations = sqlManagementClient.getDatabaseOperationsOperations(); + } + + @AfterClass + public static void cleanup() throws Exception { + for (String databaseName : databaseToBeRemoved.keySet()) { + String serverName = databaseToBeRemoved.get(databaseName); + databaseOperations.delete(serverName, databaseName); + } + + for (String serverName : serverToBeRemoved) { + serverOperations.delete(serverName); + } + } + + @Test + public void listDatabaseOperationsOperationSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String serverName = createServer(); + createDatabase(serverName); + + // act + DatabaseOperationListResponse databaseOperationOperationsListResponse = databaseOperationOperations.listByServer(serverName); + + // assert + assertEquals(1, databaseOperationOperationsListResponse.getDatabaseOperations().size()); + } + + @Test + public void getDatabaseOperationsOperationSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String serverName = createServer(); + createDatabase(serverName); + + // act + DatabaseOperationListResponse databaseOperationOperationsListResponse = databaseOperationOperations.listByServer(serverName); + DatabaseOperation databaseOperation = databaseOperationOperationsListResponse.getDatabaseOperations().get(0); + DatabaseOperationGetResponse databaseOperationGetResponse = databaseOperationOperations.get(serverName, databaseOperation.getId()); + DatabaseOperation actualDatabaseOperation = databaseOperationGetResponse.getDatabaseOperation(); + + // assert + assertEquals(databaseOperation.getDatabaseName(), actualDatabaseOperation.getDatabaseName()); + assertEquals(databaseOperation.getId(), actualDatabaseOperation.getId()); + } +} \ No newline at end of file diff --git a/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DatabaseOperationsIntegrationTest.java b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DatabaseOperationsIntegrationTest.java new file mode 100644 index 0000000000000..6a072a65d4d77 --- /dev/null +++ b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/DatabaseOperationsIntegrationTest.java @@ -0,0 +1,175 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.ArrayList; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.junit.*; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.Database; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseListResponse; +import com.microsoft.windowsazure.management.sql.models.DatabaseUpdateParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseUpdateResponse; + +public class DatabaseOperationsIntegrationTest extends SqlManagementIntegrationTestBase { + + @BeforeClass + public static void setup() throws Exception { + createService(); + databaseOperations = sqlManagementClient.getDatabasesOperations(); + serverOperations = sqlManagementClient.getServersOperations(); + } + + @AfterClass + public static void cleanup() throws Exception { + for (String databaseName : databaseToBeRemoved.keySet()) { + String serverName = databaseToBeRemoved.get(databaseName); + + try { + databaseOperations.delete(serverName, databaseName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + databaseToBeRemoved.clear(); + + for (String serverName : serverToBeRemoved) { + try { + serverOperations.delete(serverName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + + serverToBeRemoved.clear(); + } + + @Test + public void createDatabaseWithRequiredParameters() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String expectedServerName = createServer(); + String expectedCollationName = "SQL_Latin1_General_CP1_CI_AS"; + String expectedEdition = "Web"; + String expectedDatabaseName = "expecteddatabasename"; + int expectedMaximumDatabaseSizeInGBValue = 5; + + // act + DatabaseCreateParameters databaseCreateParameters = new DatabaseCreateParameters(); + databaseCreateParameters.setName(expectedDatabaseName); + databaseCreateParameters.setCollationName(expectedCollationName); + databaseCreateParameters.setEdition(expectedEdition); + databaseCreateParameters.setMaximumDatabaseSizeInGB(expectedMaximumDatabaseSizeInGBValue); + DatabaseCreateResponse databaseCreateResponse = databaseOperations.create(expectedServerName, databaseCreateParameters); + Database database= databaseCreateResponse.getDatabase(); + String databaseName = database.getName(); + databaseToBeRemoved.put(databaseName, expectedServerName); + + // assert + assertNotNull(databaseCreateResponse); + } + + @Test + public void createDatabaseWithOptionalParameters() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + int expectedMaximumDatabaseSizeInGBValue = 1; + String expectedDatabaseName = "expecteddatabasename"; + String expectedServerName = createServer(); + String expectedCollationName = "SQL_Latin1_General_CP1_CI_AS"; + String expectedEdition = "Web"; + + // act + DatabaseCreateParameters databaseCreateParameters = new DatabaseCreateParameters(); + databaseCreateParameters.setMaximumDatabaseSizeInGB(expectedMaximumDatabaseSizeInGBValue); + databaseCreateParameters.setName(expectedDatabaseName); + databaseCreateParameters.setCollationName(expectedCollationName); + databaseCreateParameters.setEdition(expectedEdition); + DatabaseCreateResponse databaseCreateResponse = databaseOperations.create(expectedServerName, databaseCreateParameters); + databaseToBeRemoved.put(databaseCreateResponse.getDatabase().getName(), expectedServerName); + + + // assert + assertEquals(expectedDatabaseName, databaseCreateResponse.getDatabase().getName()); + assertEquals(expectedMaximumDatabaseSizeInGBValue, databaseCreateResponse.getDatabase().getMaximumDatabaseSizeInGB()); + + } + + @Test + public void deleteDatabaseSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String expectedCollationName = "SQL_Latin1_General_CP1_CI_AS"; + String expectedEdition = "Web"; + String expectedDatabaseName = "expecteddatabasename"; + String serverName = createServer(); + int expectedMaxSizeInGB = 5; + + // act + DatabaseCreateParameters databaseCreateParameters = new DatabaseCreateParameters(); + databaseCreateParameters.setName(expectedDatabaseName); + databaseCreateParameters.setCollationName(expectedCollationName); + databaseCreateParameters.setEdition(expectedEdition); + databaseCreateParameters.setMaximumDatabaseSizeInGB(expectedMaxSizeInGB); + DatabaseCreateResponse databaseCreateResponse = databaseOperations.create(serverName, databaseCreateParameters); + String databaseName = databaseCreateResponse.getDatabase().getName(); + databaseOperations.delete(serverName, databaseName); + + // assert + DatabaseListResponse databaseListResponse = databaseOperations.list(serverName); + ArrayList databaseList = databaseListResponse.getDatabases(); + for (Database database : databaseList) { + assertNotEquals(databaseName, database.getName()); + } + } + + @Test + public void updateDatabaseSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String expectedCollationName = "SQL_Latin1_General_CP1_CI_AS"; + String expectedEdition = "Web"; + String updatedEdition = "Business"; + String expectedDatabaseName = "expecteddatabasename"; + String serverName = createServer(); + int expectedMaxSizeInGB = 5; + int updatedMaxSizeInGB = 10; + + // act + DatabaseCreateParameters databaseCreateParameters = new DatabaseCreateParameters(); + databaseCreateParameters.setName(expectedDatabaseName); + databaseCreateParameters.setCollationName(expectedCollationName); + databaseCreateParameters.setEdition(expectedEdition); + databaseCreateParameters.setMaximumDatabaseSizeInGB(expectedMaxSizeInGB); + DatabaseCreateResponse databaseCreateResponse = databaseOperations.create(serverName, databaseCreateParameters); + String databaseName = databaseCreateResponse.getDatabase().getName(); + databaseToBeRemoved.put(databaseName, serverName); + DatabaseUpdateParameters databaseUpdateParameters = new DatabaseUpdateParameters(); + databaseUpdateParameters.setName(expectedDatabaseName); + databaseUpdateParameters.setMaximumDatabaseSizeInGB(updatedMaxSizeInGB); + databaseUpdateParameters.setCollationName(expectedCollationName); + databaseUpdateParameters.setEdition(updatedEdition); + DatabaseUpdateResponse databaseUpdateResponse = databaseOperations.update(serverName, expectedDatabaseName, databaseUpdateParameters); + + // assert + assertEquals(updatedMaxSizeInGB, databaseUpdateResponse.getDatabase().getMaximumDatabaseSizeInGB()); + assertEquals(updatedEdition, databaseUpdateResponse.getDatabase().getEdition()); + } +} \ No newline at end of file diff --git a/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperationsIntegrationTest.java b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperationsIntegrationTest.java new file mode 100644 index 0000000000000..e68b06ba85ea5 --- /dev/null +++ b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/FirewallRuleOperationsIntegrationTest.java @@ -0,0 +1,152 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.ArrayList; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.junit.*; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.FirewallRule; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleCreateParameters; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleCreateResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleListResponse; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleUpdateParameters; +import com.microsoft.windowsazure.management.sql.models.FirewallRuleUpdateResponse; + +public class FirewallRuleOperationsIntegrationTest extends SqlManagementIntegrationTestBase { + private static FirewallRuleOperations firewallRuleOperations; + + @BeforeClass + public static void setup() throws Exception { + createService(); + firewallRuleOperations = sqlManagementClient.getFirewallRulesOperations(); + serverOperations = sqlManagementClient.getServersOperations(); + } + + @AfterClass + public static void cleanup() { + for (String firewallRuleName : firewallRuleToBeRemoved.keySet()) { + String serverName = firewallRuleToBeRemoved.get(firewallRuleName); + try { + firewallRuleOperations.delete(serverName, firewallRuleName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + + firewallRuleToBeRemoved.clear(); + + for (String serverName : serverToBeRemoved) { + try { + serverOperations.delete(serverName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + + serverToBeRemoved.clear(); + } + + @Test + public void createFirewallRuleWithRequiredParametersSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String expectedServerName = createServer(); + String expectedRuleName = "AllowAll"; + InetAddress expectedStartIpAddress = InetAddress.getByName("0.0.0.0"); + InetAddress expectedEndIpAddress = InetAddress.getByName("255.255.255.255"); + String expectedType = "Microsoft.SqlAzure.FirewallRule"; + + // act + FirewallRuleCreateParameters firewallRuleCreateParameters = new FirewallRuleCreateParameters(); + firewallRuleCreateParameters.setName(expectedRuleName); + firewallRuleCreateParameters.setStartIPAddress(expectedStartIpAddress); + firewallRuleCreateParameters.setEndIPAddress(expectedEndIpAddress); + FirewallRuleCreateResponse firewallRuleCreateResponse = firewallRuleOperations.create(expectedServerName, firewallRuleCreateParameters); + FirewallRule firewallRule = firewallRuleCreateResponse.getFirewallRule(); + String firewallRuleName = firewallRule.getName(); + firewallRuleToBeRemoved.put(firewallRuleName, expectedServerName); + + // assert + assertEquals(expectedRuleName, firewallRule.getName()); + assertEquals(expectedStartIpAddress, firewallRule.getStartIPAddress()); + assertEquals(expectedEndIpAddress, firewallRule.getEndIPAddress()); + assertEquals(expectedType, firewallRule.getType()); + } + + @Test + public void deleteFirewallRuleSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String expectedServerName = createServer(); + String expectedRuleName = "AllowAll"; + InetAddress expectedStartIpAddress = InetAddress.getByName("0.0.0.0"); + InetAddress expectedEndIpAddress = InetAddress.getByName("255.255.255.255"); + + // act + FirewallRuleCreateParameters firewallRuleCreateParameters = new FirewallRuleCreateParameters(); + firewallRuleCreateParameters.setName(expectedRuleName); + firewallRuleCreateParameters.setStartIPAddress(expectedStartIpAddress); + firewallRuleCreateParameters.setEndIPAddress(expectedEndIpAddress); + FirewallRuleCreateResponse firewallRuleCreateResponse = firewallRuleOperations.create(expectedServerName, firewallRuleCreateParameters); + FirewallRule expectedFirewallRule = firewallRuleCreateResponse.getFirewallRule(); + firewallRuleOperations.delete(expectedServerName, expectedRuleName); + + // assert + FirewallRuleListResponse firewallRuleListResponse = firewallRuleOperations.list(expectedServerName); + ArrayList firewallRuleList = firewallRuleListResponse.getFirewallRules(); + for (FirewallRule firewallRule : firewallRuleList) + { + assertNotEquals(expectedFirewallRule.getName(), firewallRule.getName()); + } + } + + @Test + public void updateRuleSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String expectedServerName = createServer(); + String expectedRuleName = "AllowAll"; + InetAddress expectedStartIpAddress = InetAddress.getByName("0.0.0.0"); + InetAddress expectedEndIpAddress = InetAddress.getByName("255.255.255.255"); + InetAddress updatedEndIpAddress = InetAddress.getByName("255.255.255.128"); + + // act + FirewallRuleCreateParameters firewallRuleCreateParameters = new FirewallRuleCreateParameters(); + firewallRuleCreateParameters.setName(expectedRuleName); + firewallRuleCreateParameters.setStartIPAddress(expectedStartIpAddress); + firewallRuleCreateParameters.setEndIPAddress(expectedEndIpAddress); + FirewallRuleCreateResponse firewallRuleCreateResponse = firewallRuleOperations.create(expectedServerName, firewallRuleCreateParameters); + FirewallRule firewallRule = firewallRuleCreateResponse.getFirewallRule(); + String firewallRuleName = firewallRule.getName(); + firewallRuleToBeRemoved.put(firewallRuleName, expectedServerName); + FirewallRuleUpdateParameters firewallRuleUpdateParameters = new FirewallRuleUpdateParameters(); + firewallRuleUpdateParameters.setEndIPAddress(updatedEndIpAddress); + firewallRuleUpdateParameters.setName(expectedRuleName); + firewallRuleUpdateParameters.setStartIPAddress(expectedStartIpAddress); + FirewallRuleUpdateResponse firewallRuleUpdateResponse = firewallRuleOperations.update(expectedServerName, expectedRuleName, firewallRuleUpdateParameters); + + // assert + FirewallRule updatedFirewallRule = firewallRuleUpdateResponse.getFirewallRule(); + assertEquals(updatedEndIpAddress, updatedFirewallRule.getEndIPAddress()); + assertEquals(expectedStartIpAddress, updatedFirewallRule.getStartIPAddress()); + assertEquals(expectedRuleName, updatedFirewallRule.getName()); + } +} \ No newline at end of file diff --git a/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveIntegrationTest.java b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveIntegrationTest.java new file mode 100644 index 0000000000000..f361c75f55090 --- /dev/null +++ b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/ServiceObjectiveIntegrationTest.java @@ -0,0 +1,97 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.junit.*; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.sql.models.ServiceObjective; +import com.microsoft.windowsazure.management.sql.models.ServiceObjectiveGetResponse; +import com.microsoft.windowsazure.management.sql.models.ServiceObjectiveListResponse; + +public class ServiceObjectiveIntegrationTest extends SqlManagementIntegrationTestBase { + + private static List serverToBeRemoved = new ArrayList(); + private static ServiceObjectiveOperations serviceObjectivesOperations; + + @BeforeClass + public static void setup() throws Exception { + createService(); + databaseOperations = sqlManagementClient.getDatabasesOperations(); + serverOperations = sqlManagementClient.getServersOperations(); + serviceObjectivesOperations = sqlManagementClient.getServiceObjectivesOperations(); + } + + @AfterClass + public static void cleanup() throws Exception { + for (String databaseName : databaseToBeRemoved.keySet()) { + String serverName = databaseToBeRemoved.get(databaseName); + try { + databaseOperations.delete(serverName, databaseName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + databaseToBeRemoved.clear(); + + for (String serverName : serverToBeRemoved) { + try { + serverOperations.delete(serverName); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + } + + @Test + public void listServiceObjectiveSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String serverName = createServer(); + createDatabase(serverName); + + // act + ServiceObjectiveListResponse serviceObjectiveListResponse = serviceObjectivesOperations.list(serverName); + + // assert + assertTrue(serviceObjectiveListResponse.getServiceObjectives().size() > 0); + } + + @Test + public void getServiceObjectiveSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // arrange + String serverName = createServer(); + createDatabase(serverName); + + // act + ServiceObjectiveListResponse serviceObjectivesListResponse = serviceObjectivesOperations.list(serverName); + ServiceObjective serviceObjective = serviceObjectivesListResponse.getServiceObjectives().get(0); + ServiceObjectiveGetResponse serviceObjectiveGetResponse = serviceObjectivesOperations.get(serverName, serviceObjective.getId()); + ServiceObjective actualServiceObjective = serviceObjectiveGetResponse.getServiceObjective(); + + // assert + assertEquals(serviceObjective.getId(), actualServiceObjective.getId()); + assertEquals(serviceObjective.getName(), actualServiceObjective.getName()); + assertEquals(serviceObjective.getName(), actualServiceObjective.getName()); + } +} \ No newline at end of file diff --git a/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/SqlManagementIntegrationTestBase.java b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/SqlManagementIntegrationTestBase.java new file mode 100644 index 0000000000000..7ce3b33a75338 --- /dev/null +++ b/management-sql/src/test/java/com/microsoft/windowsazure/management/sql/SqlManagementIntegrationTestBase.java @@ -0,0 +1,162 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.sql; + +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateParameters; +import com.microsoft.windowsazure.management.sql.models.DatabaseCreateResponse; +import com.microsoft.windowsazure.management.sql.models.ServerCreateParameters; +import com.microsoft.windowsazure.management.sql.models.ServerCreateResponse; +import com.microsoft.windowsazure.management.storage.StorageManagementClient; +import com.microsoft.windowsazure.management.storage.StorageManagementService; +import com.microsoft.windowsazure.management.storage.models.GeoRegionNames; +import com.microsoft.windowsazure.management.storage.models.StorageAccount; +import com.microsoft.windowsazure.management.storage.models.StorageAccountCreateParameters; +import com.microsoft.windowsazure.management.storage.models.StorageAccountGetKeysResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountGetResponse; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Alteration; +import com.microsoft.windowsazure.core.Builder.Registry; +import com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigurationProperties; +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.Configuration; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.filter.LoggingFilter; + +public abstract class SqlManagementIntegrationTestBase { + + protected static String testStorageAccountPrefix = "azsql"; + protected static SqlManagementClient sqlManagementClient; + protected static StorageManagementClient storageManagementClient; + protected static DatabaseOperations databaseOperations; + protected static ServerOperations serverOperations; + protected static DacOperations dacOperations; + protected static Map firewallRuleToBeRemoved = new HashMap(); + protected static List serverToBeRemoved = new ArrayList(); + protected static Map databaseToBeRemoved = new HashMap(); + + protected static String testAdministratorPasswordValue = "testAdminPassword!8"; + protected static String testAdministratorUserNameValue = "testadminuser"; + protected static String testLocationValue = "West US"; + + protected static void createService() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER, new DefaultHttpRequestRetryHandler()); + + sqlManagementClient = SqlManagementService.create(config); + } + + protected static void createStorageService() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Registry builder = (Registry) config.getBuilder(); + builder.alter(StorageManagementClient.class, Client.class, new Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + storageManagementClient = StorageManagementService.create(config); + } + + protected static StorageAccount createStorageAccount(String storageAccountName) throws Exception { + String storageAccountLabel = "Label"; + + StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters(); + createParameters.setName(storageAccountName); + createParameters.setLabel(storageAccountLabel); + createParameters.setLocation(GeoRegionNames.SOUTHCENTRALUS); + storageManagementClient.getStorageAccountsOperations().create(createParameters); + StorageAccountGetResponse storageAccountGetResponse = storageManagementClient.getStorageAccountsOperations().get(storageAccountName); + StorageAccount storageAccount = storageAccountGetResponse.getStorageAccount(); + return storageAccount; + } + + protected static String getStorageKey(String storageAccountName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + StorageAccountGetKeysResponse storageAccountGetKeyResponse = storageManagementClient.getStorageAccountsOperations().getKeys(storageAccountName); + return storageAccountGetKeyResponse.getPrimaryKey(); + } + + + protected String createServer() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + ServerCreateParameters serverCreateParameters = new ServerCreateParameters(); + serverCreateParameters.setAdministratorPassword(testAdministratorPasswordValue); + serverCreateParameters.setAdministratorUserName(testAdministratorUserNameValue); + serverCreateParameters.setLocation(testLocationValue); + ServerCreateResponse serverCreateResponse = serverOperations.create(serverCreateParameters); + String serverName = serverCreateResponse.getServerName(); + serverToBeRemoved.add(serverName); + return serverName; + + } + + protected String createDatabase(String serverName) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + String expectedCollationName = "SQL_Latin1_General_CP1_CI_AS"; + String expectedEdition = "Web"; + String expectedDatabaseName = "expecteddatabasename"; + int expectedMaxSizeInGB = 5; + + DatabaseCreateParameters databaseCreateParameters = new DatabaseCreateParameters(); + databaseCreateParameters.setName(expectedDatabaseName); + databaseCreateParameters.setCollationName(expectedCollationName); + databaseCreateParameters.setEdition(expectedEdition); + databaseCreateParameters.setMaximumDatabaseSizeInGB(expectedMaxSizeInGB); + DatabaseCreateResponse databaseCreateResponse = databaseOperations.create(serverName, databaseCreateParameters); + databaseToBeRemoved.put(databaseCreateResponse.getDatabase().getName(), serverName); + return databaseCreateResponse.getDatabase().getName(); + } + + protected static Configuration createConfiguration() throws Exception { + String baseUri = System.getenv(ManagementConfiguration.URI); + return ManagementConfiguration.configure( + baseUri != null ? new URI(baseUri) : null, + System.getenv(ManagementConfiguration.SUBSCRIPTION_ID), + System.getenv(ManagementConfiguration.KEYSTORE_PATH), + System.getenv(ManagementConfiguration.KEYSTORE_PASSWORD), + KeyStoreType.fromString(System.getenv(ManagementConfiguration.KEYSTORE_TYPE)) + ); + } + + protected static String randomString(int length) { + Random random = new Random(); + StringBuilder stringBuilder = new StringBuilder(length); + for (int i=0; i serverList = serverListResponse.iterator(); + Server createdServer = null; + while (serverList.hasNext()) { + Server nextServer = serverList.next(); + if (nextServer.getName().equals(serverName)) { + createdServer = nextServer; + } + } + assertNotNull(createdServer); + assertEquals(testAdministratorUserName, createdServer.getAdministratorUserName()); + assertEquals(testLocation, createdServer.getLocation()); + } + + @Test + public void deleteServerSuccess() throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + //arrange + String testAdministratorUserName = "testadminname"; + String testPassword = "testpassword8!"; + String testLocation = "West US"; + + // act + ServerCreateParameters serverCreateParameters = new ServerCreateParameters(); + serverCreateParameters.setAdministratorUserName(testAdministratorUserName); + serverCreateParameters.setAdministratorPassword(testPassword); + serverCreateParameters.setLocation(testLocation); + ServerCreateResponse serverCreateResponse = serverOperations.create(serverCreateParameters); + String serverName = serverCreateResponse.getServerName(); + serverOperations.delete(serverName); + + // assert + ServerListResponse serverListResponse = serverOperations.list(); + Iterator serverList = serverListResponse.iterator(); + Server createdServer = null; + while (serverList.hasNext()) { + Server nextServer = serverList.next(); + if (nextServer.getName().equals(serverName)) { + createdServer = nextServer; + } + } + assertNull(createdServer); + } +} \ No newline at end of file diff --git a/management-sql/src/test/resources/META-INF/com.microsoft.windowsazure.management.sql.properties b/management-sql/src/test/resources/META-INF/com.microsoft.windowsazure.management.sql.properties new file mode 100644 index 0000000000000..295003ddf9c6e --- /dev/null +++ b/management-sql/src/test/resources/META-INF/com.microsoft.windowsazure.management.sql.properties @@ -0,0 +1,7 @@ +management.keystore.path=%MANAGEMENT.KEYSTORE.PATH% +management.keystore.password=%MANAGEMENT.KEYSTORE.PASSWORD% +management.keystore.type=%MANAGEMENT.KEYSTORE.TYPE% +management.subscription.id=%MANAGEMENT.SUBSCRIPTION.ID% +management.uri=%MANAGEMENT.URI% +testprefix.com.microsoft.windowsazure.services.core.Configuration.connectTimeout=3 +testprefix.com.microsoft.windowsazure.services.core.Configuration.readTimeout=7 \ No newline at end of file diff --git a/management-storage/pom.xml b/management-storage/pom.xml new file mode 100644 index 0000000000000..03d50704b69ff --- /dev/null +++ b/management-storage/pom.xml @@ -0,0 +1,151 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-management-storage + jar + + Microsoft Azure Storage Management Client API + Microsoft Azure Storage Management SDK Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + 2.1.1 + 3.0.7.RELEASE + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + org.apache.httpcomponents + httpclient + + + javax.inject + javax.inject + + + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk16 + test + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+
+
diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/Exports.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/Exports.java new file mode 100644 index 0000000000000..d31805eae0f19 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/Exports.java @@ -0,0 +1,32 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.storage; + +import com.microsoft.windowsazure.core.Builder; + +/** + * The Class Exports. + */ +public class Exports implements Builder.Exports { + /* (non-Javadoc) + * @see com.microsoft.windowsazure.services.core.Builder.Exports#register(com.microsoft.windowsazure.services.core.Builder.Registry) + */ + @Override + public void register(final Builder.Registry registry) { + // provide contract implementation + registry.add(StorageManagementClient.class, + StorageManagementClientImpl.class); + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageAccountOperations.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageAccountOperations.java new file mode 100644 index 0000000000000..88e663456388e --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageAccountOperations.java @@ -0,0 +1,369 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.storage.models.CheckNameAvailabilityResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountCreateParameters; +import com.microsoft.windowsazure.management.storage.models.StorageAccountGetKeysResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountGetResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountListResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountRegenerateKeysParameters; +import com.microsoft.windowsazure.management.storage.models.StorageAccountRegenerateKeysResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountUpdateParameters; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the storage +* accounts beneath your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx for more +* information) +*/ +public interface StorageAccountOperations { + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse beginCreating(StorageAccountCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future beginCreatingAsync(StorageAccountCreateParameters parameters); + + /** + * The Check Name Availability operation checks if a storage account name is + * available for use in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx for + * more information) + * + * @param accountName Required. The desired storage account name to check + * for availability. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to a storage account check name availability request. + */ + CheckNameAvailabilityResponse checkNameAvailability(String accountName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Check Name Availability operation checks if a storage account name is + * available for use in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx for + * more information) + * + * @param accountName Required. The desired storage account name to check + * for availability. + * @return The response to a storage account check name availability request. + */ + Future checkNameAvailabilityAsync(String accountName); + + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse create(StorageAccountCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future createAsync(StorageAccountCreateParameters parameters); + + /** + * The Delete Storage Account operation deletes the specifiedstorage account + * from Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264517.aspx for + * more information) + * + * @param accountName Required. The name of the storage account. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String accountName) throws IOException, ServiceException; + + /** + * The Delete Storage Account operation deletes the specifiedstorage account + * from Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264517.aspx for + * more information) + * + * @param accountName Required. The name of the storage account. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String accountName); + + /** + * The Get Storage Account Properties operation returns system properties + * for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to get. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Storage Account Properties operation response. + */ + StorageAccountGetResponse get(String accountName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Storage Account Properties operation returns system properties + * for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to get. + * @return The Get Storage Account Properties operation response. + */ + Future getAsync(String accountName); + + /** + * The Get Storage Keys operation returns the primary and secondary access + * keys for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460785.aspx for + * more information) + * + * @param accountName Required. The name of the desired storage account. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The primary and secondary access keys for a storage account. + */ + StorageAccountGetKeysResponse getKeys(String accountName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Storage Keys operation returns the primary and secondary access + * keys for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460785.aspx for + * more information) + * + * @param accountName Required. The name of the desired storage account. + * @return The primary and secondary access keys for a storage account. + */ + Future getKeysAsync(String accountName); + + /** + * The List Storage Accounts operation lists the storage accounts available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460787.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Storage Accounts operation response. + */ + StorageAccountListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The List Storage Accounts operation lists the storage accounts available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460787.aspx for + * more information) + * + * @return The List Storage Accounts operation response. + */ + Future listAsync(); + + /** + * The Regenerate Keys operation regenerates the primary or secondary access + * key for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Regenerate Keys + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The primary and secondary access keys for a storage account. + */ + StorageAccountRegenerateKeysResponse regenerateKeys(StorageAccountRegenerateKeysParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException; + + /** + * The Regenerate Keys operation regenerates the primary or secondary access + * key for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Regenerate Keys + * operation. + * @return The primary and secondary access keys for a storage account. + */ + Future regenerateKeysAsync(StorageAccountRegenerateKeysParameters parameters); + + /** + * The Update Storage Account operation updates the label, the description, + * and enables or disables the geo-replication status for a storage account + * in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to update. + * @param parameters Required. Parameters supplied to the Update Storage + * Account operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse update(String accountName, StorageAccountUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Update Storage Account operation updates the label, the description, + * and enables or disables the geo-replication status for a storage account + * in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to update. + * @param parameters Required. Parameters supplied to the Update Storage + * Account operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future updateAsync(String accountName, StorageAccountUpdateParameters parameters); +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageAccountOperationsImpl.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageAccountOperationsImpl.java new file mode 100644 index 0000000000000..a056e45a1b51c --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageAccountOperationsImpl.java @@ -0,0 +1,1700 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.storage.models.CheckNameAvailabilityResponse; +import com.microsoft.windowsazure.management.storage.models.GeoRegionStatus; +import com.microsoft.windowsazure.management.storage.models.StorageAccount; +import com.microsoft.windowsazure.management.storage.models.StorageAccountCreateParameters; +import com.microsoft.windowsazure.management.storage.models.StorageAccountGetKeysResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountGetResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountListResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountProperties; +import com.microsoft.windowsazure.management.storage.models.StorageAccountRegenerateKeysParameters; +import com.microsoft.windowsazure.management.storage.models.StorageAccountRegenerateKeysResponse; +import com.microsoft.windowsazure.management.storage.models.StorageAccountStatus; +import com.microsoft.windowsazure.management.storage.models.StorageAccountUpdateParameters; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for managing the storage +* accounts beneath your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx for more +* information) +*/ +public class StorageAccountOperationsImpl implements ServiceOperations, StorageAccountOperations { + /** + * Initializes a new instance of the StorageAccountOperationsImpl class. + * + * @param client Reference to the service client. + */ + StorageAccountOperationsImpl(StorageManagementClientImpl client) { + this.client = client; + } + + private StorageManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.storage.StorageManagementClientImpl. + * @return The Client value. + */ + public StorageManagementClientImpl getClient() { + return this.client; + } + + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future beginCreatingAsync(final StorageAccountCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return beginCreating(parameters); + } + }); + } + + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse beginCreating(StorageAccountCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { + throw new IllegalArgumentException("parameters.Description"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getLabel().length() > 100) { + throw new IllegalArgumentException("parameters.Label"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + if (parameters.getName().length() < 3) { + throw new IllegalArgumentException("parameters.Name"); + } + if (parameters.getName().length() > 24) { + throw new IllegalArgumentException("parameters.Name"); + } + for (char nameChar : parameters.getName().toCharArray()) { + if (Character.isLowerCase(nameChar) == false && Character.isDigit(nameChar) == false) { + throw new IllegalArgumentException("parameters.Name"); + } + } + // TODO: Validate parameters.Name is a valid DNS name. + int locationCount = (parameters.getAffinityGroup() != null ? 1 : 0) + (parameters.getLocation() != null ? 1 : 0); + if (locationCount != 1) { + throw new IllegalArgumentException("Only one of parameters.AffinityGroup, parameters.Location may be provided."); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element createStorageServiceInputElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CreateStorageServiceInput"); + requestDoc.appendChild(createStorageServiceInputElement); + + Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceName"); + serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + createStorageServiceInputElement.appendChild(serviceNameElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + createStorageServiceInputElement.appendChild(labelElement); + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + createStorageServiceInputElement.appendChild(descriptionElement); + } else { + Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + nilAttribute.setValue("true"); + emptyElement.setAttributeNode(nilAttribute); + createStorageServiceInputElement.appendChild(emptyElement); + } + + if (parameters.getLocation() != null) { + Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Location"); + locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation())); + createStorageServiceInputElement.appendChild(locationElement); + } + + if (parameters.getAffinityGroup() != null) { + Element affinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + affinityGroupElement.appendChild(requestDoc.createTextNode(parameters.getAffinityGroup())); + createStorageServiceInputElement.appendChild(affinityGroupElement); + } + + Element geoReplicationEnabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "GeoReplicationEnabled"); + geoReplicationEnabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isGeoReplicationEnabled()).toLowerCase())); + createStorageServiceInputElement.appendChild(geoReplicationEnabledElement); + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + createStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Check Name Availability operation checks if a storage account name is + * available for use in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx for + * more information) + * + * @param accountName Required. The desired storage account name to check + * for availability. + * @return The response to a storage account check name availability request. + */ + @Override + public Future checkNameAvailabilityAsync(final String accountName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public CheckNameAvailabilityResponse call() throws Exception { + return checkNameAvailability(accountName); + } + }); + } + + /** + * The Check Name Availability operation checks if a storage account name is + * available for use in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154125.aspx for + * more information) + * + * @param accountName Required. The desired storage account name to check + * for availability. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response to a storage account check name availability request. + */ + @Override + public CheckNameAvailabilityResponse checkNameAvailability(String accountName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (accountName == null) { + throw new NullPointerException("accountName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("accountName", accountName); + CloudTracing.enter(invocationId, this, "checkNameAvailabilityAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices/operations/isavailable/" + accountName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + CheckNameAvailabilityResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new CheckNameAvailabilityResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element availabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "AvailabilityResponse"); + if (availabilityResponseElement != null) { + Element resultElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "Result"); + if (resultElement != null) { + boolean resultInstance; + resultInstance = DatatypeConverter.parseBoolean(resultElement.getTextContent().toLowerCase()); + result.setIsAvailable(resultInstance); + } + + Element reasonElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "Reason"); + if (reasonElement != null) { + boolean isNil = false; + Attr nilAttribute = reasonElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String reasonInstance; + reasonInstance = reasonElement.getTextContent(); + result.setReason(reasonInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future createAsync(final StorageAccountCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return create(parameters); + } + }); + } + + /** + * The Create Storage Account operation creates a new storage account in + * Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Storage + * Account operation. + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse create(StorageAccountCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException { + StorageManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + OperationResponse response = client2.getStorageAccountsOperations().beginCreatingAsync(parameters).get(); + OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != OperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(response.getRequestId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != OperationStatus.Succeeded) { + if (result.getError() != null) { + ServiceException ex = new ServiceException(result.getError().getCode() + " : " + result.getError().getMessage()); + ex.setErrorCode(result.getError().getCode()); + ex.setErrorMessage(result.getError().getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * The Delete Storage Account operation deletes the specifiedstorage account + * from Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264517.aspx for + * more information) + * + * @param accountName Required. The name of the storage account. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String accountName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(accountName); + } + }); + } + + /** + * The Delete Storage Account operation deletes the specifiedstorage account + * from Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264517.aspx for + * more information) + * + * @param accountName Required. The name of the storage account. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String accountName) throws IOException, ServiceException { + // Validate + if (accountName == null) { + throw new NullPointerException("accountName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("accountName", accountName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices/" + accountName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Storage Account Properties operation returns system properties + * for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to get. + * @return The Get Storage Account Properties operation response. + */ + @Override + public Future getAsync(final String accountName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public StorageAccountGetResponse call() throws Exception { + return get(accountName); + } + }); + } + + /** + * The Get Storage Account Properties operation returns system properties + * for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to get. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Storage Account Properties operation response. + */ + @Override + public StorageAccountGetResponse get(String accountName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (accountName == null) { + throw new NullPointerException("accountName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("accountName", accountName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices/" + accountName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + StorageAccountGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new StorageAccountGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element storageServiceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "StorageService"); + if (storageServiceElement != null) { + StorageAccount storageServiceInstance = new StorageAccount(); + result.setStorageAccount(storageServiceInstance); + + Element urlElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + storageServiceInstance.setUri(urlInstance); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + storageServiceInstance.setName(serviceNameInstance); + } + + Element storageServicePropertiesElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "StorageServiceProperties"); + if (storageServicePropertiesElement != null) { + StorageAccountProperties storageServicePropertiesInstance = new StorageAccountProperties(); + storageServiceInstance.setProperties(storageServicePropertiesInstance); + + Element descriptionElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + boolean isNil = false; + Attr nilAttribute = descriptionElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + storageServicePropertiesInstance.setDescription(descriptionInstance); + } + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + storageServicePropertiesInstance.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + storageServicePropertiesInstance.setLocation(locationInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + storageServicePropertiesInstance.setLabel(labelInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + StorageAccountStatus statusInstance; + statusInstance = StorageAccountStatus.valueOf(statusElement.getTextContent()); + storageServicePropertiesInstance.setStatus(statusInstance); + } + + Element endpointsSequenceElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Endpoints"); + if (endpointsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(endpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Endpoint").size(); i1 = i1 + 1) { + org.w3c.dom.Element endpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(endpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Endpoint").get(i1)); + storageServicePropertiesInstance.getEndpoints().add(new URI(endpointsElement.getTextContent())); + } + } + + Element geoReplicationEnabledElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoReplicationEnabled"); + if (geoReplicationEnabledElement != null) { + boolean geoReplicationEnabledInstance; + geoReplicationEnabledInstance = DatatypeConverter.parseBoolean(geoReplicationEnabledElement.getTextContent().toLowerCase()); + storageServicePropertiesInstance.setGeoReplicationEnabled(geoReplicationEnabledInstance); + } + + Element geoPrimaryRegionElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoPrimaryRegion"); + if (geoPrimaryRegionElement != null) { + String geoPrimaryRegionInstance; + geoPrimaryRegionInstance = geoPrimaryRegionElement.getTextContent(); + storageServicePropertiesInstance.setGeoPrimaryRegion(geoPrimaryRegionInstance); + } + + Element statusOfPrimaryElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "StatusOfPrimary"); + if (statusOfPrimaryElement != null && (statusOfPrimaryElement.getTextContent() == null || statusOfPrimaryElement.getTextContent().isEmpty() == true) == false) { + GeoRegionStatus statusOfPrimaryInstance; + statusOfPrimaryInstance = GeoRegionStatus.valueOf(statusOfPrimaryElement.getTextContent()); + storageServicePropertiesInstance.setStatusOfGeoPrimaryRegion(statusOfPrimaryInstance); + } + + Element lastGeoFailoverTimeElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "LastGeoFailoverTime"); + if (lastGeoFailoverTimeElement != null && (lastGeoFailoverTimeElement.getTextContent() == null || lastGeoFailoverTimeElement.getTextContent().isEmpty() == true) == false) { + Calendar lastGeoFailoverTimeInstance; + lastGeoFailoverTimeInstance = DatatypeConverter.parseDateTime(lastGeoFailoverTimeElement.getTextContent()); + storageServicePropertiesInstance.setLastGeoFailoverTime(lastGeoFailoverTimeInstance); + } + + Element geoSecondaryRegionElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoSecondaryRegion"); + if (geoSecondaryRegionElement != null) { + String geoSecondaryRegionInstance; + geoSecondaryRegionInstance = geoSecondaryRegionElement.getTextContent(); + storageServicePropertiesInstance.setGeoSecondaryRegion(geoSecondaryRegionInstance); + } + + Element statusOfSecondaryElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "StatusOfSecondary"); + if (statusOfSecondaryElement != null && (statusOfSecondaryElement.getTextContent() == null || statusOfSecondaryElement.getTextContent().isEmpty() == true) == false) { + GeoRegionStatus statusOfSecondaryInstance; + statusOfSecondaryInstance = GeoRegionStatus.valueOf(statusOfSecondaryElement.getTextContent()); + storageServicePropertiesInstance.setStatusOfGeoSecondaryRegion(statusOfSecondaryInstance); + } + } + + Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i2 = i2 + 1) { + org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i2)); + String extendedPropertiesKey = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + storageServiceInstance.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Storage Keys operation returns the primary and secondary access + * keys for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460785.aspx for + * more information) + * + * @param accountName Required. The name of the desired storage account. + * @return The primary and secondary access keys for a storage account. + */ + @Override + public Future getKeysAsync(final String accountName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public StorageAccountGetKeysResponse call() throws Exception { + return getKeys(accountName); + } + }); + } + + /** + * The Get Storage Keys operation returns the primary and secondary access + * keys for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460785.aspx for + * more information) + * + * @param accountName Required. The name of the desired storage account. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The primary and secondary access keys for a storage account. + */ + @Override + public StorageAccountGetKeysResponse getKeys(String accountName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (accountName == null) { + throw new NullPointerException("accountName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("accountName", accountName); + CloudTracing.enter(invocationId, this, "getKeysAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices/" + accountName.trim() + "/keys"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + StorageAccountGetKeysResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new StorageAccountGetKeysResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element storageServiceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "StorageService"); + if (storageServiceElement != null) { + Element urlElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + result.setUri(urlInstance); + } + + Element storageServiceKeysElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "StorageServiceKeys"); + if (storageServiceKeysElement != null) { + Element primaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement, "http://schemas.microsoft.com/windowsazure", "Primary"); + if (primaryElement != null) { + String primaryInstance; + primaryInstance = primaryElement.getTextContent(); + result.setPrimaryKey(primaryInstance); + } + + Element secondaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement, "http://schemas.microsoft.com/windowsazure", "Secondary"); + if (secondaryElement != null) { + String secondaryInstance; + secondaryInstance = secondaryElement.getTextContent(); + result.setSecondaryKey(secondaryInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Storage Accounts operation lists the storage accounts available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460787.aspx for + * more information) + * + * @return The List Storage Accounts operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public StorageAccountListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Storage Accounts operation lists the storage accounts available + * under the current subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460787.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Storage Accounts operation response. + */ + @Override + public StorageAccountListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + StorageAccountListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new StorageAccountListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element storageServicesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "StorageServices"); + if (storageServicesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storageServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "StorageService").size(); i1 = i1 + 1) { + org.w3c.dom.Element storageServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storageServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "StorageService").get(i1)); + StorageAccount storageServiceInstance = new StorageAccount(); + result.getStorageAccounts().add(storageServiceInstance); + + Element urlElement = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + storageServiceInstance.setUri(urlInstance); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + storageServiceInstance.setName(serviceNameInstance); + } + + Element storageServicePropertiesElement = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "StorageServiceProperties"); + if (storageServicePropertiesElement != null) { + StorageAccountProperties storageServicePropertiesInstance = new StorageAccountProperties(); + storageServiceInstance.setProperties(storageServicePropertiesInstance); + + Element descriptionElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + boolean isNil = false; + Attr nilAttribute = descriptionElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + storageServicePropertiesInstance.setDescription(descriptionInstance); + } + } + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + String affinityGroupInstance; + affinityGroupInstance = affinityGroupElement.getTextContent(); + storageServicePropertiesInstance.setAffinityGroup(affinityGroupInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + storageServicePropertiesInstance.setLocation(locationInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + storageServicePropertiesInstance.setLabel(labelInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + StorageAccountStatus statusInstance; + statusInstance = StorageAccountStatus.valueOf(statusElement.getTextContent()); + storageServicePropertiesInstance.setStatus(statusInstance); + } + + Element endpointsSequenceElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Endpoints"); + if (endpointsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(endpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Endpoint").size(); i2 = i2 + 1) { + org.w3c.dom.Element endpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(endpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Endpoint").get(i2)); + storageServicePropertiesInstance.getEndpoints().add(new URI(endpointsElement.getTextContent())); + } + } + + Element geoReplicationEnabledElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoReplicationEnabled"); + if (geoReplicationEnabledElement != null) { + boolean geoReplicationEnabledInstance; + geoReplicationEnabledInstance = DatatypeConverter.parseBoolean(geoReplicationEnabledElement.getTextContent().toLowerCase()); + storageServicePropertiesInstance.setGeoReplicationEnabled(geoReplicationEnabledInstance); + } + + Element geoPrimaryRegionElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoPrimaryRegion"); + if (geoPrimaryRegionElement != null) { + String geoPrimaryRegionInstance; + geoPrimaryRegionInstance = geoPrimaryRegionElement.getTextContent(); + storageServicePropertiesInstance.setGeoPrimaryRegion(geoPrimaryRegionInstance); + } + + Element statusOfPrimaryElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "StatusOfPrimary"); + if (statusOfPrimaryElement != null && (statusOfPrimaryElement.getTextContent() == null || statusOfPrimaryElement.getTextContent().isEmpty() == true) == false) { + GeoRegionStatus statusOfPrimaryInstance; + statusOfPrimaryInstance = GeoRegionStatus.valueOf(statusOfPrimaryElement.getTextContent()); + storageServicePropertiesInstance.setStatusOfGeoPrimaryRegion(statusOfPrimaryInstance); + } + + Element lastGeoFailoverTimeElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "LastGeoFailoverTime"); + if (lastGeoFailoverTimeElement != null && (lastGeoFailoverTimeElement.getTextContent() == null || lastGeoFailoverTimeElement.getTextContent().isEmpty() == true) == false) { + Calendar lastGeoFailoverTimeInstance; + lastGeoFailoverTimeInstance = DatatypeConverter.parseDateTime(lastGeoFailoverTimeElement.getTextContent()); + storageServicePropertiesInstance.setLastGeoFailoverTime(lastGeoFailoverTimeInstance); + } + + Element geoSecondaryRegionElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoSecondaryRegion"); + if (geoSecondaryRegionElement != null) { + String geoSecondaryRegionInstance; + geoSecondaryRegionInstance = geoSecondaryRegionElement.getTextContent(); + storageServicePropertiesInstance.setGeoSecondaryRegion(geoSecondaryRegionInstance); + } + + Element statusOfSecondaryElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "StatusOfSecondary"); + if (statusOfSecondaryElement != null && (statusOfSecondaryElement.getTextContent() == null || statusOfSecondaryElement.getTextContent().isEmpty() == true) == false) { + GeoRegionStatus statusOfSecondaryInstance; + statusOfSecondaryInstance = GeoRegionStatus.valueOf(statusOfSecondaryElement.getTextContent()); + storageServicePropertiesInstance.setStatusOfGeoSecondaryRegion(statusOfSecondaryInstance); + } + } + + Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + if (extendedPropertiesSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").size(); i3 = i3 + 1) { + org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty").get(i3)); + String extendedPropertiesKey = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String extendedPropertiesValue = XmlUtility.getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + storageServiceInstance.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Regenerate Keys operation regenerates the primary or secondary access + * key for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Regenerate Keys + * operation. + * @return The primary and secondary access keys for a storage account. + */ + @Override + public Future regenerateKeysAsync(final StorageAccountRegenerateKeysParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public StorageAccountRegenerateKeysResponse call() throws Exception { + return regenerateKeys(parameters); + } + }); + } + + /** + * The Regenerate Keys operation regenerates the primary or secondary access + * key for the specified storage account. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Regenerate Keys + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The primary and secondary access keys for a storage account. + */ + @Override + public StorageAccountRegenerateKeysResponse regenerateKeys(StorageAccountRegenerateKeysParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "regenerateKeysAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices/" + parameters.getName().trim() + "/keys" + "?" + "action=regenerate"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element regenerateKeysElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RegenerateKeys"); + requestDoc.appendChild(regenerateKeysElement); + + Element keyTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyType"); + keyTypeElement.appendChild(requestDoc.createTextNode(parameters.getKeyType().toString())); + regenerateKeysElement.appendChild(keyTypeElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + StorageAccountRegenerateKeysResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new StorageAccountRegenerateKeysResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element storageServiceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "StorageService"); + if (storageServiceElement != null) { + Element urlElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + result.setUri(urlInstance); + } + + Element storageServiceKeysElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "StorageServiceKeys"); + if (storageServiceKeysElement != null) { + Element primaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement, "http://schemas.microsoft.com/windowsazure", "Primary"); + if (primaryElement != null) { + String primaryInstance; + primaryInstance = primaryElement.getTextContent(); + result.setPrimaryKey(primaryInstance); + } + + Element secondaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement, "http://schemas.microsoft.com/windowsazure", "Secondary"); + if (secondaryElement != null) { + String secondaryInstance; + secondaryInstance = secondaryElement.getTextContent(); + result.setSecondaryKey(secondaryInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Update Storage Account operation updates the label, the description, + * and enables or disables the geo-replication status for a storage account + * in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to update. + * @param parameters Required. Parameters supplied to the Update Storage + * Account operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future updateAsync(final String accountName, final StorageAccountUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return update(accountName, parameters); + } + }); + } + + /** + * The Update Storage Account operation updates the label, the description, + * and enables or disables the geo-replication status for a storage account + * in Windows Azure. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx for + * more information) + * + * @param accountName Required. Name of the storage account to update. + * @param parameters Required. Parameters supplied to the Update Storage + * Account operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse update(String accountName, StorageAccountUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (accountName == null) { + throw new NullPointerException("accountName"); + } + if (accountName.length() < 3) { + throw new IllegalArgumentException("accountName"); + } + if (accountName.length() > 24) { + throw new IllegalArgumentException("accountName"); + } + for (char accountNameChar : accountName.toCharArray()) { + if (Character.isLowerCase(accountNameChar) == false && Character.isDigit(accountNameChar) == false) { + throw new IllegalArgumentException("accountName"); + } + } + // TODO: Validate accountName is a valid DNS name. + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { + throw new IllegalArgumentException("parameters.Description"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("accountName", accountName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/storageservices/" + accountName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element updateStorageServiceInputElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateStorageServiceInput"); + requestDoc.appendChild(updateStorageServiceInputElement); + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + updateStorageServiceInputElement.appendChild(descriptionElement); + } else { + Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + nilAttribute.setValue("true"); + emptyElement.setAttributeNode(nilAttribute); + updateStorageServiceInputElement.appendChild(emptyElement); + } + + if (parameters.getLabel() != null) { + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + updateStorageServiceInputElement.appendChild(labelElement); + } + + if (parameters.isGeoReplicationEnabled() != null) { + Element geoReplicationEnabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "GeoReplicationEnabled"); + geoReplicationEnabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isGeoReplicationEnabled()).toLowerCase())); + updateStorageServiceInputElement.appendChild(geoReplicationEnabledElement); + } + + if (parameters.getExtendedProperties() != null) { + Element extendedPropertiesDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); + for (Map.Entry entry : parameters.getExtendedProperties().entrySet()) { + String extendedPropertiesKey = entry.getKey(); + String extendedPropertiesValue = entry.getValue(); + Element extendedPropertiesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); + extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); + + Element extendedPropertiesKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); + extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); + + Element extendedPropertiesValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); + extendedPropertiesElement.appendChild(extendedPropertiesValueElement); + } + updateStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementClient.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementClient.java new file mode 100644 index 0000000000000..e8305ab5d03cb --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementClient.java @@ -0,0 +1,125 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage; + +import com.microsoft.windowsazure.core.FilterableService; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import java.io.Closeable; +import java.io.IOException; +import java.net.URI; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API provides programmatic access to much of the +* functionality available through the Management Portal. The Service +* Management API is a REST API. All API operations are performed over SSL and +* mutually authenticated using X.509 v3 certificates. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for more +* information) +*/ +public interface StorageManagementClient extends Closeable, FilterableService { + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + URI getBaseUri(); + + /** + * When you create a Windows Azure subscription, it is uniquely identified + * by a subscription ID. The subscription ID forms part of the URI for + * every call that you make to the Service Management API. The Windows + * Azure Service ManagementAPI use mutual authentication of management + * certificates over SSL to ensure that a request made to the service is + * secure. No anonymous requests are allowed. + * @return The Credentials value. + */ + SubscriptionCloudCredentials getCredentials(); + + /** + * The Service Management API includes operations for managing the storage + * accounts beneath your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx for + * more information) + * @return The StorageAccountsOperations value. + */ + StorageAccountOperations getStorageAccountsOperations(); + + /** + * The Get Operation Status operation returns the status of thespecified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Operation Status operation returns the status of thespecified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future getOperationStatusAsync(String requestId); +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementClientImpl.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementClientImpl.java new file mode 100644 index 0000000000000..2178f8d6f0ced --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementClientImpl.java @@ -0,0 +1,365 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage; + +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceClient; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import javax.inject.Inject; +import javax.inject.Named; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API provides programmatic access to much of the +* functionality available through the Management Portal. The Service +* Management API is a REST API. All API operations are performed over SSL and +* mutually authenticated using X.509 v3 certificates. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for more +* information) +*/ +public class StorageManagementClientImpl extends ServiceClient implements StorageManagementClient { + private URI baseUri; + + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + public URI getBaseUri() { + return this.baseUri; + } + + private SubscriptionCloudCredentials credentials; + + /** + * When you create a Windows Azure subscription, it is uniquely identified + * by a subscription ID. The subscription ID forms part of the URI for + * every call that you make to the Service Management API. The Windows + * Azure Service ManagementAPI use mutual authentication of management + * certificates over SSL to ensure that a request made to the service is + * secure. No anonymous requests are allowed. + * @return The Credentials value. + */ + public SubscriptionCloudCredentials getCredentials() { + return this.credentials; + } + + private StorageAccountOperations storageAccounts; + + /** + * The Service Management API includes operations for managing the storage + * accounts beneath your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx for + * more information) + * @return The StorageAccountsOperations value. + */ + public StorageAccountOperations getStorageAccountsOperations() { + return this.storageAccounts; + } + + /** + * Initializes a new instance of the StorageManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + private StorageManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) { + super(httpBuilder, executorService); + this.storageAccounts = new StorageAccountOperationsImpl(this); + } + + /** + * Initializes a new instance of the StorageManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create a Windows Azure + * subscription, it is uniquely identified by a subscription ID. The + * subscription ID forms part of the URI for every call that you make to + * the Service Management API. The Windows Azure Service ManagementAPI use + * mutual authentication of management certificates over SSL to ensure that + * a request made to the service is secure. No anonymous requests are + * allowed. + * @param baseUri Required. The URI used as the base for all Service + * Management requests. + */ + @Inject + public StorageManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } else { + this.credentials = credentials; + } + if (baseUri == null) { + try { + this.baseUri = new URI("https://management.core.windows.net"); + } + catch (URISyntaxException ex) { + } + } else { + this.baseUri = baseUri; + } + } + + /** + * Initializes a new instance of the StorageManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create a Windows Azure + * subscription, it is uniquely identified by a subscription ID. The + * subscription ID forms part of the URI for every call that you make to + * the Service Management API. The Windows Azure Service ManagementAPI use + * mutual authentication of management certificates over SSL to ensure that + * a request made to the service is secure. No anonymous requests are + * allowed. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + */ + public StorageManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } + this.credentials = credentials; + this.baseUri = new URI("https://management.core.windows.net"); + } + + /** + * Initializes a new instance of the StorageManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + protected StorageManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) { + return new StorageManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri()); + } + + /** + * The Get Operation Status operation returns the status of thespecified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future getOperationStatusAsync(final String requestId) { + return this.getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return getOperationStatus(requestId); + } + }); + } + + /** + * The Get Operation Status operation returns the status of thespecified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (requestId == null) { + throw new NullPointerException("requestId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("requestId", requestId); + CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getBaseUri().toString(); + String url = "/" + this.getCredentials().getSubscriptionId().trim() + "/operations/" + requestId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new OperationStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setId(idInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + OperationStatus statusInstance; + statusInstance = OperationStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "HttpStatusCode"); + if (httpStatusCodeElement != null) { + Integer httpStatusCodeInstance; + httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent()); + result.setHttpStatusCode(httpStatusCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); + result.setError(errorInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + errorInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + errorInstance.setMessage(messageInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementService.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementService.java new file mode 100644 index 0000000000000..d1377a9170b6e --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/StorageManagementService.java @@ -0,0 +1,75 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.storage; + +import com.microsoft.windowsazure.Configuration; + +/** + * + * Access service management functionality. + * + */ +public final class StorageManagementService { + private StorageManagementService() { + // class is not instantiated + } + + /** + * Creates an instance of the StorageManagementClient API. + * @return An instance of the StorageManagementClient API. + */ + public static StorageManagementClient create() { + return Configuration.getInstance().create( + StorageManagementClient.class); + } + + /** + * Creates an instance of the StorageManagementClient API using + * the specified configuration. + * + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the StorageManagementClient API. + */ + public static StorageManagementClient create(final Configuration config) { + return config.create(StorageManagementClient.class); + } + + /** + * Creates an instance of the StorageManagementClient API. + * + * @param profile A String object that representing the profile + * of the service management service. + * @return An instance of the StorageManagementClient API. + */ + public static StorageManagementClient create(final String profile) { + return Configuration.getInstance().create(profile, + StorageManagementClient.class); + } + + /** + * Creates an instance of the ManagementClient API using the + * specified configuration. + * + * @param profile The profile. + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the StorageManagementClient API. + */ + public static StorageManagementClient create(final String profile, + final Configuration config) { + return config.create(profile, StorageManagementClient.class); + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/CheckNameAvailabilityResponse.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/CheckNameAvailabilityResponse.java new file mode 100644 index 0000000000000..f2d3ab167dae2 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/CheckNameAvailabilityResponse.java @@ -0,0 +1,71 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The response to a storage account check name availability request. +*/ +public class CheckNameAvailabilityResponse extends OperationResponse { + private boolean isAvailable; + + /** + * Optional. The result of the availability request. True if the name is + * available, false otherwise + * @return The IsAvailable value. + */ + public boolean isAvailable() { + return this.isAvailable; + } + + /** + * Optional. The result of the availability request. True if the name is + * available, false otherwise + * @param isAvailableValue The IsAvailable value. + */ + public void setIsAvailable(final boolean isAvailableValue) { + this.isAvailable = isAvailableValue; + } + + private String reason; + + /** + * Optional. The reason for unavailability, if the requested name is + * unavailable + * @return The Reason value. + */ + public String getReason() { + return this.reason; + } + + /** + * Optional. The reason for unavailability, if the requested name is + * unavailable + * @param reasonValue The Reason value. + */ + public void setReason(final String reasonValue) { + this.reason = reasonValue; + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/GeoRegionNames.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/GeoRegionNames.java new file mode 100644 index 0000000000000..feb496e01e9f4 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/GeoRegionNames.java @@ -0,0 +1,41 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +/** +* The geographical region in which a storage account exists. +*/ +public abstract class GeoRegionNames { + public static final String NORTHCENTRALUS = "North Central US"; + + public static final String SOUTHCENTRALUS = "South Central US"; + + public static final String WESTEUROPE = "West Europe"; + + public static final String NORTHEUROPE = "North Europe"; + + public static final String SOUTHEASTASIA = "Southeast Asia"; + + public static final String EASTASIA = "East Asia"; +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/GeoRegionStatus.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/GeoRegionStatus.java new file mode 100644 index 0000000000000..99c8f95d5a647 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/GeoRegionStatus.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +/** +* Indicates whether the storage region is available. +*/ +public enum GeoRegionStatus { + Available, + + Unavailable, +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccount.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccount.java new file mode 100644 index 0000000000000..17fa0d8ff26db --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccount.java @@ -0,0 +1,140 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import java.net.URI; +import java.util.HashMap; + +/** +* A Storage Service associated with your subscription. +*/ +public class StorageAccount { + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended storage account property. + * Each extended property must have both a defined name and value. You can + * have a maximum of 50 extended property name/value pairs. The maximum + * length of the Name element is 64 characters, only alphanumeric + * characters and underscores are valid in the Name, and the name must + * start with a letter. Attempting to use other characters, starting the + * Name with a non-letter character, or entering a name that is identical + * to that of another extended property owned by the same storage account, + * will result in a status code 400 (Bad Request) error. Each extended + * property value has a maximum length of 255 characters. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended storage account property. + * Each extended property must have both a defined name and value. You can + * have a maximum of 50 extended property name/value pairs. The maximum + * length of the Name element is 64 characters, only alphanumeric + * characters and underscores are valid in the Name, and the name must + * start with a letter. Attempting to use other characters, starting the + * Name with a non-letter character, or entering a name that is identical + * to that of another extended property owned by the same storage account, + * will result in a status code 400 (Bad Request) error. Each extended + * property value has a maximum length of 255 characters. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private String name; + + /** + * Optional. The name of the storage account. This name is the DNS prefix + * name and can be used to access blobs, queues, and tables in the storage + * account. For example, if the service name is MyStorageAccount you could + * access the blob containers by calling: + * http://MyStorageAccount.blob.core.windows.net/mycontainer/ + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the storage account. This name is the DNS prefix + * name and can be used to access blobs, queues, and tables in the storage + * account. For example, if the service name is MyStorageAccount you could + * access the blob containers by calling: + * http://MyStorageAccount.blob.core.windows.net/mycontainer/ + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private StorageAccountProperties properties; + + /** + * Optional. Details about the storage account. + * @return The Properties value. + */ + public StorageAccountProperties getProperties() { + return this.properties; + } + + /** + * Optional. Details about the storage account. + * @param propertiesValue The Properties value. + */ + public void setProperties(final StorageAccountProperties propertiesValue) { + this.properties = propertiesValue; + } + + private URI uri; + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + + /** + * Initializes a new instance of the StorageAccount class. + * + */ + public StorageAccount() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountCreateParameters.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountCreateParameters.java new file mode 100644 index 0000000000000..49ab05275ead1 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountCreateParameters.java @@ -0,0 +1,223 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import java.util.HashMap; + +/** +* Parameters supplied to the Create Storage Account operation. +*/ +public class StorageAccountCreateParameters { + private String affinityGroup; + + /** + * Optional. Required if Location is not specified. The name of an existing + * affinity group in the specified subscription. You can include either a + * Location or AffinityGroup element in the request body, but not both. To + * list available affinity groups, use the List Affinity Groups operation. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. Required if Location is not specified. The name of an existing + * affinity group in the specified subscription. You can include either a + * Location or AffinityGroup element in the request body, but not both. To + * list available affinity groups, use the List Affinity Groups operation. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String description; + + /** + * Optional. A description for the storage account. The description may be + * up to 1024 characters in length. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. A description for the storage account. The description may be + * up to 1024 characters in length. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended storage account property. + * Each extended property must have both a defined name and value. You can + * have a maximum of 50 extended property name/value pairs. The maximum + * length of the Name element is 64 characters, only alphanumeric + * characters and underscores are valid in the Name, and the name must + * start with a letter. Attempting to use other characters, starting the + * Name with a non-letter character, or entering a name that is identical + * to that of another extended property owned by the same storage account, + * will result in a status code 400 (Bad Request) error. Each extended + * property value has a maximum length of 255 characters. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended storage account property. + * Each extended property must have both a defined name and value. You can + * have a maximum of 50 extended property name/value pairs. The maximum + * length of the Name element is 64 characters, only alphanumeric + * characters and underscores are valid in the Name, and the name must + * start with a letter. Attempting to use other characters, starting the + * Name with a non-letter character, or entering a name that is identical + * to that of another extended property owned by the same storage account, + * will result in a status code 400 (Bad Request) error. Each extended + * property value has a maximum length of 255 characters. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private boolean geoReplicationEnabled; + + /** + * Optional. Specifies whether the storage account is created with the + * geo-replication enabled. If the element is not included in the request + * body, the default value is true. If set to true, the data in the storage + * account is replicated across more than one geographic location so as to + * enable resilience in the face of catastrophic service loss. + * @return The GeoReplicationEnabled value. + */ + public boolean isGeoReplicationEnabled() { + return this.geoReplicationEnabled; + } + + /** + * Optional. Specifies whether the storage account is created with the + * geo-replication enabled. If the element is not included in the request + * body, the default value is true. If set to true, the data in the storage + * account is replicated across more than one geographic location so as to + * enable resilience in the face of catastrophic service loss. + * @param geoReplicationEnabledValue The GeoReplicationEnabled value. + */ + public void setGeoReplicationEnabled(final boolean geoReplicationEnabledValue) { + this.geoReplicationEnabled = geoReplicationEnabledValue; + } + + private String label; + + /** + * Required. A name for the storage account specified as abase64-encoded + * string. The name may be up to 100 characters inlength. The name can be + * used identify the storage account for yourtracking purposes. + * @return The Label value. + */ + public String getLabel() { + if (this.label == null) { + return this.getName(); + } else { + return this.label; + } + } + + /** + * Required. A name for the storage account specified as abase64-encoded + * string. The name may be up to 100 characters inlength. The name can be + * used identify the storage account for yourtracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. Required if AffinityGroup is not specified. The location where + * the storage account is created. You can include either a Location or + * AffinityGroup element in the request body, but not both. To list + * available locations, use the List Locations operation. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. Required if AffinityGroup is not specified. The location where + * the storage account is created. You can include either a Location or + * AffinityGroup element in the request body, but not both. To list + * available locations, use the List Locations operation. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private String name; + + /** + * Required. A name for the storage account that is unique within Windows + * Azure. Storage account names must be between 3 and 24 characters in + * length and use numbers and lower-case letters only. This name is the + * DNS prefix name and can be used to access blobs, queues, and tables in + * the storage account. For example: + * http://ServiceName.blob.core.windows.net/mycontainer/ + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. A name for the storage account that is unique within Windows + * Azure. Storage account names must be between 3 and 24 characters in + * length and use numbers and lower-case letters only. This name is the + * DNS prefix name and can be used to access blobs, queues, and tables in + * the storage account. For example: + * http://ServiceName.blob.core.windows.net/mycontainer/ + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + /** + * Initializes a new instance of the StorageAccountCreateParameters class. + * + */ + public StorageAccountCreateParameters() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountGetKeysResponse.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountGetKeysResponse.java new file mode 100644 index 0000000000000..83e98e8f2b219 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountGetKeysResponse.java @@ -0,0 +1,88 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* The primary and secondary access keys for a storage account. +*/ +public class StorageAccountGetKeysResponse extends OperationResponse { + private String primaryKey; + + /** + * Optional. The primary access key for the storage account. + * @return The PrimaryKey value. + */ + public String getPrimaryKey() { + return this.primaryKey; + } + + /** + * Optional. The primary access key for the storage account. + * @param primaryKeyValue The PrimaryKey value. + */ + public void setPrimaryKey(final String primaryKeyValue) { + this.primaryKey = primaryKeyValue; + } + + private String secondaryKey; + + /** + * Optional. The secondary access key for the storage account. + * @return The SecondaryKey value. + */ + public String getSecondaryKey() { + return this.secondaryKey; + } + + /** + * Optional. The secondary access key for the storage account. + * @param secondaryKeyValue The SecondaryKey value. + */ + public void setSecondaryKey(final String secondaryKeyValue) { + this.secondaryKey = secondaryKeyValue; + } + + private URI uri; + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountGetResponse.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountGetResponse.java new file mode 100644 index 0000000000000..551b7f38b5420 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountGetResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Storage Account Properties operation response. +*/ +public class StorageAccountGetResponse extends OperationResponse { + private StorageAccount storageAccount; + + /** + * Optional. + * @return The StorageAccount value. + */ + public StorageAccount getStorageAccount() { + return this.storageAccount; + } + + /** + * Optional. + * @param storageAccountValue The StorageAccount value. + */ + public void setStorageAccount(final StorageAccount storageAccountValue) { + this.storageAccount = storageAccountValue; + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountListResponse.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountListResponse.java new file mode 100644 index 0000000000000..0bbdf7507ddd3 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountListResponse.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Storage Accounts operation response. +*/ +public class StorageAccountListResponse extends OperationResponse implements Iterable { + private ArrayList storageAccounts; + + /** + * Optional. + * @return The StorageAccounts value. + */ + public ArrayList getStorageAccounts() { + return this.storageAccounts; + } + + /** + * Optional. + * @param storageAccountsValue The StorageAccounts value. + */ + public void setStorageAccounts(final ArrayList storageAccountsValue) { + this.storageAccounts = storageAccountsValue; + } + + /** + * Initializes a new instance of the StorageAccountListResponse class. + * + */ + public StorageAccountListResponse() { + super(); + this.storageAccounts = new ArrayList(); + } + + /** + * Gets the sequence of StorageAccounts. + * + */ + public Iterator iterator() { + return this.getStorageAccounts().iterator(); + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountProperties.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountProperties.java new file mode 100644 index 0000000000000..ffd322d41ab94 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountProperties.java @@ -0,0 +1,296 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Calendar; + +/** +* Details about a storage account. +*/ +public class StorageAccountProperties { + private String affinityGroup; + + /** + * Optional. The affinity group with which this storage account is + * associated. + * @return The AffinityGroup value. + */ + public String getAffinityGroup() { + return this.affinityGroup; + } + + /** + * Optional. The affinity group with which this storage account is + * associated. + * @param affinityGroupValue The AffinityGroup value. + */ + public void setAffinityGroup(final String affinityGroupValue) { + this.affinityGroup = affinityGroupValue; + } + + private String description; + + /** + * Optional. The user supplied description of the storage account. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. The user supplied description of the storage account. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private ArrayList endpoints; + + /** + * Optional. The URLs that are used to perform a retrieval of a public blob, + * queue, or table object. + * @return The Endpoints value. + */ + public ArrayList getEndpoints() { + return this.endpoints; + } + + /** + * Optional. The URLs that are used to perform a retrieval of a public blob, + * queue, or table object. + * @param endpointsValue The Endpoints value. + */ + public void setEndpoints(final ArrayList endpointsValue) { + this.endpoints = endpointsValue; + } + + private String geoPrimaryRegion; + + /** + * Optional. Indicates the primary geographical region in which the storage + * account exists at this time. + * @return The GeoPrimaryRegion value. + */ + public String getGeoPrimaryRegion() { + return this.geoPrimaryRegion; + } + + /** + * Optional. Indicates the primary geographical region in which the storage + * account exists at this time. + * @param geoPrimaryRegionValue The GeoPrimaryRegion value. + */ + public void setGeoPrimaryRegion(final String geoPrimaryRegionValue) { + this.geoPrimaryRegion = geoPrimaryRegionValue; + } + + private boolean geoReplicationEnabled; + + /** + * Optional. Indicates whether the data in the storage account is replicated + * across more than one geographic location so as to enable resilience in + * the face of catastrophic service loss. The value is true if + * geo-replication is enabled; otherwise false. + * @return The GeoReplicationEnabled value. + */ + public boolean isGeoReplicationEnabled() { + return this.geoReplicationEnabled; + } + + /** + * Optional. Indicates whether the data in the storage account is replicated + * across more than one geographic location so as to enable resilience in + * the face of catastrophic service loss. The value is true if + * geo-replication is enabled; otherwise false. + * @param geoReplicationEnabledValue The GeoReplicationEnabled value. + */ + public void setGeoReplicationEnabled(final boolean geoReplicationEnabledValue) { + this.geoReplicationEnabled = geoReplicationEnabledValue; + } + + private String geoSecondaryRegion; + + /** + * Optional. Indicates the geographical region in which the storage account + * is being replicated. The GeoSecondaryRegion element is not returned if + * geo-replication is "off" for this account. + * @return The GeoSecondaryRegion value. + */ + public String getGeoSecondaryRegion() { + return this.geoSecondaryRegion; + } + + /** + * Optional. Indicates the geographical region in which the storage account + * is being replicated. The GeoSecondaryRegion element is not returned if + * geo-replication is "off" for this account. + * @param geoSecondaryRegionValue The GeoSecondaryRegion value. + */ + public void setGeoSecondaryRegion(final String geoSecondaryRegionValue) { + this.geoSecondaryRegion = geoSecondaryRegionValue; + } + + private String label; + + /** + * Optional. The user supplied name of the storage account returned as a + * base-64 encoded string. This name can be used identify the storage + * account for your tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The user supplied name of the storage account returned as a + * base-64 encoded string. This name can be used identify the storage + * account for your tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private Calendar lastGeoFailoverTime; + + /** + * Optional. A timestamp that indicates the most recent instance of a + * failover to the secondary region. In case of multiple failovers only the + * latest failover date and time maintained. The format of the returned + * timestamp is: + * [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitMinute]:[2DigitSecond]:[7DigitsOfPrecision]Z. + * LastGeoFailoverTime is not returned if there has not been an instance + * of a failover. + * @return The LastGeoFailoverTime value. + */ + public Calendar getLastGeoFailoverTime() { + return this.lastGeoFailoverTime; + } + + /** + * Optional. A timestamp that indicates the most recent instance of a + * failover to the secondary region. In case of multiple failovers only the + * latest failover date and time maintained. The format of the returned + * timestamp is: + * [4DigitYear]-[2DigitMonth]-[2DigitDay]T[2DigitMinute]:[2DigitSecond]:[7DigitsOfPrecision]Z. + * LastGeoFailoverTime is not returned if there has not been an instance + * of a failover. + * @param lastGeoFailoverTimeValue The LastGeoFailoverTime value. + */ + public void setLastGeoFailoverTime(final Calendar lastGeoFailoverTimeValue) { + this.lastGeoFailoverTime = lastGeoFailoverTimeValue; + } + + private String location; + + /** + * Optional. The geo-location specified when the storage account was + * created. This property is only returned if the storage account is not + * associated with an affinity group. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The geo-location specified when the storage account was + * created. This property is only returned if the storage account is not + * associated with an affinity group. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private StorageAccountStatus status; + + /** + * Optional. The status of the storage account at the time the operation was + * called. + * @return The Status value. + */ + public StorageAccountStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the storage account at the time the operation was + * called. + * @param statusValue The Status value. + */ + public void setStatus(final StorageAccountStatus statusValue) { + this.status = statusValue; + } + + private GeoRegionStatus statusOfGeoPrimaryRegion; + + /** + * Optional. Indicates whether the primary storage region is available. + * @return The StatusOfGeoPrimaryRegion value. + */ + public GeoRegionStatus getStatusOfGeoPrimaryRegion() { + return this.statusOfGeoPrimaryRegion; + } + + /** + * Optional. Indicates whether the primary storage region is available. + * @param statusOfGeoPrimaryRegionValue The StatusOfGeoPrimaryRegion value. + */ + public void setStatusOfGeoPrimaryRegion(final GeoRegionStatus statusOfGeoPrimaryRegionValue) { + this.statusOfGeoPrimaryRegion = statusOfGeoPrimaryRegionValue; + } + + private GeoRegionStatus statusOfGeoSecondaryRegion; + + /** + * Optional. Indicates whether the secondary storage region is available. + * @return The StatusOfGeoSecondaryRegion value. + */ + public GeoRegionStatus getStatusOfGeoSecondaryRegion() { + return this.statusOfGeoSecondaryRegion; + } + + /** + * Optional. Indicates whether the secondary storage region is available. + * @param statusOfGeoSecondaryRegionValue The StatusOfGeoSecondaryRegion + * value. + */ + public void setStatusOfGeoSecondaryRegion(final GeoRegionStatus statusOfGeoSecondaryRegionValue) { + this.statusOfGeoSecondaryRegion = statusOfGeoSecondaryRegionValue; + } + + /** + * Initializes a new instance of the StorageAccountProperties class. + * + */ + public StorageAccountProperties() { + this.endpoints = new ArrayList(); + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountRegenerateKeysParameters.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountRegenerateKeysParameters.java new file mode 100644 index 0000000000000..bd721ca5b546f --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountRegenerateKeysParameters.java @@ -0,0 +1,65 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +/** +* Parameters supplied to the Regenerate Keys operation. +*/ +public class StorageAccountRegenerateKeysParameters { + private StorageKeyType keyType; + + /** + * Required. Specifies which key to regenerate. + * @return The KeyType value. + */ + public StorageKeyType getKeyType() { + return this.keyType; + } + + /** + * Required. Specifies which key to regenerate. + * @param keyTypeValue The KeyType value. + */ + public void setKeyType(final StorageKeyType keyTypeValue) { + this.keyType = keyTypeValue; + } + + private String name; + + /** + * Required. The name of the desired storage account. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. The name of the desired storage account. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountRegenerateKeysResponse.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountRegenerateKeysResponse.java new file mode 100644 index 0000000000000..63a03a3d98b0f --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountRegenerateKeysResponse.java @@ -0,0 +1,88 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* The primary and secondary access keys for a storage account. +*/ +public class StorageAccountRegenerateKeysResponse extends OperationResponse { + private String primaryKey; + + /** + * Optional. The primary access key for the storage account. + * @return The PrimaryKey value. + */ + public String getPrimaryKey() { + return this.primaryKey; + } + + /** + * Optional. The primary access key for the storage account. + * @param primaryKeyValue The PrimaryKey value. + */ + public void setPrimaryKey(final String primaryKeyValue) { + this.primaryKey = primaryKeyValue; + } + + private String secondaryKey; + + /** + * Optional. The secondary access key for the storage account. + * @return The SecondaryKey value. + */ + public String getSecondaryKey() { + return this.secondaryKey; + } + + /** + * Optional. The secondary access key for the storage account. + * @param secondaryKeyValue The SecondaryKey value. + */ + public void setSecondaryKey(final String secondaryKeyValue) { + this.secondaryKey = secondaryKeyValue; + } + + private URI uri; + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountStatus.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountStatus.java new file mode 100644 index 0000000000000..e057af014168a --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountStatus.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +/** +* The status of the storage account at the time the operation was called. +*/ +public enum StorageAccountStatus { + /** + * The Storage Account had been created. + */ + Created, + + /** + * The Storage Account is being created. + */ + Creating, + + /** + * The DNS name for the storage account is being propagated. + */ + ResolvingDns, + + /** + * The Storage Account is being deleted. + */ + Deleting, +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountUpdateParameters.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountUpdateParameters.java new file mode 100644 index 0000000000000..7a42bafda3411 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageAccountUpdateParameters.java @@ -0,0 +1,161 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +import java.util.HashMap; + +/** +* Parameters supplied to the Update Storage Account operation. +*/ +public class StorageAccountUpdateParameters { + private String description; + + /** + * Optional. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private HashMap extendedProperties; + + /** + * Optional. Represents the name of an extended storage account property. + * Each extended property must have both a defined name and value. You can + * have a maximum of 50 extended property name/value pairs. The maximum + * length of the Name element is 64 characters, only alphanumeric + * characters and underscores are valid in the Name, and the name must + * start with a letter. Attempting to use other characters, starting the + * Name with a non-letter character, or entering a name that is identical + * to that of another extended property owned by the same storage account, + * will result in a status code 400 (Bad Request) error. Each extended + * property value has a maximum length of 255 characters. You can delete + * an extended property by setting the value to NULL. + * @return The ExtendedProperties value. + */ + public HashMap getExtendedProperties() { + return this.extendedProperties; + } + + /** + * Optional. Represents the name of an extended storage account property. + * Each extended property must have both a defined name and value. You can + * have a maximum of 50 extended property name/value pairs. The maximum + * length of the Name element is 64 characters, only alphanumeric + * characters and underscores are valid in the Name, and the name must + * start with a letter. Attempting to use other characters, starting the + * Name with a non-letter character, or entering a name that is identical + * to that of another extended property owned by the same storage account, + * will result in a status code 400 (Bad Request) error. Each extended + * property value has a maximum length of 255 characters. You can delete + * an extended property by setting the value to NULL. + * @param extendedPropertiesValue The ExtendedProperties value. + */ + public void setExtendedProperties(final HashMap extendedPropertiesValue) { + this.extendedProperties = extendedPropertiesValue; + } + + private Boolean geoReplicationEnabled; + + /** + * Optional. Enables or disables geo-replication on the specified the + * storage. If set to true, the data in the storage account is replicated + * across more than one geographic location so as to enable resilience in + * the face of catastrophic service loss. If set to false, geo-replication + * is disabled. If the element is not included in the request body, the + * current value is left unchanged. Important: If you have enabled + * geo-replication you can elect to disable it by setting this element to + * false. When disabled, your data is no longer replicated to a secondary + * data center and any data in the secondary location will be removed. + * Enabling geo-replication once it has been disabled will result in the + * storage account being billed for replicating the current copy of data to + * the secondary data center. After the existing copy of the data is + * replicated to the secondary data center, updates are geo-replicated at + * no additional charge. + * @return The GeoReplicationEnabled value. + */ + public Boolean isGeoReplicationEnabled() { + return this.geoReplicationEnabled; + } + + /** + * Optional. Enables or disables geo-replication on the specified the + * storage. If set to true, the data in the storage account is replicated + * across more than one geographic location so as to enable resilience in + * the face of catastrophic service loss. If set to false, geo-replication + * is disabled. If the element is not included in the request body, the + * current value is left unchanged. Important: If you have enabled + * geo-replication you can elect to disable it by setting this element to + * false. When disabled, your data is no longer replicated to a secondary + * data center and any data in the secondary location will be removed. + * Enabling geo-replication once it has been disabled will result in the + * storage account being billed for replicating the current copy of data to + * the secondary data center. After the existing copy of the data is + * replicated to the secondary data center, updates are geo-replicated at + * no additional charge. + * @param geoReplicationEnabledValue The GeoReplicationEnabled value. + */ + public void setGeoReplicationEnabled(final Boolean geoReplicationEnabledValue) { + this.geoReplicationEnabled = geoReplicationEnabledValue; + } + + private String label; + + /** + * Optional. A name for the storage account that is base64-encoded. The + * label may be up to 100 characters in length. The name can be used + * identify the storage account for your tracking purposes. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. A name for the storage account that is base64-encoded. The + * label may be up to 100 characters in length. The name can be used + * identify the storage account for your tracking purposes. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + /** + * Initializes a new instance of the StorageAccountUpdateParameters class. + * + */ + public StorageAccountUpdateParameters() { + this.extendedProperties = new HashMap(); + } +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageKeyType.java b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageKeyType.java new file mode 100644 index 0000000000000..2af237051b7a3 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/StorageKeyType.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.storage.models; + +/** +* Describes the type of a storage key. +*/ +public enum StorageKeyType { + Primary, + + Secondary, +} diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/package.html b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/package.html new file mode 100644 index 0000000000000..95f1452dd90a2 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/models/package.html @@ -0,0 +1,4 @@ + + +This package contains the models for the storage management service. + diff --git a/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/package.html b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/package.html new file mode 100644 index 0000000000000..5c14e0173a754 --- /dev/null +++ b/management-storage/src/main/java/com/microsoft/windowsazure/management/storage/package.html @@ -0,0 +1,6 @@ + + +This package contains the storage management class, + interface, and associated configuration and utility classes. + + diff --git a/management-storage/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/management-storage/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..00f5d8b27dd60 --- /dev/null +++ b/management-storage/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1 @@ +com.microsoft.windowsazure.management.storage.Exports diff --git a/management-storage/src/test/java/com/microsoft/windowsazure/management/storage/StorageAccountOperationsTests.java b/management-storage/src/test/java/com/microsoft/windowsazure/management/storage/StorageAccountOperationsTests.java new file mode 100644 index 0000000000000..15c8d61f67d21 --- /dev/null +++ b/management-storage/src/test/java/com/microsoft/windowsazure/management/storage/StorageAccountOperationsTests.java @@ -0,0 +1,200 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.storage; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.ArrayList; + +import javax.xml.parsers.ParserConfigurationException; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.storage.models.*; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.xml.sax.SAXException; + +public class StorageAccountOperationsTests extends StorageManagementIntegrationTestBase { + //lower case only for storage account name, this is existed storage account with vhd-store container, + //need to create your own storage account and create container there to store VM images + private static String storageAccountName; + + @BeforeClass + public static void setup() throws Exception { + storageAccountName = testStorageAccountPrefix + randomString(10); + createService(); + createStorageAccount(); + } + + @AfterClass + public static void cleanup() { + StorageAccountListResponse storageServiceListResponse = null; + try { + storageServiceListResponse = storageManagementClient.getStorageAccountsOperations().list(); + } catch (IOException e) { + } catch (ServiceException e) { + } catch (ParserConfigurationException e) { + } catch (SAXException e) { + } catch (URISyntaxException e) { + } + + if (storageServiceListResponse != null){ + ArrayList storageAccountlist = storageServiceListResponse.getStorageAccounts(); + for (StorageAccount storageAccount : storageAccountlist) { + if (storageAccount.getName().startsWith(testStorageAccountPrefix)) { + try { + storageManagementClient.getStorageAccountsOperations().delete(storageAccount.getName()); + } catch (IOException e) { + } catch (ServiceException e) { + } + } + } + } + } + + private static void createStorageAccount() throws Exception { + String storageAccountDescription = "Description1"; + + //Arrange + StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters(); + createParameters.setName(storageAccountName); + createParameters.setLabel(storageAccountDescription); + createParameters.setGeoReplicationEnabled(false); + createParameters.setLocation(GeoRegionNames.SOUTHCENTRALUS); + + //act + OperationResponse operationResponse = storageManagementClient.getStorageAccountsOperations().create(createParameters); + + //Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void createStorageAccountSuccess() throws Exception { + String storageAccountName = testStorageAccountPrefix + "csas"; + String storageAccountDescription = "create storage account success"; + + //Arrange + StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters(); + createParameters.setName(storageAccountName); + createParameters.setLabel(storageAccountDescription); + createParameters.setGeoReplicationEnabled(false); + createParameters.setLocation(GeoRegionNames.SOUTHCENTRALUS); + + //act + OperationResponse operationResponse = storageManagementClient.getStorageAccountsOperations().create(createParameters); + + //Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void getStorageAccountSuccess() throws Exception { + String storageAccountLocation = GeoRegionNames.SOUTHCENTRALUS; + + //Act + StorageAccountGetResponse storageAccountResponse = storageManagementClient.getStorageAccountsOperations().get(storageAccountName); + + //Assert + Assert.assertEquals(200, storageAccountResponse.getStatusCode()); + Assert.assertNotNull(storageAccountResponse.getRequestId()); + Assert.assertEquals(storageAccountName, storageAccountResponse.getStorageAccount().getName()); + Assert.assertNotNull(storageAccountResponse.getStorageAccount().getUri()); + Assert.assertEquals(storageAccountLocation, storageAccountResponse.getStorageAccount().getProperties().getLocation()); + Assert.assertNotNull(storageAccountResponse.getStorageAccount().getExtendedProperties()); + } + + @Test + public void checkAvailabilitySuccess() throws Exception { + String expectedStorageAccountName = testStorageAccountPrefix + "cas"; + //Act + CheckNameAvailabilityResponse checkNameAvailabilityResponse = storageManagementClient.getStorageAccountsOperations().checkNameAvailability(expectedStorageAccountName); + + //Assert + Assert.assertEquals(true, checkNameAvailabilityResponse.isAvailable()); + } + + @Test + public void getKeySuccess() throws Exception { + //Act + StorageAccountGetKeysResponse storageAccountGetKeysResponse = storageManagementClient.getStorageAccountsOperations().getKeys(storageAccountName); + + //Assert + Assert.assertEquals(200, storageAccountGetKeysResponse.getStatusCode()); + Assert.assertNotNull(storageAccountGetKeysResponse.getRequestId()); + Assert.assertNotNull(storageAccountGetKeysResponse.getPrimaryKey()); + Assert.assertNotNull(storageAccountGetKeysResponse.getSecondaryKey()); + } + + @Test + public void generateKeysSuccess() throws Exception { + StorageAccountRegenerateKeysParameters storageAccountRegenerateKeysParameters = new StorageAccountRegenerateKeysParameters(); + storageAccountRegenerateKeysParameters.setName(storageAccountName); + storageAccountRegenerateKeysParameters.setKeyType(StorageKeyType.Primary); + + //Act + StorageAccountGetKeysResponse storageAccountGetKeysResponse = storageManagementClient.getStorageAccountsOperations().getKeys(storageAccountName); + StorageAccountRegenerateKeysResponse storageAccountRegenerateKeysResponse = storageManagementClient.getStorageAccountsOperations().regenerateKeys(storageAccountRegenerateKeysParameters); + + //Assert + Assert.assertEquals(200, storageAccountGetKeysResponse.getStatusCode()); + Assert.assertNotNull(storageAccountGetKeysResponse.getRequestId()); + Assert.assertNotEquals(storageAccountGetKeysResponse.getPrimaryKey(), storageAccountRegenerateKeysResponse.getPrimaryKey()); + } + + @Test + public void listStorageAccountSuccess() throws Exception { + //Arrange + StorageAccountListResponse storageAccountListResponse = storageManagementClient.getStorageAccountsOperations().list(); + ArrayList storageAccountlist = storageAccountListResponse.getStorageAccounts(); + Assert.assertNotNull(storageAccountlist); + } + + @Test + public void updateStorageAccountSuccess() throws Exception { + //Arrange + String expectedStorageAccountName = testStorageAccountPrefix + "03"; + String expectedStorageAccountLabel = "testUpdateLabel3"; + + String expectedUpdatedStorageAccountLabel = "testStorageAccountUpdatedLabel3"; + String expectedUpdatedDescription = "updatedStorageAccountsuccess3"; + + StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters(); + createParameters.setName(expectedStorageAccountName); + createParameters.setLocation(GeoRegionNames.SOUTHCENTRALUS); + createParameters.setLabel(expectedStorageAccountLabel); + createParameters.setGeoReplicationEnabled(true); + + //Act + OperationResponse operationResponse = storageManagementClient.getStorageAccountsOperations().create(createParameters); + Assert.assertEquals(200, operationResponse.getStatusCode()); + + StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters(); + updateParameters.setLabel(expectedUpdatedStorageAccountLabel); + updateParameters.setGeoReplicationEnabled(false); + updateParameters.setDescription(expectedUpdatedDescription); + OperationResponse updateoperationResponse = storageManagementClient.getStorageAccountsOperations().update(expectedStorageAccountName, updateParameters); + + //Assert + Assert.assertEquals(200, updateoperationResponse.getStatusCode()); + Assert.assertNotNull(updateoperationResponse.getRequestId()); + } +} \ No newline at end of file diff --git a/management-storage/src/test/java/com/microsoft/windowsazure/management/storage/StorageManagementIntegrationTestBase.java b/management-storage/src/test/java/com/microsoft/windowsazure/management/storage/StorageManagementIntegrationTestBase.java new file mode 100644 index 0000000000000..2f36a9ec9223e --- /dev/null +++ b/management-storage/src/test/java/com/microsoft/windowsazure/management/storage/StorageManagementIntegrationTestBase.java @@ -0,0 +1,62 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.storage; + +import java.net.URI; +import java.util.Random; + +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; + +import com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigurationProperties; +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.Configuration; + +public abstract class StorageManagementIntegrationTestBase { + + protected static String testStorageAccountPrefix = "aztst"; + + protected static StorageManagementClient storageManagementClient; + + protected static void createService() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER, new DefaultHttpRequestRetryHandler()); + + storageManagementClient = StorageManagementService.create(config); + } + + protected static Configuration createConfiguration() throws Exception { + String baseUri = System.getenv(ManagementConfiguration.URI); + return ManagementConfiguration.configure( + baseUri != null ? new URI(baseUri) : null, + System.getenv(ManagementConfiguration.SUBSCRIPTION_ID), + System.getenv(ManagementConfiguration.KEYSTORE_PATH), + System.getenv(ManagementConfiguration.KEYSTORE_PASSWORD), + KeyStoreType.fromString(System.getenv(ManagementConfiguration.KEYSTORE_TYPE)) + ); + } + + protected static String randomString(int length) + { + Random random = new Random(); + StringBuilder stringBuilder = new StringBuilder(length); + for (int i=0; i + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-management-websites + jar + + Microsoft Azure Website Management Client API + Microsoft Azure Website Management SDK Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + 2.1.1 + 3.0.7.RELEASE + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + org.apache.httpcomponents + httpclient + + + javax.inject + javax.inject + + + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk16 + test + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+
+
diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/Exports.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/Exports.java new file mode 100644 index 0000000000000..e15395b3b680a --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/Exports.java @@ -0,0 +1,32 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.Builder; + +/** + * The Class Exports. + */ +public class Exports implements Builder.Exports { + /* (non-Javadoc) + * @see com.microsoft.windowsazure.services.core.Builder.Exports#register(com.microsoft.windowsazure.services.core.Builder.Registry) + */ + @Override + public void register(final Builder.Registry registry) { + // provide contract implementation + registry.add(WebSiteManagementClient.class, + WebSiteManagementClientImpl.class); + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/ServerFarmOperations.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/ServerFarmOperations.java new file mode 100644 index 0000000000000..6e0479f0e7269 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/ServerFarmOperations.java @@ -0,0 +1,284 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.ServerFarmCreateParameters; +import com.microsoft.windowsazure.management.websites.models.ServerFarmCreateResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmGetResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmListResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmUpdateParameters; +import com.microsoft.windowsazure.management.websites.models.ServerFarmUpdateResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* Operations for managing the server farm in a web space. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for more +* information) +*/ +public interface ServerFarmOperations { + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Server Farm + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Create Server Farm operation response. + */ + ServerFarmCreateResponse create(String webSpaceName, ServerFarmCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException; + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Server Farm + * operation. + * @return The Create Server Farm operation response. + */ + Future createAsync(String webSpaceName, ServerFarmCreateParameters parameters); + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String webSpaceName) throws IOException, ServiceException; + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String webSpaceName); + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param serverFarmName Required. The name of the server farm. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Server Farm operation response. + */ + ServerFarmGetResponse get(String webSpaceName, String serverFarmName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param serverFarmName Required. The name of the server farm. + * @return The Get Server Farm operation response. + */ + Future getAsync(String webSpaceName, String serverFarmName); + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Server Farm operation response. + */ + ServerFarmListResponse list(String webSpaceName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @return The List Server Farm operation response. + */ + Future listAsync(String webSpaceName); + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Update Server Farm + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Update Server Farm operation response. + */ + ServerFarmUpdateResponse update(String webSpaceName, ServerFarmUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException; + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Update Server Farm + * operation. + * @return The Update Server Farm operation response. + */ + Future updateAsync(String webSpaceName, ServerFarmUpdateParameters parameters); +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/ServerFarmOperationsImpl.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/ServerFarmOperationsImpl.java new file mode 100644 index 0000000000000..bc131e926fd59 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/ServerFarmOperationsImpl.java @@ -0,0 +1,1053 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.ServerFarmCreateParameters; +import com.microsoft.windowsazure.management.websites.models.ServerFarmCreateResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmGetResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmListResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmStatus; +import com.microsoft.windowsazure.management.websites.models.ServerFarmUpdateParameters; +import com.microsoft.windowsazure.management.websites.models.ServerFarmUpdateResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmWorkerSize; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Operations for managing the server farm in a web space. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for more +* information) +*/ +public class ServerFarmOperationsImpl implements ServiceOperations, ServerFarmOperations { + /** + * Initializes a new instance of the ServerFarmOperationsImpl class. + * + * @param client Reference to the service client. + */ + ServerFarmOperationsImpl(WebSiteManagementClientImpl client) { + this.client = client; + } + + private WebSiteManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.websites.WebSiteManagementClientImpl. + * @return The Client value. + */ + public WebSiteManagementClientImpl getClient() { + return this.client; + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Server Farm + * operation. + * @return The Create Server Farm operation response. + */ + @Override + public Future createAsync(final String webSpaceName, final ServerFarmCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServerFarmCreateResponse call() throws Exception { + return create(webSpaceName, parameters); + } + }); + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Server Farm + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Create Server Farm operation response. + */ + @Override + public ServerFarmCreateResponse create(String webSpaceName, ServerFarmCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServerFarm"); + requestDoc.appendChild(serverFarmElement); + + if (parameters.getCurrentNumberOfWorkers() != null) { + Element currentNumberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + currentNumberOfWorkersElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers()))); + serverFarmElement.appendChild(currentNumberOfWorkersElement); + } + + if (parameters.getCurrentWorkerSize() != null) { + Element currentWorkerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + currentWorkerSizeElement.appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString())); + serverFarmElement.appendChild(currentWorkerSizeElement); + } + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode("DefaultServerFarm")); + serverFarmElement.appendChild(nameElement); + + Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + numberOfWorkersElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers()))); + serverFarmElement.appendChild(numberOfWorkersElement); + + Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WorkerSize"); + workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString())); + serverFarmElement.appendChild(workerSizeElement); + + if (parameters.getStatus() != null) { + Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Status"); + statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString())); + serverFarmElement.appendChild(statusElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServerFarmCreateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServerFarmCreateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); + if (serverFarmElement2 != null) { + Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + if (currentNumberOfWorkersElement2 != null) { + int currentNumberOfWorkersInstance; + currentNumberOfWorkersInstance = DatatypeConverter.parseInt(currentNumberOfWorkersElement2.getTextContent()); + result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance); + } + + Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + if (currentWorkerSizeElement2 != null) { + ServerFarmWorkerSize currentWorkerSizeInstance; + currentWorkerSizeInstance = ServerFarmWorkerSize.valueOf(currentWorkerSizeElement2.getTextContent()); + result.setCurrentWorkerSize(currentWorkerSizeInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + result.setName(nameInstance); + } + + Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + if (numberOfWorkersElement2 != null) { + int numberOfWorkersInstance; + numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent()); + result.setNumberOfWorkers(numberOfWorkersInstance); + } + + Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); + if (workerSizeElement2 != null) { + ServerFarmWorkerSize workerSizeInstance; + workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent()); + result.setWorkerSize(workerSizeInstance); + } + + Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement2 != null) { + ServerFarmStatus statusInstance; + statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent()); + result.setStatus(statusInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String webSpaceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(webSpaceName); + } + }); + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String webSpaceName) throws IOException, ServiceException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms/DefaultServerFarm"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param serverFarmName Required. The name of the server farm. + * @return The Get Server Farm operation response. + */ + @Override + public Future getAsync(final String webSpaceName, final String serverFarmName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServerFarmGetResponse call() throws Exception { + return get(webSpaceName, serverFarmName); + } + }); + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param serverFarmName Required. The name of the server farm. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Server Farm operation response. + */ + @Override + public ServerFarmGetResponse get(String webSpaceName, String serverFarmName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (serverFarmName == null) { + throw new NullPointerException("serverFarmName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("serverFarmName", serverFarmName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms/" + serverFarmName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServerFarmGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServerFarmGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serverFarmElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); + if (serverFarmElement != null) { + Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmElement, "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + if (currentNumberOfWorkersElement != null) { + int currentNumberOfWorkersInstance; + currentNumberOfWorkersInstance = DatatypeConverter.parseInt(currentNumberOfWorkersElement.getTextContent()); + result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance); + } + + Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmElement, "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + if (currentWorkerSizeElement != null) { + ServerFarmWorkerSize currentWorkerSizeInstance; + currentWorkerSizeInstance = ServerFarmWorkerSize.valueOf(currentWorkerSizeElement.getTextContent()); + result.setCurrentWorkerSize(currentWorkerSizeInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(serverFarmElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element numberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmElement, "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + if (numberOfWorkersElement != null) { + int numberOfWorkersInstance; + numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement.getTextContent()); + result.setNumberOfWorkers(numberOfWorkersInstance); + } + + Element workerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmElement, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); + if (workerSizeElement != null) { + ServerFarmWorkerSize workerSizeInstance; + workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement.getTextContent()); + result.setWorkerSize(workerSizeInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(serverFarmElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + ServerFarmStatus statusInstance; + statusInstance = ServerFarmStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @return The List Server Farm operation response. + */ + @Override + public Future listAsync(final String webSpaceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServerFarmListResponse call() throws Exception { + return list(webSpaceName); + } + }); + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Server Farm operation response. + */ + @Override + public ServerFarmListResponse list(String webSpaceName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServerFarmListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServerFarmListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element serverFarmsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServerFarms"); + if (serverFarmsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serverFarmsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServerFarm").size(); i1 = i1 + 1) { + org.w3c.dom.Element serverFarmsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(serverFarmsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ServerFarm").get(i1)); + ServerFarmListResponse.ServerFarm serverFarmInstance = new ServerFarmListResponse.ServerFarm(); + result.getServerFarms().add(serverFarmInstance); + + Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmsElement, "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + if (currentNumberOfWorkersElement != null) { + int currentNumberOfWorkersInstance; + currentNumberOfWorkersInstance = DatatypeConverter.parseInt(currentNumberOfWorkersElement.getTextContent()); + serverFarmInstance.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance); + } + + Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmsElement, "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + if (currentWorkerSizeElement != null) { + ServerFarmWorkerSize currentWorkerSizeInstance; + currentWorkerSizeInstance = ServerFarmWorkerSize.valueOf(currentWorkerSizeElement.getTextContent()); + serverFarmInstance.setCurrentWorkerSize(currentWorkerSizeInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(serverFarmsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + serverFarmInstance.setName(nameInstance); + } + + Element numberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmsElement, "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + if (numberOfWorkersElement != null) { + int numberOfWorkersInstance; + numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement.getTextContent()); + serverFarmInstance.setNumberOfWorkers(numberOfWorkersInstance); + } + + Element workerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmsElement, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); + if (workerSizeElement != null) { + ServerFarmWorkerSize workerSizeInstance; + workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement.getTextContent()); + serverFarmInstance.setWorkerSize(workerSizeInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(serverFarmsElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + ServerFarmStatus statusInstance; + statusInstance = ServerFarmStatus.valueOf(statusElement.getTextContent()); + serverFarmInstance.setStatus(statusInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Update Server Farm + * operation. + * @return The Update Server Farm operation response. + */ + @Override + public Future updateAsync(final String webSpaceName, final ServerFarmUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ServerFarmUpdateResponse call() throws Exception { + return update(webSpaceName, parameters); + } + }); + } + + /** + * You can create a server farm by issuing an HTTP POST request. Only one + * server farm per webspace is permitted. You can retrieve server farm + * details by using HTTP GET, change server farm properties by using HTTP + * PUT, and delete a server farm by using HTTP DELETE. A request body is + * required for server farm creation (HTTP POST) and server farm update + * (HTTP PUT). Warning: Creating a server farm changes your webspace's + * Compute Mode from Shared to Dedicated. You will be charged from the + * moment the server farm is created, even if all your sites are still + * running in Free mode. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Update Server Farm + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Update Server Farm operation response. + */ + @Override + public ServerFarmUpdateResponse update(String webSpaceName, ServerFarmUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms/DefaultServerFarm"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServerFarm"); + requestDoc.appendChild(serverFarmElement); + + if (parameters.getCurrentNumberOfWorkers() != null) { + Element currentNumberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + currentNumberOfWorkersElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers()))); + serverFarmElement.appendChild(currentNumberOfWorkersElement); + } + + if (parameters.getCurrentWorkerSize() != null) { + Element currentWorkerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + currentWorkerSizeElement.appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString())); + serverFarmElement.appendChild(currentWorkerSizeElement); + } + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode("DefaultServerFarm")); + serverFarmElement.appendChild(nameElement); + + Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + numberOfWorkersElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers()))); + serverFarmElement.appendChild(numberOfWorkersElement); + + Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WorkerSize"); + workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString())); + serverFarmElement.appendChild(workerSizeElement); + + if (parameters.getStatus() != null) { + Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Status"); + statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString())); + serverFarmElement.appendChild(statusElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ServerFarmUpdateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ServerFarmUpdateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); + if (serverFarmElement2 != null) { + Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + if (currentNumberOfWorkersElement2 != null) { + int currentNumberOfWorkersInstance; + currentNumberOfWorkersInstance = DatatypeConverter.parseInt(currentNumberOfWorkersElement2.getTextContent()); + result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance); + } + + Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + if (currentWorkerSizeElement2 != null) { + ServerFarmWorkerSize currentWorkerSizeInstance; + currentWorkerSizeInstance = ServerFarmWorkerSize.valueOf(currentWorkerSizeElement2.getTextContent()); + result.setCurrentWorkerSize(currentWorkerSizeInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + result.setName(nameInstance); + } + + Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + if (numberOfWorkersElement2 != null) { + int numberOfWorkersInstance; + numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent()); + result.setNumberOfWorkers(numberOfWorkersInstance); + } + + Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); + if (workerSizeElement2 != null) { + ServerFarmWorkerSize workerSizeInstance; + workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent()); + result.setWorkerSize(workerSizeInstance); + } + + Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement2 != null) { + ServerFarmStatus statusInstance; + statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent()); + result.setStatus(statusInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteExtendedErrorCodes.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteExtendedErrorCodes.java new file mode 100644 index 0000000000000..27e77a0836e46 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteExtendedErrorCodes.java @@ -0,0 +1,419 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +/** +* In addition to standard HTTP status codes, the Azure Web Sites Management +* REST API returns extended error codes and error messages. The extended codes +* do not replace the standard HTTP status codes, but provide additional, +* actionable information that can be used in conjunction with the standard +* HTTP status codes. For example, an HTTP 404 error can occur for numerous +* reasons, so having the additional information in the extended message can +* assist with problem resolution. (For more information on the standard HTTP +* codes returned by the REST API, see Service Management Status and Error +* Codes.) (see +* http://msdn.microsoft.com/en-us/library/windowsazure/dn166968.aspx for more +* information) +*/ +public abstract class WebSiteExtendedErrorCodes { + /** + * Access is denied. + */ + public static final String ACCESSDENIED = "01001"; + + /** + * Command resource object is not present in the request body. + */ + public static final String COMMANDRESOURCENOTPRESENT = "01002"; + + /** + * Invalid name {0}. + */ + public static final String INVALIDNAME = "01003"; + + /** + * Cannot understand command verb {0}. + */ + public static final String UNKNOWNCOMMANDVERB = "01004"; + + /** + * The service is currently in read only mode. + */ + public static final String ISINREADONLYMODE = "01005"; + + /** + * The {0} parameter is not specified. + */ + public static final String PARAMETERISNOTSPECIFIED = "01006"; + + /** + * Parameter {0} has invalid value. + */ + public static final String INVALIDPARAMETERVALUE = "01007"; + + /** + * {0} object is not present in the request body. + */ + public static final String INVALIDREQUEST = "01008"; + + /** + * The from value in the query string is bigger than or equal to the to + * value. + */ + public static final String INCORRECTDATETIMERANGE = "01009"; + + /** + * Required parameter {0} is missing. + */ + public static final String REQUIREDPARAMETERMISSING = "01010"; + + /** + * Name of the web quota cannot change. + */ + public static final String RESOURCENAMECANNOTCHANGE = "01011"; + + /** + * The value of the query string parameter cannot be converted to Boolean. + */ + public static final String FAILEDTOCONVERTPARAMETERVALUE = "01012"; + + /** + * Parameter with name {0} already exists in the request. + */ + public static final String PARAMETERNAMEALREADYEXISTS = "01013"; + + /** + * Parameter name cannot be empty. + */ + public static final String PARAMETERNAMEISEMPTY = "01014"; + + /** + * Not ready. + */ + public static final String NOTREADY = "01015"; + + /** + * Ready. + */ + public static final String READY = "01016"; + + /** + * Update is not allowed for the {0} field. + */ + public static final String UPDATEFORFIELDNOTALLOWED = "01017"; + + /** + * Web Service does not support Command {0}. Only supported command(s) is + * {1}. + */ + public static final String NOTSUPPORTEDCOMMAND = "01018"; + + /** + * Invalid data ({0}). + */ + public static final String INVALIDDATA = "01019"; + + /** + * There was a conflict. {0} + */ + public static final String GENERICCONFLICT = "01020"; + + /** + * Internal server error occurred. {0} + */ + public static final String INTERNALSERVERERROR = "01021"; + + /** + * Number of sites exceeds the maximum allowed. + */ + public static final String NUMBEROFSITESLIMIT = "03001"; + + /** + * Number of workers exceeds the maximum allowed. + */ + public static final String NUMBEROFWORKERSLIMIT = "03002"; + + /** + * There is not enough space on the disk. + */ + public static final String NOSTORAGEVOLUMEAVAILABLE = "03003"; + + /** + * WebSpace with name {0} already exists for subscription {1}. + */ + public static final String WEBSPACEALREADYEXISTS = "03004"; + + /** + * Cannot find webspace {0} for subscription {1}. + */ + public static final String WEBSPACENOTFOUND = "03005"; + + /** + * Web space contains resources. + */ + public static final String WEBSPACECONTAINSRESOURCES = "03006"; + + /** + * The file storage capacity exceeds the limit. + */ + public static final String FILESTORAGELIMIT = "03007"; + + /** + * Failed to delete web space {0}: {1} + */ + public static final String WEBSPACEDELETEERROR = "03008"; + + /** + * Not enough available Standard Instance servers to satisfy this request. + */ + public static final String NOWORKERSAVAILABLE = "03009"; + + /** + * Failed to create web space {0} on storage volume {1}: {2}. + */ + public static final String WEBSPACECREATEERROR = "03010"; + + /** + * Directory already exists for site {0}. + */ + public static final String DIRECTORYALREADYEXISTS = "04001"; + + /** + * Failed to delete directory {0}. + */ + public static final String DIRECTORYDELETEERROR = "04002"; + + /** + * Invalid host name {0}. + */ + public static final String INVALIDHOSTNAME = "04003"; + + /** + * NumberOfWorkers value must be more than zero. + */ + public static final String INVALIDNUMBEROFWORKERS = "04004"; + + /** + * Hostname '{0}' already exists. + */ + public static final String HOSTNAMEALREADYEXISTS = "04005"; + + /** + * No CNAME (or too many CNAMEs) pointing from {0} to a site in a default + * DNS zone. + */ + public static final String INVALIDCUSTOMHOSTNAMEVALIDATION = "04006"; + + /** + * There are no hostnames which could be used for validation. + */ + public static final String INVALIDCUSTOMHOSTNAMEVALIDATIONNOBASEHOSTNAME = "04007"; + + /** + * Site with name {0} already exists. + */ + public static final String SITEALREADYEXISTS = "04008"; + + /** + * Cannot find site {0}. + */ + public static final String SITENOTFOUND = "04009"; + + /** + * The external URL "{0}" specified on request header "{1}" is invalid. + */ + public static final String INVALIDEXTERNALURIHEADER = "04010"; + + /** + * Failed to delete file {0}. + */ + public static final String FILEDELETEERROR = "04011"; + + /** + * Number of workers for this site exceeds the maximum allowed. + */ + public static final String NUMBEROFWORKERSPERSITELIMIT = "04012"; + + /** + * WebSiteManager.CreateWebSite: Creating Site using storageVolume {0}. + */ + public static final String TRACEWEBSITESTORAGEVOLUME = "04013"; + + /** + * Cannot delete repository with name {0}. + */ + public static final String REPOSITORYDELETEERROR = "05001"; + + /** + * Development site already exists in the repository for site {0}. + */ + public static final String REPOSITORYDEVSITEALREADYEXISTS = "05002"; + + /** + * Development site does not exist in the repository for site {0}. + */ + public static final String REPOSITORYDEVSITENOTEXIST = "05003"; + + /** + * Site {0} already has repository created for it. + */ + public static final String REPOSITORYSITEALREADYEXISTS = "05004"; + + /** + * Repository does not exist for site {0}. + */ + public static final String REPOSITORYSITENOTEXIST = "05005"; + + /** + * Failed to create a development site. + */ + public static final String TRACEFAILEDTOCREATEDEVSITE = "05006"; + + /** + * User {0} has been rejected. + */ + public static final String AUTHENTICATEDFAILED = "06001"; + + /** + * User {0} has been successfully authenticated. + */ + public static final String AUTHENTICATEDPASSED = "06002"; + + /** + * User {0} has been rejected. + */ + public static final String AUTHORIZATIONFAILED = "06003"; + + /** + * User {0} has been authorized. + */ + public static final String AUTHORIZATIONPASSED = "06004"; + + /** + * Publishing credentials have to be trimmed from white characters. + */ + public static final String PUBLISHINGCREDENTIALSNOTTRIMMED = "06005"; + + /** + * Publishing password cannot be empty. + */ + public static final String PUBLISHINGPASSWORDISEMPTY = "06006"; + + /** + * Publishing password must be specified. + */ + public static final String PUBLISHINGPASSWORDNOTSPECIFIED = "06007"; + + /** + * Publishing username {0} is already used. Specify a different publishing + * username. + */ + public static final String PUBLISHINGUSERNAMEALREADYEXISTS = "06008"; + + /** + * Publishing user name cannot be empty. + */ + public static final String PUBLISHINGUSERNAMEISEMPTY = "06009"; + + /** + * An error occurred when adding the {0} entry: {1}. + */ + public static final String ERRORADDING = "51001"; + + /** + * An error occurred when deleting the {0} entry: {1}. + */ + public static final String ERRORDELETING = "51002"; + + /** + * An error occurred when updating the {0} entry: {1}. + */ + public static final String ERRORUPDATING = "51003"; + + /** + * Cannot find {0} with name {1}. + */ + public static final String CANNOTFINDENTITY = "51004"; + + /** + * Subscription with specified name already exists. + */ + public static final String SUBSCRIPTIONCONFLICT = "52001"; + + /** + * Subscription Name cannot be null or empty. + */ + public static final String SUBSCRIPTIONNONEMPTY = "52002"; + + /** + * Subscription {0} not found. + */ + public static final String SUBSCRIPTIONNOTFOUND = "52003"; + + /** + * Subscription {0} is suspended. + */ + public static final String SUBSCRIPTIONSUSPENDED = "52004"; + + /** + * Subscription contains WebSpaces. + */ + public static final String NONEMPTYSUBSCRIPTION = "52005"; + + /** + * WebSpace with specified name already exists. + */ + public static final String WEBSPACECONFLICT = "53001"; + + /** + * WebSpace Name cannot be null or empty. + */ + public static final String WEBSPACENONEMPTY = "53002"; + + /** + * WebSpace contains web sites. + */ + public static final String NONEMPTYWEBSPACE = "53003"; + + /** + * An error occurred when picking Stamp for WebSpace {0}. + */ + public static final String ERRORPICKINGSTAMP = "53004"; + + /** + * Web site with given name {0} already exists in the specified Subscription + * and Webspace. + */ + public static final String WEBSITECONFLICT = "54001"; + + /** + * WebSiteName cannot be null or empty. + */ + public static final String WEBSITENONEMPTY = "54002"; + + /** + * Specified Host Name {0} is already taken by another site. + */ + public static final String HOSTNAMECONFLICT = "54003"; +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementClient.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementClient.java new file mode 100644 index 0000000000000..043526712b903 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementClient.java @@ -0,0 +1,181 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.FilterableService; +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.WebSiteOperationStatusResponse; +import java.io.Closeable; +import java.io.IOException; +import java.net.URI; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Web Sites Management API provides a RESTful set of web services that +* interact with the Windows Azure Web Sites service to manage your web sites. +* The API has entities that capture the relationship between an end user and +* Windows Azure Web Sites service. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for more +* information) +*/ +public interface WebSiteManagementClient extends Closeable, FilterableService { + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + URI getBaseUri(); + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + SubscriptionCloudCredentials getCredentials(); + + /** + * Operations for managing the server farm in a web space. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * @return The ServerFarmsOperations value. + */ + ServerFarmOperations getServerFarmsOperations(); + + /** + * Operations for managing the web sites in a web space. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for + * more information) + * @return The WebSitesOperations value. + */ + WebSiteOperations getWebSitesOperations(); + + /** + * Operations for managing web spaces beneath your subscription. + * @return The WebSpacesOperations value. + */ + WebSpaceOperations getWebSpacesOperations(); + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling a long-running operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, timed out, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param webSpaceName Required. The name of the webspace for the website + * where the operation was targeted. + * @param siteName Required. The name of the site where the operation was + * targeted. + * @param operationId Required. The operation ID for the operation you wish + * to track. The operation ID is returned in the ID field in the body of + * the response for long-running operations. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + WebSiteOperationStatusResponse getOperationStatus(String webSpaceName, String siteName, String operationId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling a long-running operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, timed out, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param webSpaceName Required. The name of the webspace for the website + * where the operation was targeted. + * @param siteName Required. The name of the site where the operation was + * targeted. + * @param operationId Required. The operation ID for the operation you wish + * to track. The operation ID is returned in the ID field in the body of + * the response for long-running operations. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + Future getOperationStatusAsync(String webSpaceName, String siteName, String operationId); + + /** + * Register your subscription to use Azure Web Sites. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse registerSubscription() throws IOException, ServiceException; + + /** + * Register your subscription to use Azure Web Sites. + * + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future registerSubscriptionAsync(); + + /** + * Unregister your subscription to use Azure Web Sites. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse unregisterSubscription() throws IOException, ServiceException; + + /** + * Unregister your subscription to use Azure Web Sites. + * + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future unregisterSubscriptionAsync(); +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementClientImpl.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementClientImpl.java new file mode 100644 index 0000000000000..32ba939e91e75 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementClientImpl.java @@ -0,0 +1,727 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceClient; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.management.websites.models.WebSiteOperationStatus; +import com.microsoft.windowsazure.management.websites.models.WebSiteOperationStatusResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import javax.inject.Inject; +import javax.inject.Named; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.impl.client.HttpClientBuilder; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Web Sites Management API provides a RESTful set of web services that +* interact with the Windows Azure Web Sites service to manage your web sites. +* The API has entities that capture the relationship between an end user and +* Windows Azure Web Sites service. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for more +* information) +*/ +public class WebSiteManagementClientImpl extends ServiceClient implements WebSiteManagementClient { + private URI baseUri; + + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + public URI getBaseUri() { + return this.baseUri; + } + + private SubscriptionCloudCredentials credentials; + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + public SubscriptionCloudCredentials getCredentials() { + return this.credentials; + } + + private ServerFarmOperations serverFarms; + + /** + * Operations for managing the server farm in a web space. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for + * more information) + * @return The ServerFarmsOperations value. + */ + public ServerFarmOperations getServerFarmsOperations() { + return this.serverFarms; + } + + private WebSiteOperations webSites; + + /** + * Operations for managing the web sites in a web space. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for + * more information) + * @return The WebSitesOperations value. + */ + public WebSiteOperations getWebSitesOperations() { + return this.webSites; + } + + private WebSpaceOperations webSpaces; + + /** + * Operations for managing web spaces beneath your subscription. + * @return The WebSpacesOperations value. + */ + public WebSpaceOperations getWebSpacesOperations() { + return this.webSpaces; + } + + /** + * Initializes a new instance of the WebSiteManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + private WebSiteManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) { + super(httpBuilder, executorService); + this.serverFarms = new ServerFarmOperationsImpl(this); + this.webSites = new WebSiteOperationsImpl(this); + this.webSpaces = new WebSpaceOperationsImpl(this); + } + + /** + * Initializes a new instance of the WebSiteManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @param baseUri Required. The URI used as the base for all Service + * Management requests. + */ + @Inject + public WebSiteManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } else { + this.credentials = credentials; + } + if (baseUri == null) { + try { + this.baseUri = new URI("https://management.core.windows.net"); + } + catch (URISyntaxException ex) { + } + } else { + this.baseUri = baseUri; + } + } + + /** + * Initializes a new instance of the WebSiteManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + */ + public WebSiteManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } + this.credentials = credentials; + this.baseUri = new URI("https://management.core.windows.net"); + } + + /** + * Initializes a new instance of the WebSiteManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + protected WebSiteManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) { + return new WebSiteManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri()); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling a long-running operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, timed out, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param webSpaceName Required. The name of the webspace for the website + * where the operation was targeted. + * @param siteName Required. The name of the site where the operation was + * targeted. + * @param operationId Required. The operation ID for the operation you wish + * to track. The operation ID is returned in the ID field in the body of + * the response for long-running operations. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + @Override + public Future getOperationStatusAsync(final String webSpaceName, final String siteName, final String operationId) { + return this.getExecutorService().submit(new Callable() { + @Override + public WebSiteOperationStatusResponse call() throws Exception { + return getOperationStatus(webSpaceName, siteName, operationId); + } + }); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling a long-running operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, timed out, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param webSpaceName Required. The name of the webspace for the website + * where the operation was targeted. + * @param siteName Required. The name of the site where the operation was + * targeted. + * @param operationId Required. The operation ID for the operation you wish + * to track. The operation ID is returned in the ID field in the body of + * the response for long-running operations. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + @Override + public WebSiteOperationStatusResponse getOperationStatus(String webSpaceName, String siteName, String operationId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (siteName == null) { + throw new NullPointerException("siteName"); + } + if (operationId == null) { + throw new NullPointerException("operationId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("siteName", siteName); + tracingParameters.put("operationId", operationId); + CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getBaseUri().toString(); + String url = "/" + this.getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + siteName.trim() + "/operations/" + operationId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteOperationStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteOperationStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + Element createdTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); + if (createdTimeElement != null) { + Calendar createdTimeInstance; + createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); + result.setCreatedTime(createdTimeInstance); + } + + Element errorsSequenceElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Errors"); + if (errorsSequenceElement != null) { + boolean isNil = false; + Attr nilAttribute = errorsSequenceElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(errorsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Error").size(); i1 = i1 + 1) { + org.w3c.dom.Element errorsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(errorsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Error").get(i1)); + WebSiteOperationStatusResponse.Error errorInstance = new WebSiteOperationStatusResponse.Error(); + result.getErrors().add(errorInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + boolean isNil2 = false; + Attr nilAttribute2 = codeElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + errorInstance.setCode(codeInstance); + } + } + + Element messageElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + boolean isNil3 = false; + Attr nilAttribute3 = messageElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute3 != null) { + isNil3 = "true".equals(nilAttribute3.getValue()); + } + if (isNil3 == false) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + errorInstance.setMessage(messageInstance); + } + } + + Element extendedCodeElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "ExtendedCode"); + if (extendedCodeElement != null) { + boolean isNil4 = false; + Attr nilAttribute4 = extendedCodeElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute4 != null) { + isNil4 = "true".equals(nilAttribute4.getValue()); + } + if (isNil4 == false) { + String extendedCodeInstance; + extendedCodeInstance = extendedCodeElement.getTextContent(); + errorInstance.setExtendedCode(extendedCodeInstance); + } + } + + Element messageTemplateElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "MessageTemplate"); + if (messageTemplateElement != null) { + boolean isNil5 = false; + Attr nilAttribute5 = messageTemplateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute5 != null) { + isNil5 = "true".equals(nilAttribute5.getValue()); + } + if (isNil5 == false) { + String messageTemplateInstance; + messageTemplateInstance = messageTemplateElement.getTextContent(); + errorInstance.setMessageTemplate(messageTemplateInstance); + } + } + + Element parametersSequenceElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Parameters"); + if (parametersSequenceElement != null) { + boolean isNil6 = false; + Attr nilAttribute6 = parametersSequenceElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute6 != null) { + isNil6 = "true".equals(nilAttribute6.getValue()); + } + if (isNil6 == false) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(parametersSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i2 = i2 + 1) { + org.w3c.dom.Element parametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(parametersSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i2)); + errorInstance.getParameters().add(parametersElement.getTextContent()); + } + } + } + + Element innerErrorsElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "InnerErrors"); + if (innerErrorsElement != null) { + boolean isNil7 = false; + Attr nilAttribute7 = innerErrorsElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute7 != null) { + isNil7 = "true".equals(nilAttribute7.getValue()); + } + if (isNil7 == false) { + String innerErrorsInstance; + innerErrorsInstance = innerErrorsElement.getTextContent(); + errorInstance.setInnerErrors(innerErrorsInstance); + } + } + } + } + } + + Element expirationTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ExpirationTime"); + if (expirationTimeElement != null) { + Calendar expirationTimeInstance; + expirationTimeInstance = DatatypeConverter.parseDateTime(expirationTimeElement.getTextContent()); + result.setExpirationTime(expirationTimeInstance); + } + + Element geoMasterOperationIdElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "GeoMasterOperationId"); + if (geoMasterOperationIdElement != null) { + boolean isNil8 = false; + Attr nilAttribute8 = geoMasterOperationIdElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute8 != null) { + isNil8 = "true".equals(nilAttribute8.getValue()); + } + if (isNil8 == false) { + String geoMasterOperationIdInstance; + geoMasterOperationIdInstance = geoMasterOperationIdElement.getTextContent(); + result.setGeoMasterOperationId(geoMasterOperationIdInstance); + } + } + + Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + boolean isNil9 = false; + Attr nilAttribute9 = idElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute9 != null) { + isNil9 = "true".equals(nilAttribute9.getValue()); + } + if (isNil9 == false) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + Element modifiedTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ModifiedTime"); + if (modifiedTimeElement != null) { + Calendar modifiedTimeInstance; + modifiedTimeInstance = DatatypeConverter.parseDateTime(modifiedTimeElement.getTextContent()); + result.setModifiedTime(modifiedTimeInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + boolean isNil10 = false; + Attr nilAttribute10 = nameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute10 != null) { + isNil10 = "true".equals(nilAttribute10.getValue()); + } + if (isNil10 == false) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + } + + Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + WebSiteOperationStatus statusInstance; + statusInstance = WebSiteOperationStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Register your subscription to use Azure Web Sites. + * + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future registerSubscriptionAsync() { + return this.getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return registerSubscription(); + } + }); + } + + /** + * Register your subscription to use Azure Web Sites. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse registerSubscription() throws IOException, ServiceException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "registerSubscriptionAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getBaseUri().toString(); + String url = "/" + this.getCredentials().getSubscriptionId().trim() + "/services" + "?"; + url = url + "service=website"; + url = url + "&" + "action=register"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Unregister your subscription to use Azure Web Sites. + * + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future unregisterSubscriptionAsync() { + return this.getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return unregisterSubscription(); + } + }); + } + + /** + * Unregister your subscription to use Azure Web Sites. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse unregisterSubscription() throws IOException, ServiceException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "unregisterSubscriptionAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getBaseUri().toString(); + String url = "/" + this.getCredentials().getSubscriptionId().trim() + "/services" + "?"; + url = url + "service=website"; + url = url + "&" + "action=unregister"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementService.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementService.java new file mode 100644 index 0000000000000..d2761c6d8985e --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteManagementService.java @@ -0,0 +1,78 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.Configuration; + +/** + * + * Access service management functionality. + * + */ +public final class WebSiteManagementService { + /** + * The default constructor. + */ + private WebSiteManagementService() { + // class is not instantiated + } + + /** + * Creates an instance of the WebSiteManagementClient API. + * @return The WebSiteManagementClient. + */ + public static WebSiteManagementClient create() { + return Configuration.getInstance() + .create(WebSiteManagementClient.class); + } + + /** + * Creates an instance of the WebSiteManagementClient API + * using the specified configuration. + * + * @param config A Configuration object that represents the + * configuration for the service management. + * @return The WebSiteManagementClient. + */ + public static WebSiteManagementClient create(final Configuration config) { + return config.create(WebSiteManagementClient.class); + } + + /** + * Creates an instance of the WebSiteManagementClient API. + * + * @param profile A String object that representing the profile + * of the service management service. + * @return The WebSiteManagementClient. + */ + public static WebSiteManagementClient create(final String profile) { + return Configuration.getInstance().create(profile, + WebSiteManagementClient.class); + } + + /** + * Creates an instance of the WebSiteManagementClient API + * using the specified configuration. + * + * @param profile The profile. + * @param config A Configuration object that represents the + * configuration for the service management. + * @return The WebSiteManagementClient. + */ + public static WebSiteManagementClient create(final String profile, + final Configuration config) { + return config.create(profile, WebSiteManagementClient.class); + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteOperations.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteOperations.java new file mode 100644 index 0000000000000..b6c34df31f2e4 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteOperations.java @@ -0,0 +1,751 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.WebSiteCreateParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteCreateResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteDeleteParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteDeleteRepositoryResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetConfigurationResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetHistoricalUsageMetricsParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetHistoricalUsageMetricsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetPublishProfileResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetRepositoryResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetUsageMetricsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteInstanceIdsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteIsHostnameAvailableResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteOperationStatusResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteUpdateConfigurationParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteUpdateParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteUpdateResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* Operations for managing the web sites in a web space. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for more +* information) +*/ +public interface WebSiteOperations { + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + WebSiteOperationStatusResponse beginSwapingSlots(String webSpaceName, String webSiteName, String sourceSlotName, String targetSlotName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + Future beginSwapingSlotsAsync(String webSpaceName, String webSiteName, String sourceSlotName, String targetSlotName); + + /** + * You can create a web site by using a POST request that includes the name + * of the web site and other information in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166986.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Web Site + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Create Web Site operation response. + */ + WebSiteCreateResponse create(String webSpaceName, WebSiteCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException; + + /** + * You can create a web site by using a POST request that includes the name + * of the web site and other information in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166986.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Web Site + * operation. + * @return The Create Web Site operation response. + */ + Future createAsync(String webSpaceName, WebSiteCreateParameters parameters); + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository create operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse createRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException; + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository create operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future createRepositoryAsync(String webSpaceName, String webSiteName); + + /** + * You can delete a web site by issuing an HTTP DELETE request. If the web + * site being deleted is the only site remaining in a server farm, you can + * optionally delete the server farm as well by using the + * deleteEmptyServerFarm parameter. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236430.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Delete Web Site + * operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String webSpaceName, String webSiteName, WebSiteDeleteParameters parameters) throws IOException, ServiceException; + + /** + * You can delete a web site by issuing an HTTP DELETE request. If the web + * site being deleted is the only site remaining in a server farm, you can + * optionally delete the server farm as well by using the + * deleteEmptyServerFarm parameter. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236430.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Delete Web Site + * operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String webSpaceName, String webSiteName, WebSiteDeleteParameters parameters); + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository delete operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Delete Repository Web Site operation response. + */ + WebSiteDeleteRepositoryResponse deleteRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository delete operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Delete Repository Web Site operation response. + */ + Future deleteRepositoryAsync(String webSpaceName, String webSiteName); + + /** + * You can generate a new random password for publishing a site by issuing + * an HTTP POST request. Tip: If you want to verify that the publish + * password has changed, issue an HTTP GET on /publishxml before calling + * /newpassword. In the publish XML, note the hash value in the userPWD + * attribute. After calling /newpassword, call /publishxml again. You can + * then compare the new value of userPWD in the Publish XML with the one + * you noted earlier. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236428.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse generatePassword(String webSpaceName, String webSiteName) throws IOException, ServiceException; + + /** + * You can generate a new random password for publishing a site by issuing + * an HTTP POST request. Tip: If you want to verify that the publish + * password has changed, issue an HTTP GET on /publishxml before calling + * /newpassword. In the publish XML, note the hash value in the userPWD + * attribute. After calling /newpassword, call /publishxml again. You can + * then compare the new value of userPWD in the Publish XML with the one + * you noted earlier. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236428.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future generatePasswordAsync(String webSpaceName, String webSiteName); + + /** + * You can retrieve details for a web site by issuing an HTTP GET request. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn167007.aspx + * for more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Optional. Parameters supplied to the Get Web Site + * Operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Web Site operation response. + */ + WebSiteGetResponse get(String webSpaceName, String webSiteName, WebSiteGetParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * You can retrieve details for a web site by issuing an HTTP GET request. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn167007.aspx + * for more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Optional. Parameters supplied to the Get Web Site + * Operation. + * @return The Get Web Site operation response. + */ + Future getAsync(String webSpaceName, String webSiteName, WebSiteGetParameters parameters); + + /** + * You can retrieve the config settings for a web site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Configuration Web Site operation response. + */ + WebSiteGetConfigurationResponse getConfiguration(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * You can retrieve the config settings for a web site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Configuration Web Site operation response. + */ + Future getConfigurationAsync(String webSpaceName, String webSiteName); + + /** + * You can retrieve historical usage metrics for a site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Get Historical + * Usage Metrics Web Site operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Historical Usage Metrics Web Site operation response. + */ + WebSiteGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName, String webSiteName, WebSiteGetHistoricalUsageMetricsParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * You can retrieve historical usage metrics for a site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Get Historical + * Usage Metrics Web Site operation. + * @return The Get Historical Usage Metrics Web Site operation response. + */ + Future getHistoricalUsageMetricsAsync(String webSpaceName, String webSiteName, WebSiteGetHistoricalUsageMetricsParameters parameters); + + /** + * You can retrieve the list of active instances by ids for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The web site instance ids reponse. + */ + WebSiteInstanceIdsResponse getInstanceIds(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * You can retrieve the list of active instances by ids for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The web site instance ids reponse. + */ + Future getInstanceIdsAsync(String webSpaceName, String webSiteName); + + /** + * You can retrieve the publish settings information for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166996.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Publish Profile Web Site operation response. + */ + WebSiteGetPublishProfileResponse getPublishProfile(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * You can retrieve the publish settings information for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166996.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Publish Profile Web Site operation response. + */ + Future getPublishProfileAsync(String webSpaceName, String webSiteName); + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository get operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Repository Web Site operation response. + */ + WebSiteGetRepositoryResponse getRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository get operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Repository Web Site operation response. + */ + Future getRepositoryAsync(String webSpaceName, String webSiteName); + + /** + * You can retrieve current usage metrics for a site by issuing an HTTP GET + * request. The metrics returned include CPU Time, Data In, Data Out, Local + * Bytes Read, Local Bytes Written, Network Bytes Read, Network Bytes + * Written, WP Stop Requests, Memory Usage, CPU Time - Minute Limit, and + * File System Storage. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166991.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Usage Metrics Web Site operation response. + */ + WebSiteGetUsageMetricsResponse getUsageMetrics(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * You can retrieve current usage metrics for a site by issuing an HTTP GET + * request. The metrics returned include CPU Time, Data In, Data Out, Local + * Bytes Read, Local Bytes Written, Network Bytes Read, Network Bytes + * Written, WP Stop Requests, Memory Usage, CPU Time - Minute Limit, and + * File System Storage. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166991.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Usage Metrics Web Site operation response. + */ + Future getUsageMetricsAsync(String webSpaceName, String webSiteName); + + /** + * Determines if a host name is available. + * + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Is Hostname Available Web Site operation response. + */ + WebSiteIsHostnameAvailableResponse isHostnameAvailable(String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Determines if a host name is available. + * + * @param webSiteName Required. The name of the web site. + * @return The Is Hostname Available Web Site operation response. + */ + Future isHostnameAvailableAsync(String webSiteName); + + /** + * You can restart a web site by issuing an HTTP POST request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236425.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse restart(String webSpaceName, String webSiteName) throws IOException, ServiceException; + + /** + * You can restart a web site by issuing an HTTP POST request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236425.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future restartAsync(String webSpaceName, String webSiteName); + + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + WebSiteOperationStatusResponse swapSlots(String webSpaceName, String webSiteName, String sourceSlotName, String targetSlotName) throws InterruptedException, ExecutionException, ServiceException, IOException; + + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + Future swapSlotsAsync(String webSpaceName, String webSiteName, String sourceSlotName, String targetSlotName); + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository sync operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse syncRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException; + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository sync operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future syncRepositoryAsync(String webSpaceName, String webSiteName); + + /** + * You can update the settings for a web site by using the HTTP PUT method + * and by specifying the settings in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167005.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update Web Site + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Update Web Site operation response. + */ + WebSiteUpdateResponse update(String webSpaceName, String webSiteName, WebSiteUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException; + + /** + * You can update the settings for a web site by using the HTTP PUT method + * and by specifying the settings in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167005.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update Web Site + * operation. + * @return The Update Web Site operation response. + */ + Future updateAsync(String webSpaceName, String webSiteName, WebSiteUpdateParameters parameters); + + /** + * You can update the config settings for a web site by issuing an HTTP PUT + * with a request body containing the updated settings. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update + * Configuration Web Site operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse updateConfiguration(String webSpaceName, String webSiteName, WebSiteUpdateConfigurationParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * You can update the config settings for a web site by issuing an HTTP PUT + * with a request body containing the updated settings. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update + * Configuration Web Site operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future updateConfigurationAsync(String webSpaceName, String webSiteName, WebSiteUpdateConfigurationParameters parameters); +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteOperationsImpl.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteOperationsImpl.java new file mode 100644 index 0000000000000..2b42d46e0fec0 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSiteOperationsImpl.java @@ -0,0 +1,4954 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.CommaStringBuilder; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.ManagedPipelineMode; +import com.microsoft.windowsazure.management.websites.models.RemoteDebuggingVersion; +import com.microsoft.windowsazure.management.websites.models.WebSite; +import com.microsoft.windowsazure.management.websites.models.WebSiteComputeMode; +import com.microsoft.windowsazure.management.websites.models.WebSiteCreateParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteCreateResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteDeleteParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteDeleteRepositoryResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetConfigurationResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetHistoricalUsageMetricsParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetHistoricalUsageMetricsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetPublishProfileResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetRepositoryResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteGetUsageMetricsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteInstanceIdsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteIsHostnameAvailableResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteMode; +import com.microsoft.windowsazure.management.websites.models.WebSiteOperationStatus; +import com.microsoft.windowsazure.management.websites.models.WebSiteOperationStatusResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteRuntimeAvailabilityState; +import com.microsoft.windowsazure.management.websites.models.WebSiteSslState; +import com.microsoft.windowsazure.management.websites.models.WebSiteUpdateConfigurationParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteUpdateParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteUpdateResponse; +import com.microsoft.windowsazure.management.websites.models.WebSiteUsageState; +import com.microsoft.windowsazure.management.websites.models.WebSpaceAvailabilityState; +import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Operations for managing the web sites in a web space. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for more +* information) +*/ +public class WebSiteOperationsImpl implements ServiceOperations, WebSiteOperations { + /** + * Initializes a new instance of the WebSiteOperationsImpl class. + * + * @param client Reference to the service client. + */ + WebSiteOperationsImpl(WebSiteManagementClientImpl client) { + this.client = client; + } + + private WebSiteManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.websites.WebSiteManagementClientImpl. + * @return The Client value. + */ + public WebSiteManagementClientImpl getClient() { + return this.client; + } + + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + @Override + public Future beginSwapingSlotsAsync(final String webSpaceName, final String webSiteName, final String sourceSlotName, final String targetSlotName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteOperationStatusResponse call() throws Exception { + return beginSwapingSlots(webSpaceName, webSiteName, sourceSlotName, targetSlotName); + } + }); + } + + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + @Override + public WebSiteOperationStatusResponse beginSwapingSlots(String webSpaceName, String webSiteName, String sourceSlotName, String targetSlotName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + if (sourceSlotName == null) { + throw new NullPointerException("sourceSlotName"); + } + if (targetSlotName == null) { + throw new NullPointerException("targetSlotName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + tracingParameters.put("sourceSlotName", sourceSlotName); + tracingParameters.put("targetSlotName", targetSlotName); + CloudTracing.enter(invocationId, this, "beginSwapingSlotsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "(" + sourceSlotName.trim() + ")/slots" + "?"; + url = url + "Command=swap"; + url = url + "&" + "targetSlot=" + URLEncoder.encode(targetSlotName.trim(), "UTF-8"); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteOperationStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteOperationStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + Element createdTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); + if (createdTimeElement != null) { + Calendar createdTimeInstance; + createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); + result.setCreatedTime(createdTimeInstance); + } + + Element errorsSequenceElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Errors"); + if (errorsSequenceElement != null) { + boolean isNil = false; + Attr nilAttribute = errorsSequenceElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(errorsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Error").size(); i1 = i1 + 1) { + org.w3c.dom.Element errorsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(errorsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Error").get(i1)); + WebSiteOperationStatusResponse.Error errorInstance = new WebSiteOperationStatusResponse.Error(); + result.getErrors().add(errorInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + boolean isNil2 = false; + Attr nilAttribute2 = codeElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + errorInstance.setCode(codeInstance); + } + } + + Element messageElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + boolean isNil3 = false; + Attr nilAttribute3 = messageElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute3 != null) { + isNil3 = "true".equals(nilAttribute3.getValue()); + } + if (isNil3 == false) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + errorInstance.setMessage(messageInstance); + } + } + + Element extendedCodeElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "ExtendedCode"); + if (extendedCodeElement != null) { + boolean isNil4 = false; + Attr nilAttribute4 = extendedCodeElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute4 != null) { + isNil4 = "true".equals(nilAttribute4.getValue()); + } + if (isNil4 == false) { + String extendedCodeInstance; + extendedCodeInstance = extendedCodeElement.getTextContent(); + errorInstance.setExtendedCode(extendedCodeInstance); + } + } + + Element messageTemplateElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "MessageTemplate"); + if (messageTemplateElement != null) { + boolean isNil5 = false; + Attr nilAttribute5 = messageTemplateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute5 != null) { + isNil5 = "true".equals(nilAttribute5.getValue()); + } + if (isNil5 == false) { + String messageTemplateInstance; + messageTemplateInstance = messageTemplateElement.getTextContent(); + errorInstance.setMessageTemplate(messageTemplateInstance); + } + } + + Element parametersSequenceElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Parameters"); + if (parametersSequenceElement != null) { + boolean isNil6 = false; + Attr nilAttribute6 = parametersSequenceElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute6 != null) { + isNil6 = "true".equals(nilAttribute6.getValue()); + } + if (isNil6 == false) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(parametersSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i2 = i2 + 1) { + org.w3c.dom.Element parametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(parametersSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i2)); + errorInstance.getParameters().add(parametersElement.getTextContent()); + } + } + } + + Element innerErrorsElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "InnerErrors"); + if (innerErrorsElement != null) { + boolean isNil7 = false; + Attr nilAttribute7 = innerErrorsElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute7 != null) { + isNil7 = "true".equals(nilAttribute7.getValue()); + } + if (isNil7 == false) { + String innerErrorsInstance; + innerErrorsInstance = innerErrorsElement.getTextContent(); + errorInstance.setInnerErrors(innerErrorsInstance); + } + } + } + } + } + + Element expirationTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ExpirationTime"); + if (expirationTimeElement != null) { + Calendar expirationTimeInstance; + expirationTimeInstance = DatatypeConverter.parseDateTime(expirationTimeElement.getTextContent()); + result.setExpirationTime(expirationTimeInstance); + } + + Element geoMasterOperationIdElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "GeoMasterOperationId"); + if (geoMasterOperationIdElement != null) { + boolean isNil8 = false; + Attr nilAttribute8 = geoMasterOperationIdElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute8 != null) { + isNil8 = "true".equals(nilAttribute8.getValue()); + } + if (isNil8 == false) { + String geoMasterOperationIdInstance; + geoMasterOperationIdInstance = geoMasterOperationIdElement.getTextContent(); + result.setGeoMasterOperationId(geoMasterOperationIdInstance); + } + } + + Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Id"); + if (idElement != null) { + boolean isNil9 = false; + Attr nilAttribute9 = idElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute9 != null) { + isNil9 = "true".equals(nilAttribute9.getValue()); + } + if (isNil9 == false) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setOperationId(idInstance); + } + } + + Element modifiedTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ModifiedTime"); + if (modifiedTimeElement != null) { + Calendar modifiedTimeInstance; + modifiedTimeInstance = DatatypeConverter.parseDateTime(modifiedTimeElement.getTextContent()); + result.setModifiedTime(modifiedTimeInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + boolean isNil10 = false; + Attr nilAttribute10 = nameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute10 != null) { + isNil10 = "true".equals(nilAttribute10.getValue()); + } + if (isNil10 == false) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + } + + Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + WebSiteOperationStatus statusInstance; + statusInstance = WebSiteOperationStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can create a web site by using a POST request that includes the name + * of the web site and other information in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166986.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Web Site + * operation. + * @return The Create Web Site operation response. + */ + @Override + public Future createAsync(final String webSpaceName, final WebSiteCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteCreateResponse call() throws Exception { + return create(webSpaceName, parameters); + } + }); + } + + /** + * You can create a web site by using a POST request that includes the name + * of the web site and other information in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166986.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Required. Parameters supplied to the Create Web Site + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Create Web Site operation response. + */ + @Override + public WebSiteCreateResponse create(String webSpaceName, WebSiteCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + if (parameters.getWebSpace() != null) { + if (parameters.getWebSpace().getGeoRegion() == null) { + throw new NullPointerException("parameters.WebSpace.GeoRegion"); + } + if (parameters.getWebSpace().getName() == null) { + throw new NullPointerException("parameters.WebSpace.Name"); + } + if (parameters.getWebSpace().getPlan() == null) { + throw new NullPointerException("parameters.WebSpace.Plan"); + } + } + if (parameters.getWebSpaceName() == null) { + throw new NullPointerException("parameters.WebSpaceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element siteElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Site"); + requestDoc.appendChild(siteElement); + + if (parameters.getHostNames() != null) { + Element hostNamesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostNames"); + for (String hostNamesItem : parameters.getHostNames()) { + Element hostNamesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string"); + hostNamesItemElement.appendChild(requestDoc.createTextNode(hostNamesItem)); + hostNamesSequenceElement.appendChild(hostNamesItemElement); + } + siteElement.appendChild(hostNamesSequenceElement); + } + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + siteElement.appendChild(nameElement); + + if (parameters.getComputeMode() != null) { + Element computeModeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ComputeMode"); + computeModeElement.appendChild(requestDoc.createTextNode(parameters.getComputeMode().toString())); + siteElement.appendChild(computeModeElement); + } + + if (parameters.getServerFarm() != null) { + Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServerFarm"); + serverFarmElement.appendChild(requestDoc.createTextNode(parameters.getServerFarm())); + siteElement.appendChild(serverFarmElement); + } + + if (parameters.getSiteMode() != null) { + Element siteModeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SiteMode"); + siteModeElement.appendChild(requestDoc.createTextNode(parameters.getSiteMode().toString())); + siteElement.appendChild(siteModeElement); + } + + Element webSpaceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WebSpace"); + webSpaceElement.appendChild(requestDoc.createTextNode(parameters.getWebSpaceName())); + siteElement.appendChild(webSpaceElement); + + if (parameters.getWebSpace() != null) { + Element webSpaceToCreateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WebSpaceToCreate"); + siteElement.appendChild(webSpaceToCreateElement); + + Element geoRegionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "GeoRegion"); + geoRegionElement.appendChild(requestDoc.createTextNode(parameters.getWebSpace().getGeoRegion())); + webSpaceToCreateElement.appendChild(geoRegionElement); + + Element nameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement2.appendChild(requestDoc.createTextNode(parameters.getWebSpace().getName())); + webSpaceToCreateElement.appendChild(nameElement2); + + Element planElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Plan"); + planElement.appendChild(requestDoc.createTextNode(parameters.getWebSpace().getPlan())); + webSpaceToCreateElement.appendChild(planElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteCreateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteCreateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element siteElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Site"); + if (siteElement2 != null) { + WebSite webSiteInstance = new WebSite(); + result.setWebSite(webSiteInstance); + + Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "AdminEnabled"); + if (adminEnabledElement != null) { + boolean adminEnabledInstance; + adminEnabledInstance = DatatypeConverter.parseBoolean(adminEnabledElement.getTextContent().toLowerCase()); + webSiteInstance.setAdminEnabled(adminEnabledInstance); + } + + Element availabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "AvailabilityState"); + if (availabilityStateElement != null) { + WebSpaceAvailabilityState availabilityStateInstance; + availabilityStateInstance = WebSpaceAvailabilityState.valueOf(availabilityStateElement.getTextContent()); + webSiteInstance.setAvailabilityState(availabilityStateInstance); + } + + Element computeModeElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "ComputeMode"); + if (computeModeElement2 != null) { + WebSiteComputeMode computeModeInstance; + computeModeInstance = WebSiteComputeMode.valueOf(computeModeElement2.getTextContent()); + webSiteInstance.setComputeMode(computeModeInstance); + } + + Element enabledElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "Enabled"); + if (enabledElement != null) { + boolean enabledInstance; + enabledInstance = DatatypeConverter.parseBoolean(enabledElement.getTextContent().toLowerCase()); + webSiteInstance.setEnabled(enabledInstance); + } + + Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "EnabledHostNames"); + if (enabledHostNamesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i1 = i1 + 1) { + org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i1)); + webSiteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent()); + } + } + + Element hostNameSslStatesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "HostNameSslStates"); + if (hostNameSslStatesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").size(); i2 = i2 + 1) { + org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").get(i2)); + WebSite.WebSiteHostNameSslState webSiteHostNameSslStateInstance = new WebSite.WebSiteHostNameSslState(); + webSiteInstance.getHostNameSslStates().add(webSiteHostNameSslStateInstance); + + Element nameElement3 = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement3 != null) { + String nameInstance; + nameInstance = nameElement3.getTextContent(); + webSiteHostNameSslStateInstance.setName(nameInstance); + } + + Element sslStateElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "SslState"); + if (sslStateElement != null) { + WebSiteSslState sslStateInstance; + sslStateInstance = WebSiteSslState.valueOf(sslStateElement.getTextContent()); + webSiteHostNameSslStateInstance.setSslState(sslStateInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + boolean isNil = false; + Attr nilAttribute = thumbprintElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + webSiteHostNameSslStateInstance.setThumbprint(thumbprintInstance); + } + } + + Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP"); + if (virtualIPElement != null) { + boolean isNil2 = false; + Attr nilAttribute2 = virtualIPElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + InetAddress virtualIPInstance; + virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent()); + webSiteHostNameSslStateInstance.setVirtualIP(virtualIPInstance); + } + } + } + } + + Element hostNamesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement2 != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i3 = i3 + 1) { + org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i3)); + webSiteInstance.getHostNames().add(hostNamesElement.getTextContent()); + } + } + + Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc"); + if (lastModifiedTimeUtcElement != null) { + Calendar lastModifiedTimeUtcInstance; + lastModifiedTimeUtcInstance = DatatypeConverter.parseDateTime(lastModifiedTimeUtcElement.getTextContent()); + webSiteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance); + } + + Element nameElement4 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement4 != null) { + String nameInstance2; + nameInstance2 = nameElement4.getTextContent(); + webSiteInstance.setName(nameInstance2); + } + + Element ownerElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "Owner"); + if (ownerElement != null) { + boolean isNil3 = false; + Attr nilAttribute3 = ownerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute3 != null) { + isNil3 = "true".equals(nilAttribute3.getValue()); + } + if (isNil3 == false) { + String ownerInstance; + ownerInstance = ownerElement.getTextContent(); + webSiteInstance.setOwner(ownerInstance); + } + } + + Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "RepositorySiteName"); + if (repositorySiteNameElement != null) { + String repositorySiteNameInstance; + repositorySiteNameInstance = repositorySiteNameElement.getTextContent(); + webSiteInstance.setRepositorySiteName(repositorySiteNameInstance); + } + + Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState"); + if (runtimeAvailabilityStateElement != null) { + WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance; + runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState.valueOf(runtimeAvailabilityStateElement.getTextContent()); + webSiteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance); + } + + Element sSLCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SSLCertificates"); + if (sSLCertificatesSequenceElement != null) { + boolean isNil4 = false; + Attr nilAttribute4 = sSLCertificatesSequenceElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute4 != null) { + isNil4 = "true".equals(nilAttribute4.getValue()); + } + if (isNil4 == false) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").size(); i4 = i4 + 1) { + org.w3c.dom.Element sSLCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").get(i4)); + WebSite.WebSiteSslCertificate certificateInstance = new WebSite.WebSiteSslCertificate(); + webSiteInstance.getSslCertificates().add(certificateInstance); + + Element expirationDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ExpirationDate"); + if (expirationDateElement != null && (expirationDateElement.getTextContent() == null || expirationDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil5 = false; + Attr nilAttribute5 = expirationDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute5 != null) { + isNil5 = "true".equals(nilAttribute5.getValue()); + } + if (isNil5 == false) { + Calendar expirationDateInstance; + expirationDateInstance = DatatypeConverter.parseDateTime(expirationDateElement.getTextContent()); + certificateInstance.setExpirationDate(expirationDateInstance); + } + } + + Element friendlyNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "FriendlyName"); + if (friendlyNameElement != null) { + boolean isNil6 = false; + Attr nilAttribute6 = friendlyNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute6 != null) { + isNil6 = "true".equals(nilAttribute6.getValue()); + } + if (isNil6 == false) { + String friendlyNameInstance; + friendlyNameInstance = friendlyNameElement.getTextContent(); + certificateInstance.setFriendlyName(friendlyNameInstance); + } + } + + Element hostNamesSequenceElement3 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement3 != null) { + boolean isNil7 = false; + Attr nilAttribute7 = hostNamesSequenceElement3.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute7 != null) { + isNil7 = "true".equals(nilAttribute7.getValue()); + } + if (isNil7 == false) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement3, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i5 = i5 + 1) { + org.w3c.dom.Element hostNamesElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement3, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i5)); + certificateInstance.getHostNames().add(hostNamesElement2.getTextContent()); + } + } + } + + Element issueDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "IssueDate"); + if (issueDateElement != null && (issueDateElement.getTextContent() == null || issueDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil8 = false; + Attr nilAttribute8 = issueDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute8 != null) { + isNil8 = "true".equals(nilAttribute8.getValue()); + } + if (isNil8 == false) { + Calendar issueDateInstance; + issueDateInstance = DatatypeConverter.parseDateTime(issueDateElement.getTextContent()); + certificateInstance.setIssueDate(issueDateInstance); + } + } + + Element issuerElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Issuer"); + if (issuerElement != null) { + boolean isNil9 = false; + Attr nilAttribute9 = issuerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute9 != null) { + isNil9 = "true".equals(nilAttribute9.getValue()); + } + if (isNil9 == false) { + String issuerInstance; + issuerInstance = issuerElement.getTextContent(); + certificateInstance.setIssuer(issuerInstance); + } + } + + Element passwordElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement != null) { + boolean isNil10 = false; + Attr nilAttribute10 = passwordElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute10 != null) { + isNil10 = "true".equals(nilAttribute10.getValue()); + } + if (isNil10 == false) { + String passwordInstance; + passwordInstance = passwordElement.getTextContent(); + certificateInstance.setPassword(passwordInstance); + } + } + + Element pfxBlobElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "PfxBlob"); + if (pfxBlobElement != null) { + boolean isNil11 = false; + Attr nilAttribute11 = pfxBlobElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute11 != null) { + isNil11 = "true".equals(nilAttribute11.getValue()); + } + if (isNil11 == false) { + byte[] pfxBlobInstance; + pfxBlobInstance = pfxBlobElement.getTextContent() != null ? Base64.decode(pfxBlobElement.getTextContent()) : null; + certificateInstance.setPfxBlob(pfxBlobInstance); + } + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + boolean isNil12 = false; + Attr nilAttribute12 = selfLinkElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute12 != null) { + isNil12 = "true".equals(nilAttribute12.getValue()); + } + if (isNil12 == false) { + URI selfLinkInstance; + selfLinkInstance = new URI(selfLinkElement.getTextContent()); + certificateInstance.setSelfLinkUri(selfLinkInstance); + } + } + + Element siteNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SiteName"); + if (siteNameElement != null) { + boolean isNil13 = false; + Attr nilAttribute13 = siteNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute13 != null) { + isNil13 = "true".equals(nilAttribute13.getValue()); + } + if (isNil13 == false) { + String siteNameInstance; + siteNameInstance = siteNameElement.getTextContent(); + certificateInstance.setSiteName(siteNameInstance); + } + } + + Element subjectNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubjectName"); + if (subjectNameElement != null) { + boolean isNil14 = false; + Attr nilAttribute14 = subjectNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute14 != null) { + isNil14 = "true".equals(nilAttribute14.getValue()); + } + if (isNil14 == false) { + String subjectNameInstance; + subjectNameInstance = subjectNameElement.getTextContent(); + certificateInstance.setSubjectName(subjectNameInstance); + } + } + + Element thumbprintElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement2 != null) { + boolean isNil15 = false; + Attr nilAttribute15 = thumbprintElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute15 != null) { + isNil15 = "true".equals(nilAttribute15.getValue()); + } + if (isNil15 == false) { + String thumbprintInstance2; + thumbprintInstance2 = thumbprintElement2.getTextContent(); + certificateInstance.setThumbprint(thumbprintInstance2); + } + } + + Element toDeleteElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ToDelete"); + if (toDeleteElement != null && (toDeleteElement.getTextContent() == null || toDeleteElement.getTextContent().isEmpty() == true) == false) { + boolean isNil16 = false; + Attr nilAttribute16 = toDeleteElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute16 != null) { + isNil16 = "true".equals(nilAttribute16.getValue()); + } + if (isNil16 == false) { + boolean toDeleteInstance; + toDeleteInstance = DatatypeConverter.parseBoolean(toDeleteElement.getTextContent().toLowerCase()); + certificateInstance.setIsToBeDeleted(toDeleteInstance); + } + } + + Element validElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Valid"); + if (validElement != null && (validElement.getTextContent() == null || validElement.getTextContent().isEmpty() == true) == false) { + boolean isNil17 = false; + Attr nilAttribute17 = validElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute17 != null) { + isNil17 = "true".equals(nilAttribute17.getValue()); + } + if (isNil17 == false) { + boolean validInstance; + validInstance = DatatypeConverter.parseBoolean(validElement.getTextContent().toLowerCase()); + certificateInstance.setIsValid(validInstance); + } + } + } + } + } + + Element selfLinkElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement2 != null) { + URI selfLinkInstance2; + selfLinkInstance2 = new URI(selfLinkElement2.getTextContent()); + webSiteInstance.setUri(selfLinkInstance2); + } + + Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); + if (serverFarmElement2 != null) { + String serverFarmInstance; + serverFarmInstance = serverFarmElement2.getTextContent(); + webSiteInstance.setServerFarm(serverFarmInstance); + } + + Element siteModeElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SiteMode"); + if (siteModeElement2 != null) { + WebSiteMode siteModeInstance; + siteModeInstance = WebSiteMode.valueOf(siteModeElement2.getTextContent()); + webSiteInstance.setSiteMode(siteModeInstance); + } + + Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SiteProperties"); + if (sitePropertiesElement != null) { + WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties(); + webSiteInstance.setSiteProperties(sitePropertiesInstance); + + Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AppSettings"); + if (appSettingsSequenceElement != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i6 = i6 + 1) { + org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i6)); + String appSettingsKey = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String appSettingsValue = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue); + } + } + + Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Metadata"); + if (metadataSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i7 = i7 + 1) { + org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i7)); + String metadataKey = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String metadataValue = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue); + } + } + + Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Properties"); + if (propertiesSequenceElement != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i8 = i8 + 1) { + org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i8)); + String propertiesKey = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String propertiesValue = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue); + } + } + } + + Element stateElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + webSiteInstance.setState(stateInstance); + } + + Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "UsageState"); + if (usageStateElement != null) { + WebSiteUsageState usageStateInstance; + usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent()); + webSiteInstance.setUsageState(usageStateInstance); + } + + Element webSpaceElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "WebSpace"); + if (webSpaceElement2 != null) { + String webSpaceInstance; + webSpaceInstance = webSpaceElement2.getTextContent(); + webSiteInstance.setWebSpace(webSpaceInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository create operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future createRepositoryAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return createRepository(webSpaceName, webSiteName); + } + }); + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository create operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse createRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "createRepositoryAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/repository"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can delete a web site by issuing an HTTP DELETE request. If the web + * site being deleted is the only site remaining in a server farm, you can + * optionally delete the server farm as well by using the + * deleteEmptyServerFarm parameter. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236430.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Delete Web Site + * operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String webSpaceName, final String webSiteName, final WebSiteDeleteParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(webSpaceName, webSiteName, parameters); + } + }); + } + + /** + * You can delete a web site by issuing an HTTP DELETE request. If the web + * site being deleted is the only site remaining in a server farm, you can + * optionally delete the server farm as well by using the + * deleteEmptyServerFarm parameter. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236430.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Delete Web Site + * operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String webSpaceName, String webSiteName, WebSiteDeleteParameters parameters) throws IOException, ServiceException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "?"; + url = url + "deleteEmptyServerFarm=" + URLEncoder.encode(Boolean.toString(parameters.isDeleteEmptyServerFarm()).toLowerCase(), "UTF-8"); + url = url + "&" + "deleteMetrics=" + URLEncoder.encode(Boolean.toString(parameters.isDeleteMetrics()).toLowerCase(), "UTF-8"); + url = url + "&" + "deleteAllSlots=" + URLEncoder.encode(Boolean.toString(parameters.isDeleteAllSlots()).toLowerCase(), "UTF-8"); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository delete operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Delete Repository Web Site operation response. + */ + @Override + public Future deleteRepositoryAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteDeleteRepositoryResponse call() throws Exception { + return deleteRepository(webSpaceName, webSiteName); + } + }); + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository delete operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Delete Repository Web Site operation response. + */ + @Override + public WebSiteDeleteRepositoryResponse deleteRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "deleteRepositoryAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/repository"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteDeleteRepositoryResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteDeleteRepositoryResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element anyURIElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "anyURI"); + if (anyURIElement != null) { + result.setUri(new URI(anyURIElement.getTextContent())); + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can generate a new random password for publishing a site by issuing + * an HTTP POST request. Tip: If you want to verify that the publish + * password has changed, issue an HTTP GET on /publishxml before calling + * /newpassword. In the publish XML, note the hash value in the userPWD + * attribute. After calling /newpassword, call /publishxml again. You can + * then compare the new value of userPWD in the Publish XML with the one + * you noted earlier. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236428.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future generatePasswordAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return generatePassword(webSpaceName, webSiteName); + } + }); + } + + /** + * You can generate a new random password for publishing a site by issuing + * an HTTP POST request. Tip: If you want to verify that the publish + * password has changed, issue an HTTP GET on /publishxml before calling + * /newpassword. In the publish XML, note the hash value in the userPWD + * attribute. After calling /newpassword, call /publishxml again. You can + * then compare the new value of userPWD in the Publish XML with the one + * you noted earlier. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236428.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse generatePassword(String webSpaceName, String webSiteName) throws IOException, ServiceException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "generatePasswordAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/newpassword"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve details for a web site by issuing an HTTP GET request. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn167007.aspx + * for more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Optional. Parameters supplied to the Get Web Site + * Operation. + * @return The Get Web Site operation response. + */ + @Override + public Future getAsync(final String webSpaceName, final String webSiteName, final WebSiteGetParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteGetResponse call() throws Exception { + return get(webSpaceName, webSiteName, parameters); + } + }); + } + + /** + * You can retrieve details for a web site by issuing an HTTP GET request. + * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn167007.aspx + * for more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Optional. Parameters supplied to the Get Web Site + * Operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Web Site operation response. + */ + @Override + public WebSiteGetResponse get(String webSpaceName, String webSiteName, WebSiteGetParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "?"; + if (parameters != null && parameters.getPropertiesToInclude() != null && parameters.getPropertiesToInclude().size() > 0) { + url = url + "propertiesToInclude=" + URLEncoder.encode(CommaStringBuilder.join(parameters.getPropertiesToInclude()), "UTF-8"); + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element siteElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Site"); + if (siteElement != null) { + WebSite webSiteInstance = new WebSite(); + result.setWebSite(webSiteInstance); + + Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "AdminEnabled"); + if (adminEnabledElement != null) { + boolean adminEnabledInstance; + adminEnabledInstance = DatatypeConverter.parseBoolean(adminEnabledElement.getTextContent().toLowerCase()); + webSiteInstance.setAdminEnabled(adminEnabledInstance); + } + + Element availabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "AvailabilityState"); + if (availabilityStateElement != null) { + WebSpaceAvailabilityState availabilityStateInstance; + availabilityStateInstance = WebSpaceAvailabilityState.valueOf(availabilityStateElement.getTextContent()); + webSiteInstance.setAvailabilityState(availabilityStateInstance); + } + + Element computeModeElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "ComputeMode"); + if (computeModeElement != null) { + WebSiteComputeMode computeModeInstance; + computeModeInstance = WebSiteComputeMode.valueOf(computeModeElement.getTextContent()); + webSiteInstance.setComputeMode(computeModeInstance); + } + + Element enabledElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "Enabled"); + if (enabledElement != null) { + boolean enabledInstance; + enabledInstance = DatatypeConverter.parseBoolean(enabledElement.getTextContent().toLowerCase()); + webSiteInstance.setEnabled(enabledInstance); + } + + Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "EnabledHostNames"); + if (enabledHostNamesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i1 = i1 + 1) { + org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i1)); + webSiteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent()); + } + } + + Element hostNameSslStatesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "HostNameSslStates"); + if (hostNameSslStatesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").size(); i2 = i2 + 1) { + org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").get(i2)); + WebSite.WebSiteHostNameSslState webSiteHostNameSslStateInstance = new WebSite.WebSiteHostNameSslState(); + webSiteInstance.getHostNameSslStates().add(webSiteHostNameSslStateInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + webSiteHostNameSslStateInstance.setName(nameInstance); + } + + Element sslStateElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "SslState"); + if (sslStateElement != null) { + WebSiteSslState sslStateInstance; + sslStateInstance = WebSiteSslState.valueOf(sslStateElement.getTextContent()); + webSiteHostNameSslStateInstance.setSslState(sslStateInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + boolean isNil = false; + Attr nilAttribute = thumbprintElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + webSiteHostNameSslStateInstance.setThumbprint(thumbprintInstance); + } + } + + Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP"); + if (virtualIPElement != null) { + boolean isNil2 = false; + Attr nilAttribute2 = virtualIPElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + InetAddress virtualIPInstance; + virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent()); + webSiteHostNameSslStateInstance.setVirtualIP(virtualIPInstance); + } + } + } + } + + Element hostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i3 = i3 + 1) { + org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i3)); + webSiteInstance.getHostNames().add(hostNamesElement.getTextContent()); + } + } + + Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc"); + if (lastModifiedTimeUtcElement != null) { + Calendar lastModifiedTimeUtcInstance; + lastModifiedTimeUtcInstance = DatatypeConverter.parseDateTime(lastModifiedTimeUtcElement.getTextContent()); + webSiteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + webSiteInstance.setName(nameInstance2); + } + + Element ownerElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "Owner"); + if (ownerElement != null) { + boolean isNil3 = false; + Attr nilAttribute3 = ownerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute3 != null) { + isNil3 = "true".equals(nilAttribute3.getValue()); + } + if (isNil3 == false) { + String ownerInstance; + ownerInstance = ownerElement.getTextContent(); + webSiteInstance.setOwner(ownerInstance); + } + } + + Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "RepositorySiteName"); + if (repositorySiteNameElement != null) { + String repositorySiteNameInstance; + repositorySiteNameInstance = repositorySiteNameElement.getTextContent(); + webSiteInstance.setRepositorySiteName(repositorySiteNameInstance); + } + + Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState"); + if (runtimeAvailabilityStateElement != null) { + WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance; + runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState.valueOf(runtimeAvailabilityStateElement.getTextContent()); + webSiteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance); + } + + Element sSLCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "SSLCertificates"); + if (sSLCertificatesSequenceElement != null) { + boolean isNil4 = false; + Attr nilAttribute4 = sSLCertificatesSequenceElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute4 != null) { + isNil4 = "true".equals(nilAttribute4.getValue()); + } + if (isNil4 == false) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").size(); i4 = i4 + 1) { + org.w3c.dom.Element sSLCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").get(i4)); + WebSite.WebSiteSslCertificate certificateInstance = new WebSite.WebSiteSslCertificate(); + webSiteInstance.getSslCertificates().add(certificateInstance); + + Element expirationDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ExpirationDate"); + if (expirationDateElement != null && (expirationDateElement.getTextContent() == null || expirationDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil5 = false; + Attr nilAttribute5 = expirationDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute5 != null) { + isNil5 = "true".equals(nilAttribute5.getValue()); + } + if (isNil5 == false) { + Calendar expirationDateInstance; + expirationDateInstance = DatatypeConverter.parseDateTime(expirationDateElement.getTextContent()); + certificateInstance.setExpirationDate(expirationDateInstance); + } + } + + Element friendlyNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "FriendlyName"); + if (friendlyNameElement != null) { + boolean isNil6 = false; + Attr nilAttribute6 = friendlyNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute6 != null) { + isNil6 = "true".equals(nilAttribute6.getValue()); + } + if (isNil6 == false) { + String friendlyNameInstance; + friendlyNameInstance = friendlyNameElement.getTextContent(); + certificateInstance.setFriendlyName(friendlyNameInstance); + } + } + + Element hostNamesSequenceElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement2 != null) { + boolean isNil7 = false; + Attr nilAttribute7 = hostNamesSequenceElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute7 != null) { + isNil7 = "true".equals(nilAttribute7.getValue()); + } + if (isNil7 == false) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i5 = i5 + 1) { + org.w3c.dom.Element hostNamesElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i5)); + certificateInstance.getHostNames().add(hostNamesElement2.getTextContent()); + } + } + } + + Element issueDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "IssueDate"); + if (issueDateElement != null && (issueDateElement.getTextContent() == null || issueDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil8 = false; + Attr nilAttribute8 = issueDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute8 != null) { + isNil8 = "true".equals(nilAttribute8.getValue()); + } + if (isNil8 == false) { + Calendar issueDateInstance; + issueDateInstance = DatatypeConverter.parseDateTime(issueDateElement.getTextContent()); + certificateInstance.setIssueDate(issueDateInstance); + } + } + + Element issuerElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Issuer"); + if (issuerElement != null) { + boolean isNil9 = false; + Attr nilAttribute9 = issuerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute9 != null) { + isNil9 = "true".equals(nilAttribute9.getValue()); + } + if (isNil9 == false) { + String issuerInstance; + issuerInstance = issuerElement.getTextContent(); + certificateInstance.setIssuer(issuerInstance); + } + } + + Element passwordElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement != null) { + boolean isNil10 = false; + Attr nilAttribute10 = passwordElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute10 != null) { + isNil10 = "true".equals(nilAttribute10.getValue()); + } + if (isNil10 == false) { + String passwordInstance; + passwordInstance = passwordElement.getTextContent(); + certificateInstance.setPassword(passwordInstance); + } + } + + Element pfxBlobElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "PfxBlob"); + if (pfxBlobElement != null) { + boolean isNil11 = false; + Attr nilAttribute11 = pfxBlobElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute11 != null) { + isNil11 = "true".equals(nilAttribute11.getValue()); + } + if (isNil11 == false) { + byte[] pfxBlobInstance; + pfxBlobInstance = pfxBlobElement.getTextContent() != null ? Base64.decode(pfxBlobElement.getTextContent()) : null; + certificateInstance.setPfxBlob(pfxBlobInstance); + } + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + boolean isNil12 = false; + Attr nilAttribute12 = selfLinkElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute12 != null) { + isNil12 = "true".equals(nilAttribute12.getValue()); + } + if (isNil12 == false) { + URI selfLinkInstance; + selfLinkInstance = new URI(selfLinkElement.getTextContent()); + certificateInstance.setSelfLinkUri(selfLinkInstance); + } + } + + Element siteNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SiteName"); + if (siteNameElement != null) { + boolean isNil13 = false; + Attr nilAttribute13 = siteNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute13 != null) { + isNil13 = "true".equals(nilAttribute13.getValue()); + } + if (isNil13 == false) { + String siteNameInstance; + siteNameInstance = siteNameElement.getTextContent(); + certificateInstance.setSiteName(siteNameInstance); + } + } + + Element subjectNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubjectName"); + if (subjectNameElement != null) { + boolean isNil14 = false; + Attr nilAttribute14 = subjectNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute14 != null) { + isNil14 = "true".equals(nilAttribute14.getValue()); + } + if (isNil14 == false) { + String subjectNameInstance; + subjectNameInstance = subjectNameElement.getTextContent(); + certificateInstance.setSubjectName(subjectNameInstance); + } + } + + Element thumbprintElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement2 != null) { + boolean isNil15 = false; + Attr nilAttribute15 = thumbprintElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute15 != null) { + isNil15 = "true".equals(nilAttribute15.getValue()); + } + if (isNil15 == false) { + String thumbprintInstance2; + thumbprintInstance2 = thumbprintElement2.getTextContent(); + certificateInstance.setThumbprint(thumbprintInstance2); + } + } + + Element toDeleteElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ToDelete"); + if (toDeleteElement != null && (toDeleteElement.getTextContent() == null || toDeleteElement.getTextContent().isEmpty() == true) == false) { + boolean isNil16 = false; + Attr nilAttribute16 = toDeleteElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute16 != null) { + isNil16 = "true".equals(nilAttribute16.getValue()); + } + if (isNil16 == false) { + boolean toDeleteInstance; + toDeleteInstance = DatatypeConverter.parseBoolean(toDeleteElement.getTextContent().toLowerCase()); + certificateInstance.setIsToBeDeleted(toDeleteInstance); + } + } + + Element validElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Valid"); + if (validElement != null && (validElement.getTextContent() == null || validElement.getTextContent().isEmpty() == true) == false) { + boolean isNil17 = false; + Attr nilAttribute17 = validElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute17 != null) { + isNil17 = "true".equals(nilAttribute17.getValue()); + } + if (isNil17 == false) { + boolean validInstance; + validInstance = DatatypeConverter.parseBoolean(validElement.getTextContent().toLowerCase()); + certificateInstance.setIsValid(validInstance); + } + } + } + } + } + + Element selfLinkElement2 = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement2 != null) { + URI selfLinkInstance2; + selfLinkInstance2 = new URI(selfLinkElement2.getTextContent()); + webSiteInstance.setUri(selfLinkInstance2); + } + + Element serverFarmElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); + if (serverFarmElement != null) { + String serverFarmInstance; + serverFarmInstance = serverFarmElement.getTextContent(); + webSiteInstance.setServerFarm(serverFarmInstance); + } + + Element siteModeElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "SiteMode"); + if (siteModeElement != null) { + WebSiteMode siteModeInstance; + siteModeInstance = WebSiteMode.valueOf(siteModeElement.getTextContent()); + webSiteInstance.setSiteMode(siteModeInstance); + } + + Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "SiteProperties"); + if (sitePropertiesElement != null) { + WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties(); + webSiteInstance.setSiteProperties(sitePropertiesInstance); + + Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AppSettings"); + if (appSettingsSequenceElement != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i6 = i6 + 1) { + org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i6)); + String appSettingsKey = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String appSettingsValue = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue); + } + } + + Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Metadata"); + if (metadataSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i7 = i7 + 1) { + org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i7)); + String metadataKey = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String metadataValue = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue); + } + } + + Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Properties"); + if (propertiesSequenceElement != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i8 = i8 + 1) { + org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i8)); + String propertiesKey = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String propertiesValue = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue); + } + } + } + + Element stateElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + webSiteInstance.setState(stateInstance); + } + + Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "UsageState"); + if (usageStateElement != null) { + WebSiteUsageState usageStateInstance; + usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent()); + webSiteInstance.setUsageState(usageStateInstance); + } + + Element webSpaceElement = XmlUtility.getElementByTagNameNS(siteElement, "http://schemas.microsoft.com/windowsazure", "WebSpace"); + if (webSpaceElement != null) { + String webSpaceInstance; + webSpaceInstance = webSpaceElement.getTextContent(); + webSiteInstance.setWebSpace(webSpaceInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve the config settings for a web site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Configuration Web Site operation response. + */ + @Override + public Future getConfigurationAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteGetConfigurationResponse call() throws Exception { + return getConfiguration(webSpaceName, webSiteName); + } + }); + } + + /** + * You can retrieve the config settings for a web site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Configuration Web Site operation response. + */ + @Override + public WebSiteGetConfigurationResponse getConfiguration(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "getConfigurationAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/config"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteGetConfigurationResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteGetConfigurationResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element siteConfigElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "SiteConfig"); + if (siteConfigElement != null) { + Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "AppSettings"); + if (appSettingsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i1 = i1 + 1) { + org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i1)); + String appSettingsKey = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String appSettingsValue = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + result.getAppSettings().put(appSettingsKey, appSettingsValue); + } + } + + Element connectionStringsSequenceElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "ConnectionStrings"); + if (connectionStringsSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(connectionStringsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConnStringInfo").size(); i2 = i2 + 1) { + org.w3c.dom.Element connectionStringsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(connectionStringsSequenceElement, "http://schemas.microsoft.com/windowsazure", "ConnStringInfo").get(i2)); + WebSiteGetConfigurationResponse.ConnectionStringInfo connStringInfoInstance = new WebSiteGetConfigurationResponse.ConnectionStringInfo(); + result.getConnectionStrings().add(connStringInfoInstance); + + Element connectionStringElement = XmlUtility.getElementByTagNameNS(connectionStringsElement, "http://schemas.microsoft.com/windowsazure", "ConnectionString"); + if (connectionStringElement != null) { + String connectionStringInstance; + connectionStringInstance = connectionStringElement.getTextContent(); + connStringInfoInstance.setConnectionString(connectionStringInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(connectionStringsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + connStringInfoInstance.setName(nameInstance); + } + + Element typeElement = XmlUtility.getElementByTagNameNS(connectionStringsElement, "http://schemas.microsoft.com/windowsazure", "Type"); + if (typeElement != null) { + String typeInstance; + typeInstance = typeElement.getTextContent(); + connStringInfoInstance.setType(typeInstance); + } + } + } + + Element defaultDocumentsSequenceElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "DefaultDocuments"); + if (defaultDocumentsSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(defaultDocumentsSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i3 = i3 + 1) { + org.w3c.dom.Element defaultDocumentsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(defaultDocumentsSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i3)); + result.getDefaultDocuments().add(defaultDocumentsElement.getTextContent()); + } + } + + Element detailedErrorLoggingEnabledElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "DetailedErrorLoggingEnabled"); + if (detailedErrorLoggingEnabledElement != null && (detailedErrorLoggingEnabledElement.getTextContent() == null || detailedErrorLoggingEnabledElement.getTextContent().isEmpty() == true) == false) { + boolean detailedErrorLoggingEnabledInstance; + detailedErrorLoggingEnabledInstance = DatatypeConverter.parseBoolean(detailedErrorLoggingEnabledElement.getTextContent().toLowerCase()); + result.setDetailedErrorLoggingEnabled(detailedErrorLoggingEnabledInstance); + } + + Element documentRootElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "DocumentRoot"); + if (documentRootElement != null) { + String documentRootInstance; + documentRootInstance = documentRootElement.getTextContent(); + result.setDocumentRoot(documentRootInstance); + } + + Element handlerMappingsSequenceElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "HandlerMappings"); + if (handlerMappingsSequenceElement != null) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(handlerMappingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "HandlerMapping").size(); i4 = i4 + 1) { + org.w3c.dom.Element handlerMappingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(handlerMappingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "HandlerMapping").get(i4)); + WebSiteGetConfigurationResponse.HandlerMapping handlerMappingInstance = new WebSiteGetConfigurationResponse.HandlerMapping(); + result.getHandlerMappings().add(handlerMappingInstance); + + Element argumentsElement = XmlUtility.getElementByTagNameNS(handlerMappingsElement, "http://schemas.microsoft.com/windowsazure", "Arguments"); + if (argumentsElement != null) { + String argumentsInstance; + argumentsInstance = argumentsElement.getTextContent(); + handlerMappingInstance.setArguments(argumentsInstance); + } + + Element extensionElement = XmlUtility.getElementByTagNameNS(handlerMappingsElement, "http://schemas.microsoft.com/windowsazure", "Extension"); + if (extensionElement != null) { + String extensionInstance; + extensionInstance = extensionElement.getTextContent(); + handlerMappingInstance.setExtension(extensionInstance); + } + + Element scriptProcessorElement = XmlUtility.getElementByTagNameNS(handlerMappingsElement, "http://schemas.microsoft.com/windowsazure", "ScriptProcessor"); + if (scriptProcessorElement != null) { + String scriptProcessorInstance; + scriptProcessorInstance = scriptProcessorElement.getTextContent(); + handlerMappingInstance.setScriptProcessor(scriptProcessorInstance); + } + } + } + + Element httpLoggingEnabledElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "HttpLoggingEnabled"); + if (httpLoggingEnabledElement != null && (httpLoggingEnabledElement.getTextContent() == null || httpLoggingEnabledElement.getTextContent().isEmpty() == true) == false) { + boolean httpLoggingEnabledInstance; + httpLoggingEnabledInstance = DatatypeConverter.parseBoolean(httpLoggingEnabledElement.getTextContent().toLowerCase()); + result.setHttpLoggingEnabled(httpLoggingEnabledInstance); + } + + Element logsDirectorySizeLimitElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "LogsDirectorySizeLimit"); + if (logsDirectorySizeLimitElement != null && (logsDirectorySizeLimitElement.getTextContent() == null || logsDirectorySizeLimitElement.getTextContent().isEmpty() == true) == false) { + int logsDirectorySizeLimitInstance; + logsDirectorySizeLimitInstance = DatatypeConverter.parseInt(logsDirectorySizeLimitElement.getTextContent()); + result.setLogsDirectorySizeLimit(logsDirectorySizeLimitInstance); + } + + Element managedPipelineModeElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "ManagedPipelineMode"); + if (managedPipelineModeElement != null && (managedPipelineModeElement.getTextContent() == null || managedPipelineModeElement.getTextContent().isEmpty() == true) == false) { + ManagedPipelineMode managedPipelineModeInstance; + managedPipelineModeInstance = ManagedPipelineMode.valueOf(managedPipelineModeElement.getTextContent()); + result.setManagedPipelineMode(managedPipelineModeInstance); + } + + Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "Metadata"); + if (metadataSequenceElement != null) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i5 = i5 + 1) { + org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i5)); + String metadataKey = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String metadataValue = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + result.getMetadata().put(metadataKey, metadataValue); + } + } + + Element netFrameworkVersionElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "NetFrameworkVersion"); + if (netFrameworkVersionElement != null) { + String netFrameworkVersionInstance; + netFrameworkVersionInstance = netFrameworkVersionElement.getTextContent(); + result.setNetFrameworkVersion(netFrameworkVersionInstance); + } + + Element numberOfWorkersElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + if (numberOfWorkersElement != null && (numberOfWorkersElement.getTextContent() == null || numberOfWorkersElement.getTextContent().isEmpty() == true) == false) { + int numberOfWorkersInstance; + numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement.getTextContent()); + result.setNumberOfWorkers(numberOfWorkersInstance); + } + + Element phpVersionElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "PhpVersion"); + if (phpVersionElement != null) { + String phpVersionInstance; + phpVersionInstance = phpVersionElement.getTextContent(); + result.setPhpVersion(phpVersionInstance); + } + + Element publishingPasswordElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "PublishingPassword"); + if (publishingPasswordElement != null) { + String publishingPasswordInstance; + publishingPasswordInstance = publishingPasswordElement.getTextContent(); + result.setPublishingPassword(publishingPasswordInstance); + } + + Element publishingUsernameElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "PublishingUsername"); + if (publishingUsernameElement != null) { + String publishingUsernameInstance; + publishingUsernameInstance = publishingUsernameElement.getTextContent(); + result.setPublishingUserName(publishingUsernameInstance); + } + + Element remoteDebuggingEnabledElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "RemoteDebuggingEnabled"); + if (remoteDebuggingEnabledElement != null && (remoteDebuggingEnabledElement.getTextContent() == null || remoteDebuggingEnabledElement.getTextContent().isEmpty() == true) == false) { + boolean remoteDebuggingEnabledInstance; + remoteDebuggingEnabledInstance = DatatypeConverter.parseBoolean(remoteDebuggingEnabledElement.getTextContent().toLowerCase()); + result.setRemoteDebuggingEnabled(remoteDebuggingEnabledInstance); + } + + Element remoteDebuggingVersionElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "RemoteDebuggingVersion"); + if (remoteDebuggingVersionElement != null) { + boolean isNil = false; + Attr nilAttribute = remoteDebuggingVersionElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + RemoteDebuggingVersion remoteDebuggingVersionInstance; + remoteDebuggingVersionInstance = RemoteDebuggingVersion.valueOf(remoteDebuggingVersionElement.getTextContent()); + result.setRemoteDebuggingVersion(remoteDebuggingVersionInstance); + } + } + + Element requestTracingEnabledElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "RequestTracingEnabled"); + if (requestTracingEnabledElement != null && (requestTracingEnabledElement.getTextContent() == null || requestTracingEnabledElement.getTextContent().isEmpty() == true) == false) { + boolean requestTracingEnabledInstance; + requestTracingEnabledInstance = DatatypeConverter.parseBoolean(requestTracingEnabledElement.getTextContent().toLowerCase()); + result.setRequestTracingEnabled(requestTracingEnabledInstance); + } + + Element requestTracingExpirationTimeElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "RequestTracingExpirationTime"); + if (requestTracingExpirationTimeElement != null && (requestTracingExpirationTimeElement.getTextContent() == null || requestTracingExpirationTimeElement.getTextContent().isEmpty() == true) == false) { + boolean isNil2 = false; + Attr nilAttribute2 = requestTracingExpirationTimeElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + Calendar requestTracingExpirationTimeInstance; + requestTracingExpirationTimeInstance = DatatypeConverter.parseDateTime(requestTracingExpirationTimeElement.getTextContent()); + result.setRequestTracingExpirationTime(requestTracingExpirationTimeInstance); + } + } + + Element scmTypeElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "ScmType"); + if (scmTypeElement != null) { + String scmTypeInstance; + scmTypeInstance = scmTypeElement.getTextContent(); + result.setScmType(scmTypeInstance); + } + + Element use32BitWorkerProcessElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "Use32BitWorkerProcess"); + if (use32BitWorkerProcessElement != null && (use32BitWorkerProcessElement.getTextContent() == null || use32BitWorkerProcessElement.getTextContent().isEmpty() == true) == false) { + boolean use32BitWorkerProcessInstance; + use32BitWorkerProcessInstance = DatatypeConverter.parseBoolean(use32BitWorkerProcessElement.getTextContent().toLowerCase()); + result.setUse32BitWorkerProcess(use32BitWorkerProcessInstance); + } + + Element webSocketsEnabledElement = XmlUtility.getElementByTagNameNS(siteConfigElement, "http://schemas.microsoft.com/windowsazure", "WebSocketsEnabled"); + if (webSocketsEnabledElement != null && (webSocketsEnabledElement.getTextContent() == null || webSocketsEnabledElement.getTextContent().isEmpty() == true) == false) { + boolean webSocketsEnabledInstance; + webSocketsEnabledInstance = DatatypeConverter.parseBoolean(webSocketsEnabledElement.getTextContent().toLowerCase()); + result.setWebSocketsEnabled(webSocketsEnabledInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve historical usage metrics for a site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Get Historical + * Usage Metrics Web Site operation. + * @return The Get Historical Usage Metrics Web Site operation response. + */ + @Override + public Future getHistoricalUsageMetricsAsync(final String webSpaceName, final String webSiteName, final WebSiteGetHistoricalUsageMetricsParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteGetHistoricalUsageMetricsResponse call() throws Exception { + return getHistoricalUsageMetrics(webSpaceName, webSiteName, parameters); + } + }); + } + + /** + * You can retrieve historical usage metrics for a site by issuing an HTTP + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Get Historical + * Usage Metrics Web Site operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Historical Usage Metrics Web Site operation response. + */ + @Override + public WebSiteGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName, String webSiteName, WebSiteGetHistoricalUsageMetricsParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "getHistoricalUsageMetricsAsync", tracingParameters); + } + + // Construct URL + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/metrics" + "?"; + if (parameters.getMetricNames() != null && parameters.getMetricNames().size() > 0) { + url = url + "&" + "names=" + URLEncoder.encode(CommaStringBuilder.join(parameters.getMetricNames()), "UTF-8"); + } + if (parameters.getStartTime() != null) { + url = url + "&" + "StartTime=" + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"); + } + if (parameters.getEndTime() != null) { + url = url + "&" + "EndTime=" + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"); + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteGetHistoricalUsageMetricsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteGetHistoricalUsageMetricsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element metricResponsesElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "MetricResponses"); + if (metricResponsesElement != null) { + if (metricResponsesElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metricResponsesElement, "http://schemas.microsoft.com/windowsazure", "MetricResponse").size(); i1 = i1 + 1) { + org.w3c.dom.Element usageMetricsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metricResponsesElement, "http://schemas.microsoft.com/windowsazure", "MetricResponse").get(i1)); + WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetric metricResponseInstance = new WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetric(); + result.getUsageMetrics().add(metricResponseInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + metricResponseInstance.setCode(codeInstance); + } + + Element dataElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "Data"); + if (dataElement != null) { + WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricData dataInstance = new WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricData(); + metricResponseInstance.setData(dataInstance); + + Element displayNameElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "DisplayName"); + if (displayNameElement != null) { + String displayNameInstance; + displayNameInstance = displayNameElement.getTextContent(); + dataInstance.setDisplayName(displayNameInstance); + } + + Element endTimeElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "EndTime"); + if (endTimeElement != null) { + Calendar endTimeInstance; + endTimeInstance = DatatypeConverter.parseDateTime(endTimeElement.getTextContent()); + dataInstance.setEndTime(endTimeInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + dataInstance.setName(nameInstance); + } + + Element primaryAggregationTypeElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "PrimaryAggregationType"); + if (primaryAggregationTypeElement != null) { + String primaryAggregationTypeInstance; + primaryAggregationTypeInstance = primaryAggregationTypeElement.getTextContent(); + dataInstance.setPrimaryAggregationType(primaryAggregationTypeInstance); + } + + Element startTimeElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); + if (startTimeElement != null) { + Calendar startTimeInstance; + startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); + dataInstance.setStartTime(startTimeInstance); + } + + Element timeGrainElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "TimeGrain"); + if (timeGrainElement != null) { + String timeGrainInstance; + timeGrainInstance = timeGrainElement.getTextContent(); + dataInstance.setTimeGrain(timeGrainInstance); + } + + Element unitElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "Unit"); + if (unitElement != null) { + String unitInstance; + unitInstance = unitElement.getTextContent(); + dataInstance.setUnit(unitInstance); + } + + Element valuesSequenceElement = XmlUtility.getElementByTagNameNS(dataElement, "http://schemas.microsoft.com/windowsazure", "Values"); + if (valuesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(valuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "MetricSample").size(); i2 = i2 + 1) { + org.w3c.dom.Element valuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(valuesSequenceElement, "http://schemas.microsoft.com/windowsazure", "MetricSample").get(i2)); + WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricSample metricSampleInstance = new WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricSample(); + dataInstance.getValues().add(metricSampleInstance); + + Element countElement = XmlUtility.getElementByTagNameNS(valuesElement, "http://schemas.microsoft.com/windowsazure", "Count"); + if (countElement != null) { + int countInstance; + countInstance = DatatypeConverter.parseInt(countElement.getTextContent()); + metricSampleInstance.setCount(countInstance); + } + + Element maximumElement = XmlUtility.getElementByTagNameNS(valuesElement, "http://schemas.microsoft.com/windowsazure", "Maximum"); + if (maximumElement != null) { + boolean isNil = false; + Attr nilAttribute = maximumElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String maximumInstance; + maximumInstance = maximumElement.getTextContent(); + metricSampleInstance.setMaximum(maximumInstance); + } + } + + Element minimumElement = XmlUtility.getElementByTagNameNS(valuesElement, "http://schemas.microsoft.com/windowsazure", "Minimum"); + if (minimumElement != null) { + boolean isNil2 = false; + Attr nilAttribute2 = minimumElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + String minimumInstance; + minimumInstance = minimumElement.getTextContent(); + metricSampleInstance.setMinimum(minimumInstance); + } + } + + Element timeCreatedElement = XmlUtility.getElementByTagNameNS(valuesElement, "http://schemas.microsoft.com/windowsazure", "TimeCreated"); + if (timeCreatedElement != null) { + Calendar timeCreatedInstance; + timeCreatedInstance = DatatypeConverter.parseDateTime(timeCreatedElement.getTextContent()); + metricSampleInstance.setTimeCreated(timeCreatedInstance); + } + + Element totalElement = XmlUtility.getElementByTagNameNS(valuesElement, "http://schemas.microsoft.com/windowsazure", "Total"); + if (totalElement != null) { + String totalInstance; + totalInstance = totalElement.getTextContent(); + metricSampleInstance.setTotal(totalInstance); + } + } + } + } + + Element messageElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + metricResponseInstance.setMessage(messageInstance); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve the list of active instances by ids for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The web site instance ids reponse. + */ + @Override + public Future getInstanceIdsAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteInstanceIdsResponse call() throws Exception { + return getInstanceIds(webSpaceName, webSiteName); + } + }); + } + + /** + * You can retrieve the list of active instances by ids for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The web site instance ids reponse. + */ + @Override + public WebSiteInstanceIdsResponse getInstanceIds(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "getInstanceIdsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/instanceids"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteInstanceIdsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteInstanceIdsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element arrayOfstringSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "ArrayOfstring"); + if (arrayOfstringSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(arrayOfstringSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i1 = i1 + 1) { + org.w3c.dom.Element arrayOfstringElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(arrayOfstringSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i1)); + result.getInstanceIds().add(arrayOfstringElement.getTextContent()); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve the publish settings information for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166996.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Publish Profile Web Site operation response. + */ + @Override + public Future getPublishProfileAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteGetPublishProfileResponse call() throws Exception { + return getPublishProfile(webSpaceName, webSiteName); + } + }); + } + + /** + * You can retrieve the publish settings information for a web site by + * issuing an HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166996.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Publish Profile Web Site operation response. + */ + @Override + public WebSiteGetPublishProfileResponse getPublishProfile(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "getPublishProfileAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/publishxml"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteGetPublishProfileResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteGetPublishProfileResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element publishDataElement = XmlUtility.getElementByTagNameNS(responseDoc, "", "publishData"); + if (publishDataElement != null) { + if (publishDataElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publishDataElement, "", "publishProfile").size(); i1 = i1 + 1) { + org.w3c.dom.Element publishProfilesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(publishDataElement, "", "publishProfile").get(i1)); + WebSiteGetPublishProfileResponse.PublishProfile publishProfileInstance = new WebSiteGetPublishProfileResponse.PublishProfile(); + result.getPublishProfiles().add(publishProfileInstance); + + Attr profileNameAttribute = publishProfilesElement.getAttributeNodeNS("", "profileName"); + if (profileNameAttribute != null) { + publishProfileInstance.setProfileName(profileNameAttribute.getValue()); + } + + Attr publishMethodAttribute = publishProfilesElement.getAttributeNodeNS("", "publishMethod"); + if (publishMethodAttribute != null) { + publishProfileInstance.setPublishMethod(publishMethodAttribute.getValue()); + } + + Attr publishUrlAttribute = publishProfilesElement.getAttributeNodeNS("", "publishUrl"); + if (publishUrlAttribute != null) { + publishProfileInstance.setPublishUrl(publishUrlAttribute.getValue()); + } + + Attr msdeploySiteAttribute = publishProfilesElement.getAttributeNodeNS("", "msdeploySite"); + if (msdeploySiteAttribute != null) { + publishProfileInstance.setMSDeploySite(msdeploySiteAttribute.getValue()); + } + + Attr ftpPassiveModeAttribute = publishProfilesElement.getAttributeNodeNS("", "ftpPassiveMode"); + if (ftpPassiveModeAttribute != null) { + publishProfileInstance.setFtpPassiveMode(DatatypeConverter.parseBoolean(ftpPassiveModeAttribute.getValue().toLowerCase())); + } + + Attr userNameAttribute = publishProfilesElement.getAttributeNodeNS("", "userName"); + if (userNameAttribute != null) { + publishProfileInstance.setUserName(userNameAttribute.getValue()); + } + + Attr userPWDAttribute = publishProfilesElement.getAttributeNodeNS("", "userPWD"); + if (userPWDAttribute != null) { + publishProfileInstance.setUserPassword(userPWDAttribute.getValue()); + } + + Attr destinationAppUrlAttribute = publishProfilesElement.getAttributeNodeNS("", "destinationAppUrl"); + if (destinationAppUrlAttribute != null) { + publishProfileInstance.setDestinationAppUri(new URI(destinationAppUrlAttribute.getValue())); + } + + Attr sQLServerDBConnectionStringAttribute = publishProfilesElement.getAttributeNodeNS("", "SQLServerDBConnectionString"); + if (sQLServerDBConnectionStringAttribute != null) { + publishProfileInstance.setSqlServerConnectionString(sQLServerDBConnectionStringAttribute.getValue()); + } + + Attr mySQLDBConnectionStringAttribute = publishProfilesElement.getAttributeNodeNS("", "mySQLDBConnectionString"); + if (mySQLDBConnectionStringAttribute != null) { + publishProfileInstance.setMySqlConnectionString(mySQLDBConnectionStringAttribute.getValue()); + } + + Attr hostingProviderForumLinkAttribute = publishProfilesElement.getAttributeNodeNS("", "hostingProviderForumLink"); + if (hostingProviderForumLinkAttribute != null) { + publishProfileInstance.setHostingProviderForumUri(new URI(hostingProviderForumLinkAttribute.getValue())); + } + + Attr controlPanelLinkAttribute = publishProfilesElement.getAttributeNodeNS("", "controlPanelLink"); + if (controlPanelLinkAttribute != null) { + publishProfileInstance.setControlPanelUri(new URI(controlPanelLinkAttribute.getValue())); + } + + Element databasesSequenceElement = XmlUtility.getElementByTagNameNS(publishProfilesElement, "", "databases"); + if (databasesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(databasesSequenceElement, "", "add").size(); i2 = i2 + 1) { + org.w3c.dom.Element databasesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(databasesSequenceElement, "", "add").get(i2)); + WebSiteGetPublishProfileResponse.Database addInstance = new WebSiteGetPublishProfileResponse.Database(); + publishProfileInstance.getDatabases().add(addInstance); + + Attr nameAttribute = databasesElement.getAttributeNodeNS("", "name"); + if (nameAttribute != null) { + addInstance.setName(nameAttribute.getValue()); + } + + Attr connectionStringAttribute = databasesElement.getAttributeNodeNS("", "connectionString"); + if (connectionStringAttribute != null) { + addInstance.setConnectionString(connectionStringAttribute.getValue()); + } + + Attr providerNameAttribute = databasesElement.getAttributeNodeNS("", "providerName"); + if (providerNameAttribute != null) { + addInstance.setProviderName(providerNameAttribute.getValue()); + } + + Attr typeAttribute = databasesElement.getAttributeNodeNS("", "type"); + if (typeAttribute != null) { + addInstance.setType(typeAttribute.getValue()); + } + } + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository get operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Repository Web Site operation response. + */ + @Override + public Future getRepositoryAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteGetRepositoryResponse call() throws Exception { + return getRepository(webSpaceName, webSiteName); + } + }); + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository get operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Repository Web Site operation response. + */ + @Override + public WebSiteGetRepositoryResponse getRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "getRepositoryAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/repository"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteGetRepositoryResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteGetRepositoryResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element anyURIElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "anyURI"); + if (anyURIElement != null) { + result.setUri(new URI(anyURIElement.getTextContent())); + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve current usage metrics for a site by issuing an HTTP GET + * request. The metrics returned include CPU Time, Data In, Data Out, Local + * Bytes Read, Local Bytes Written, Network Bytes Read, Network Bytes + * Written, WP Stop Requests, Memory Usage, CPU Time - Minute Limit, and + * File System Storage. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166991.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return The Get Usage Metrics Web Site operation response. + */ + @Override + public Future getUsageMetricsAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteGetUsageMetricsResponse call() throws Exception { + return getUsageMetrics(webSpaceName, webSiteName); + } + }); + } + + /** + * You can retrieve current usage metrics for a site by issuing an HTTP GET + * request. The metrics returned include CPU Time, Data In, Data Out, Local + * Bytes Read, Local Bytes Written, Network Bytes Read, Network Bytes + * Written, WP Stop Requests, Memory Usage, CPU Time - Minute Limit, and + * File System Storage. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166991.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get Usage Metrics Web Site operation response. + */ + @Override + public WebSiteGetUsageMetricsResponse getUsageMetrics(String webSpaceName, String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "getUsageMetricsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/usages"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteGetUsageMetricsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteGetUsageMetricsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element usagesElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Usages"); + if (usagesElement != null) { + if (usagesElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(usagesElement, "http://schemas.microsoft.com/windowsazure", "Usage").size(); i1 = i1 + 1) { + org.w3c.dom.Element usageMetricsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(usagesElement, "http://schemas.microsoft.com/windowsazure", "Usage").get(i1)); + WebSiteGetUsageMetricsResponse.UsageMetric usageInstance = new WebSiteGetUsageMetricsResponse.UsageMetric(); + result.getUsageMetrics().add(usageInstance); + + Element computeModeElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "ComputeMode"); + if (computeModeElement != null) { + WebSiteComputeMode computeModeInstance; + computeModeInstance = WebSiteComputeMode.valueOf(computeModeElement.getTextContent()); + usageInstance.setComputeMode(computeModeInstance); + } + + Element currentValueElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "CurrentValue"); + if (currentValueElement != null) { + String currentValueInstance; + currentValueInstance = currentValueElement.getTextContent(); + usageInstance.setCurrentValue(currentValueInstance); + } + + Element displayNameElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "DisplayName"); + if (displayNameElement != null) { + String displayNameInstance; + displayNameInstance = displayNameElement.getTextContent(); + usageInstance.setDisplayName(displayNameInstance); + } + + Element limitElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "Limit"); + if (limitElement != null) { + String limitInstance; + limitInstance = limitElement.getTextContent(); + usageInstance.setLimit(limitInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + usageInstance.setName(nameInstance); + } + + Element nextResetTimeElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "NextResetTime"); + if (nextResetTimeElement != null) { + Calendar nextResetTimeInstance; + nextResetTimeInstance = DatatypeConverter.parseDateTime(nextResetTimeElement.getTextContent()); + usageInstance.setNextResetTime(nextResetTimeInstance); + } + + Element resourceNameElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "ResourceName"); + if (resourceNameElement != null) { + String resourceNameInstance; + resourceNameInstance = resourceNameElement.getTextContent(); + usageInstance.setResourceName(resourceNameInstance); + } + + Element siteModeElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "SiteMode"); + if (siteModeElement != null) { + WebSiteMode siteModeInstance; + siteModeInstance = WebSiteMode.valueOf(siteModeElement.getTextContent()); + usageInstance.setSiteMode(siteModeInstance); + } + + Element unitElement = XmlUtility.getElementByTagNameNS(usageMetricsElement, "http://schemas.microsoft.com/windowsazure", "Unit"); + if (unitElement != null) { + String unitInstance; + unitInstance = unitElement.getTextContent(); + usageInstance.setUnit(unitInstance); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Determines if a host name is available. + * + * @param webSiteName Required. The name of the web site. + * @return The Is Hostname Available Web Site operation response. + */ + @Override + public Future isHostnameAvailableAsync(final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteIsHostnameAvailableResponse call() throws Exception { + return isHostnameAvailable(webSiteName); + } + }); + } + + /** + * Determines if a host name is available. + * + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Is Hostname Available Web Site operation response. + */ + @Override + public WebSiteIsHostnameAvailableResponse isHostnameAvailable(String webSiteName) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "isHostnameAvailableAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces" + "?"; + url = url + "ishostnameavailable=" + URLEncoder.encode(webSiteName.trim(), "UTF-8"); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteIsHostnameAvailableResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteIsHostnameAvailableResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element booleanElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "boolean"); + if (booleanElement != null) { + boolean booleanInstance; + booleanInstance = DatatypeConverter.parseBoolean(booleanElement.getTextContent().toLowerCase()); + result.setIsAvailable(booleanInstance); + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can restart a web site by issuing an HTTP POST request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236425.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future restartAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return restart(webSpaceName, webSiteName); + } + }); + } + + /** + * You can restart a web site by issuing an HTTP POST request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236425.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse restart(String webSpaceName, String webSiteName) throws IOException, ServiceException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "restartAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/restart"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + @Override + public Future swapSlotsAsync(final String webSpaceName, final String webSiteName, final String sourceSlotName, final String targetSlotName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteOperationStatusResponse call() throws Exception { + return swapSlots(webSpaceName, webSiteName, sourceSlotName, targetSlotName); + } + }); + } + + /** + * You can swap a web site from one slot to another slot. + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param sourceSlotName Required. The name of the first web site slot to + * swap (source). + * @param targetSlotName Required. The name of the second web site slot to + * swap with (target). + * @throws InterruptedException Thrown when a thread is waiting, sleeping, + * or otherwise occupied, and the thread is interrupted, either before or + * during the activity. Occasionally a method may wish to test whether the + * current thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve this effect: + * @throws ExecutionException Thrown when attempting to retrieve the result + * of a task that aborted by throwing an exception. This exception can be + * inspected using the Throwable.getCause() method. + * @throws ServiceException Thrown if the server returned an error for the + * request. + * @throws IOException Thrown if there was an error setting up tracing for + * the request. + * @return The response body contains the status of the specified + * long-running operation, indicating whether it has succeeded, is + * inprogress, has timed out, or has failed. Note that this status is + * distinct from the HTTP status code returned for the Get Operation Status + * operation itself. If the long-running operation failed, the response + * body includes error information regarding the failure. + */ + @Override + public WebSiteOperationStatusResponse swapSlots(String webSpaceName, String webSiteName, String sourceSlotName, String targetSlotName) throws InterruptedException, ExecutionException, ServiceException, IOException { + WebSiteManagementClient client2 = this.getClient(); + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + tracingParameters.put("sourceSlotName", sourceSlotName); + tracingParameters.put("targetSlotName", targetSlotName); + CloudTracing.enter(invocationId, this, "swapSlotsAsync", tracingParameters); + } + try { + if (shouldTrace) { + client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId)).withResponseFilterLast(new ClientRequestTrackingHandler(invocationId)); + } + + WebSiteOperationStatusResponse response = client2.getWebSitesOperations().beginSwapingSlotsAsync(webSpaceName, webSiteName, sourceSlotName, targetSlotName).get(); + if (response.getStatus() == WebSiteOperationStatus.Succeeded) { + return response; + } + WebSiteOperationStatusResponse result = client2.getOperationStatusAsync(webSpaceName, webSiteName, response.getOperationId()).get(); + int delayInSeconds = 30; + while ((result.getStatus() != WebSiteOperationStatus.InProgress) == false) { + Thread.sleep(delayInSeconds * 1000); + result = client2.getOperationStatusAsync(webSpaceName, webSiteName, response.getOperationId()).get(); + delayInSeconds = 30; + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + + if (result.getStatus() != WebSiteOperationStatus.Succeeded) { + if (result.getErrors() != null && result.getErrors().size() > 0) { + ServiceException ex = new ServiceException(result.getErrors().get(0).getCode() + " : " + result.getErrors().get(0).getMessage()); + ex.setErrorCode(result.getErrors().get(0).getCode()); + ex.setErrorMessage(result.getErrors().get(0).getMessage()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } else { + ServiceException ex = new ServiceException(""); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + } + + return result; + } finally { + if (client2 != null && shouldTrace) { + client2.close(); + } + } + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository sync operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future syncRepositoryAsync(final String webSpaceName, final String webSiteName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return syncRepository(webSpaceName, webSiteName); + } + }); + } + + /** + * A web site repository is essentially a Git repository that you can use to + * manage your web site content. By using Git source control tools, you can + * push or pull version-controlled changes to your site. This API executes + * a repository sync operation. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166967.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse syncRepository(String webSpaceName, String webSiteName) throws IOException, ServiceException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + CloudTracing.enter(invocationId, this, "syncRepositoryAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/repository" + "?" + "action=sync"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can update the settings for a web site by using the HTTP PUT method + * and by specifying the settings in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167005.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update Web Site + * operation. + * @return The Update Web Site operation response. + */ + @Override + public Future updateAsync(final String webSpaceName, final String webSiteName, final WebSiteUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSiteUpdateResponse call() throws Exception { + return update(webSpaceName, webSiteName, parameters); + } + }); + } + + /** + * You can update the settings for a web site by using the HTTP PUT method + * and by specifying the settings in the request body. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167005.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update Web Site + * operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Update Web Site operation response. + */ + @Override + public WebSiteUpdateResponse update(String webSpaceName, String webSiteName, WebSiteUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element siteElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Site"); + requestDoc.appendChild(siteElement); + + if (parameters.getAvailabilityState() != null) { + Element availabilityStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AvailabilityState"); + availabilityStateElement.appendChild(requestDoc.createTextNode(parameters.getAvailabilityState().toString())); + siteElement.appendChild(availabilityStateElement); + } + + if (parameters.getComputeMode() != null) { + Element computeModeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ComputeMode"); + computeModeElement.appendChild(requestDoc.createTextNode(parameters.getComputeMode().toString())); + siteElement.appendChild(computeModeElement); + } + + if (parameters.isEnabled() != null) { + Element enabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Enabled"); + enabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isEnabled()).toLowerCase())); + siteElement.appendChild(enabledElement); + } + + if (parameters.getHostNameSslStates() != null) { + Element hostNameSslStatesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostNameSslStates"); + for (WebSiteUpdateParameters.WebSiteHostNameSslState hostNameSslStatesItem : parameters.getHostNameSslStates()) { + Element webSiteHostNameSslStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState"); + hostNameSslStatesSequenceElement.appendChild(webSiteHostNameSslStateElement); + + if (hostNameSslStatesItem.getSslState() != null) { + Element sslStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SslState"); + sslStateElement.appendChild(requestDoc.createTextNode(hostNameSslStatesItem.getSslState().toString())); + webSiteHostNameSslStateElement.appendChild(sslStateElement); + } + + if (hostNameSslStatesItem.getThumbprint() != null) { + Element thumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + thumbprintElement.appendChild(requestDoc.createTextNode(hostNameSslStatesItem.getThumbprint())); + webSiteHostNameSslStateElement.appendChild(thumbprintElement); + } else { + Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + nilAttribute.setValue("true"); + emptyElement.setAttributeNode(nilAttribute); + webSiteHostNameSslStateElement.appendChild(emptyElement); + } + + if (hostNameSslStatesItem.isToUpdate() != null) { + Element toUpdateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ToUpdate"); + toUpdateElement.appendChild(requestDoc.createTextNode(Boolean.toString(hostNameSslStatesItem.isToUpdate()).toLowerCase())); + webSiteHostNameSslStateElement.appendChild(toUpdateElement); + } + } + siteElement.appendChild(hostNameSslStatesSequenceElement); + } + + if (parameters.getHostNames() != null) { + Element hostNamesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HostNames"); + for (String hostNamesItem : parameters.getHostNames()) { + Element hostNamesItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string"); + hostNamesItemElement.appendChild(requestDoc.createTextNode(hostNamesItem)); + hostNamesSequenceElement.appendChild(hostNamesItemElement); + } + siteElement.appendChild(hostNamesSequenceElement); + } + + if (parameters.getRuntimeAvailabilityState() != null) { + Element runtimeAvailabilityStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState"); + runtimeAvailabilityStateElement.appendChild(requestDoc.createTextNode(parameters.getRuntimeAvailabilityState().toString())); + siteElement.appendChild(runtimeAvailabilityStateElement); + } + + if (parameters.getSslCertificates() != null) { + Element sSLCertificatesSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SSLCertificates"); + for (WebSiteUpdateParameters.WebSiteSslCertificate sSLCertificatesItem : parameters.getSslCertificates()) { + Element certificateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Certificate"); + sSLCertificatesSequenceElement.appendChild(certificateElement); + + if (sSLCertificatesItem.getPassword() != null) { + Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Password"); + passwordElement.appendChild(requestDoc.createTextNode(sSLCertificatesItem.getPassword())); + certificateElement.appendChild(passwordElement); + } + + if (sSLCertificatesItem.getPfxBlob() != null) { + Element pfxBlobElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PfxBlob"); + pfxBlobElement.appendChild(requestDoc.createTextNode(Base64.encode(sSLCertificatesItem.getPfxBlob()))); + certificateElement.appendChild(pfxBlobElement); + } + + if (sSLCertificatesItem.getThumbprint() != null) { + Element thumbprintElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); + thumbprintElement2.appendChild(requestDoc.createTextNode(sSLCertificatesItem.getThumbprint())); + certificateElement.appendChild(thumbprintElement2); + } + + if (sSLCertificatesItem.isToBeDeleted() != null) { + Element toDeleteElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ToDelete"); + toDeleteElement.appendChild(requestDoc.createTextNode(Boolean.toString(sSLCertificatesItem.isToBeDeleted()).toLowerCase())); + certificateElement.appendChild(toDeleteElement); + } + } + siteElement.appendChild(sSLCertificatesSequenceElement); + } + + if (parameters.getServerFarm() != null) { + Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServerFarm"); + serverFarmElement.appendChild(requestDoc.createTextNode(parameters.getServerFarm())); + siteElement.appendChild(serverFarmElement); + } + + if (parameters.getSiteMode() != null) { + Element siteModeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SiteMode"); + siteModeElement.appendChild(requestDoc.createTextNode(parameters.getSiteMode().toString())); + siteElement.appendChild(siteModeElement); + } + + if (parameters.getState() != null) { + Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State"); + stateElement.appendChild(requestDoc.createTextNode(parameters.getState())); + siteElement.appendChild(stateElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSiteUpdateResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSiteUpdateResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element siteElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Site"); + if (siteElement2 != null) { + WebSite webSiteInstance = new WebSite(); + result.setWebSite(webSiteInstance); + + Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "AdminEnabled"); + if (adminEnabledElement != null) { + boolean adminEnabledInstance; + adminEnabledInstance = DatatypeConverter.parseBoolean(adminEnabledElement.getTextContent().toLowerCase()); + webSiteInstance.setAdminEnabled(adminEnabledInstance); + } + + Element availabilityStateElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "AvailabilityState"); + if (availabilityStateElement2 != null) { + WebSpaceAvailabilityState availabilityStateInstance; + availabilityStateInstance = WebSpaceAvailabilityState.valueOf(availabilityStateElement2.getTextContent()); + webSiteInstance.setAvailabilityState(availabilityStateInstance); + } + + Element computeModeElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "ComputeMode"); + if (computeModeElement2 != null) { + WebSiteComputeMode computeModeInstance; + computeModeInstance = WebSiteComputeMode.valueOf(computeModeElement2.getTextContent()); + webSiteInstance.setComputeMode(computeModeInstance); + } + + Element enabledElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "Enabled"); + if (enabledElement2 != null) { + boolean enabledInstance; + enabledInstance = DatatypeConverter.parseBoolean(enabledElement2.getTextContent().toLowerCase()); + webSiteInstance.setEnabled(enabledInstance); + } + + Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "EnabledHostNames"); + if (enabledHostNamesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i1 = i1 + 1) { + org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i1)); + webSiteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent()); + } + } + + Element hostNameSslStatesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "HostNameSslStates"); + if (hostNameSslStatesSequenceElement2 != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").size(); i2 = i2 + 1) { + org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").get(i2)); + WebSite.WebSiteHostNameSslState webSiteHostNameSslStateInstance = new WebSite.WebSiteHostNameSslState(); + webSiteInstance.getHostNameSslStates().add(webSiteHostNameSslStateInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + webSiteHostNameSslStateInstance.setName(nameInstance); + } + + Element sslStateElement2 = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "SslState"); + if (sslStateElement2 != null) { + WebSiteSslState sslStateInstance; + sslStateInstance = WebSiteSslState.valueOf(sslStateElement2.getTextContent()); + webSiteHostNameSslStateInstance.setSslState(sslStateInstance); + } + + Element thumbprintElement3 = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement3 != null) { + boolean isNil = false; + Attr nilAttribute2 = thumbprintElement3.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil = "true".equals(nilAttribute2.getValue()); + } + if (isNil == false) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement3.getTextContent(); + webSiteHostNameSslStateInstance.setThumbprint(thumbprintInstance); + } + } + + Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP"); + if (virtualIPElement != null) { + boolean isNil2 = false; + Attr nilAttribute3 = virtualIPElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute3 != null) { + isNil2 = "true".equals(nilAttribute3.getValue()); + } + if (isNil2 == false) { + InetAddress virtualIPInstance; + virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent()); + webSiteHostNameSslStateInstance.setVirtualIP(virtualIPInstance); + } + } + } + } + + Element hostNamesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement2 != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i3 = i3 + 1) { + org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i3)); + webSiteInstance.getHostNames().add(hostNamesElement.getTextContent()); + } + } + + Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc"); + if (lastModifiedTimeUtcElement != null) { + Calendar lastModifiedTimeUtcInstance; + lastModifiedTimeUtcInstance = DatatypeConverter.parseDateTime(lastModifiedTimeUtcElement.getTextContent()); + webSiteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + webSiteInstance.setName(nameInstance2); + } + + Element ownerElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "Owner"); + if (ownerElement != null) { + boolean isNil3 = false; + Attr nilAttribute4 = ownerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute4 != null) { + isNil3 = "true".equals(nilAttribute4.getValue()); + } + if (isNil3 == false) { + String ownerInstance; + ownerInstance = ownerElement.getTextContent(); + webSiteInstance.setOwner(ownerInstance); + } + } + + Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "RepositorySiteName"); + if (repositorySiteNameElement != null) { + String repositorySiteNameInstance; + repositorySiteNameInstance = repositorySiteNameElement.getTextContent(); + webSiteInstance.setRepositorySiteName(repositorySiteNameInstance); + } + + Element runtimeAvailabilityStateElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState"); + if (runtimeAvailabilityStateElement2 != null) { + WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance; + runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState.valueOf(runtimeAvailabilityStateElement2.getTextContent()); + webSiteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance); + } + + Element sSLCertificatesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SSLCertificates"); + if (sSLCertificatesSequenceElement2 != null) { + boolean isNil4 = false; + Attr nilAttribute5 = sSLCertificatesSequenceElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute5 != null) { + isNil4 = "true".equals(nilAttribute5.getValue()); + } + if (isNil4 == false) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Certificate").size(); i4 = i4 + 1) { + org.w3c.dom.Element sSLCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "Certificate").get(i4)); + WebSite.WebSiteSslCertificate certificateInstance = new WebSite.WebSiteSslCertificate(); + webSiteInstance.getSslCertificates().add(certificateInstance); + + Element expirationDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ExpirationDate"); + if (expirationDateElement != null && (expirationDateElement.getTextContent() == null || expirationDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil5 = false; + Attr nilAttribute6 = expirationDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute6 != null) { + isNil5 = "true".equals(nilAttribute6.getValue()); + } + if (isNil5 == false) { + Calendar expirationDateInstance; + expirationDateInstance = DatatypeConverter.parseDateTime(expirationDateElement.getTextContent()); + certificateInstance.setExpirationDate(expirationDateInstance); + } + } + + Element friendlyNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "FriendlyName"); + if (friendlyNameElement != null) { + boolean isNil6 = false; + Attr nilAttribute7 = friendlyNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute7 != null) { + isNil6 = "true".equals(nilAttribute7.getValue()); + } + if (isNil6 == false) { + String friendlyNameInstance; + friendlyNameInstance = friendlyNameElement.getTextContent(); + certificateInstance.setFriendlyName(friendlyNameInstance); + } + } + + Element hostNamesSequenceElement3 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement3 != null) { + boolean isNil7 = false; + Attr nilAttribute8 = hostNamesSequenceElement3.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute8 != null) { + isNil7 = "true".equals(nilAttribute8.getValue()); + } + if (isNil7 == false) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement3, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i5 = i5 + 1) { + org.w3c.dom.Element hostNamesElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement3, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i5)); + certificateInstance.getHostNames().add(hostNamesElement2.getTextContent()); + } + } + } + + Element issueDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "IssueDate"); + if (issueDateElement != null && (issueDateElement.getTextContent() == null || issueDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil8 = false; + Attr nilAttribute9 = issueDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute9 != null) { + isNil8 = "true".equals(nilAttribute9.getValue()); + } + if (isNil8 == false) { + Calendar issueDateInstance; + issueDateInstance = DatatypeConverter.parseDateTime(issueDateElement.getTextContent()); + certificateInstance.setIssueDate(issueDateInstance); + } + } + + Element issuerElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Issuer"); + if (issuerElement != null) { + boolean isNil9 = false; + Attr nilAttribute10 = issuerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute10 != null) { + isNil9 = "true".equals(nilAttribute10.getValue()); + } + if (isNil9 == false) { + String issuerInstance; + issuerInstance = issuerElement.getTextContent(); + certificateInstance.setIssuer(issuerInstance); + } + } + + Element passwordElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement2 != null) { + boolean isNil10 = false; + Attr nilAttribute11 = passwordElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute11 != null) { + isNil10 = "true".equals(nilAttribute11.getValue()); + } + if (isNil10 == false) { + String passwordInstance; + passwordInstance = passwordElement2.getTextContent(); + certificateInstance.setPassword(passwordInstance); + } + } + + Element pfxBlobElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "PfxBlob"); + if (pfxBlobElement2 != null) { + boolean isNil11 = false; + Attr nilAttribute12 = pfxBlobElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute12 != null) { + isNil11 = "true".equals(nilAttribute12.getValue()); + } + if (isNil11 == false) { + byte[] pfxBlobInstance; + pfxBlobInstance = pfxBlobElement2.getTextContent() != null ? Base64.decode(pfxBlobElement2.getTextContent()) : null; + certificateInstance.setPfxBlob(pfxBlobInstance); + } + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + boolean isNil12 = false; + Attr nilAttribute13 = selfLinkElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute13 != null) { + isNil12 = "true".equals(nilAttribute13.getValue()); + } + if (isNil12 == false) { + URI selfLinkInstance; + selfLinkInstance = new URI(selfLinkElement.getTextContent()); + certificateInstance.setSelfLinkUri(selfLinkInstance); + } + } + + Element siteNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SiteName"); + if (siteNameElement != null) { + boolean isNil13 = false; + Attr nilAttribute14 = siteNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute14 != null) { + isNil13 = "true".equals(nilAttribute14.getValue()); + } + if (isNil13 == false) { + String siteNameInstance; + siteNameInstance = siteNameElement.getTextContent(); + certificateInstance.setSiteName(siteNameInstance); + } + } + + Element subjectNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubjectName"); + if (subjectNameElement != null) { + boolean isNil14 = false; + Attr nilAttribute15 = subjectNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute15 != null) { + isNil14 = "true".equals(nilAttribute15.getValue()); + } + if (isNil14 == false) { + String subjectNameInstance; + subjectNameInstance = subjectNameElement.getTextContent(); + certificateInstance.setSubjectName(subjectNameInstance); + } + } + + Element thumbprintElement4 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement4 != null) { + boolean isNil15 = false; + Attr nilAttribute16 = thumbprintElement4.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute16 != null) { + isNil15 = "true".equals(nilAttribute16.getValue()); + } + if (isNil15 == false) { + String thumbprintInstance2; + thumbprintInstance2 = thumbprintElement4.getTextContent(); + certificateInstance.setThumbprint(thumbprintInstance2); + } + } + + Element toDeleteElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ToDelete"); + if (toDeleteElement2 != null && (toDeleteElement2.getTextContent() == null || toDeleteElement2.getTextContent().isEmpty() == true) == false) { + boolean isNil16 = false; + Attr nilAttribute17 = toDeleteElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute17 != null) { + isNil16 = "true".equals(nilAttribute17.getValue()); + } + if (isNil16 == false) { + boolean toDeleteInstance; + toDeleteInstance = DatatypeConverter.parseBoolean(toDeleteElement2.getTextContent().toLowerCase()); + certificateInstance.setIsToBeDeleted(toDeleteInstance); + } + } + + Element validElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Valid"); + if (validElement != null && (validElement.getTextContent() == null || validElement.getTextContent().isEmpty() == true) == false) { + boolean isNil17 = false; + Attr nilAttribute18 = validElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute18 != null) { + isNil17 = "true".equals(nilAttribute18.getValue()); + } + if (isNil17 == false) { + boolean validInstance; + validInstance = DatatypeConverter.parseBoolean(validElement.getTextContent().toLowerCase()); + certificateInstance.setIsValid(validInstance); + } + } + } + } + } + + Element selfLinkElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement2 != null) { + URI selfLinkInstance2; + selfLinkInstance2 = new URI(selfLinkElement2.getTextContent()); + webSiteInstance.setUri(selfLinkInstance2); + } + + Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); + if (serverFarmElement2 != null) { + String serverFarmInstance; + serverFarmInstance = serverFarmElement2.getTextContent(); + webSiteInstance.setServerFarm(serverFarmInstance); + } + + Element siteModeElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SiteMode"); + if (siteModeElement2 != null) { + WebSiteMode siteModeInstance; + siteModeInstance = WebSiteMode.valueOf(siteModeElement2.getTextContent()); + webSiteInstance.setSiteMode(siteModeInstance); + } + + Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "SiteProperties"); + if (sitePropertiesElement != null) { + WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties(); + webSiteInstance.setSiteProperties(sitePropertiesInstance); + + Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AppSettings"); + if (appSettingsSequenceElement != null) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i6 = i6 + 1) { + org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i6)); + String appSettingsKey = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String appSettingsValue = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue); + } + } + + Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Metadata"); + if (metadataSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i7 = i7 + 1) { + org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i7)); + String metadataKey = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String metadataValue = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue); + } + } + + Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Properties"); + if (propertiesSequenceElement != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i8 = i8 + 1) { + org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i8)); + String propertiesKey = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String propertiesValue = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue); + } + } + } + + Element stateElement2 = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement2 != null) { + String stateInstance; + stateInstance = stateElement2.getTextContent(); + webSiteInstance.setState(stateInstance); + } + + Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "UsageState"); + if (usageStateElement != null) { + WebSiteUsageState usageStateInstance; + usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent()); + webSiteInstance.setUsageState(usageStateInstance); + } + + Element webSpaceElement = XmlUtility.getElementByTagNameNS(siteElement2, "http://schemas.microsoft.com/windowsazure", "WebSpace"); + if (webSpaceElement != null) { + String webSpaceInstance; + webSpaceInstance = webSpaceElement.getTextContent(); + webSiteInstance.setWebSpace(webSpaceInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can update the config settings for a web site by issuing an HTTP PUT + * with a request body containing the updated settings. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update + * Configuration Web Site operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future updateConfigurationAsync(final String webSpaceName, final String webSiteName, final WebSiteUpdateConfigurationParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return updateConfiguration(webSpaceName, webSiteName, parameters); + } + }); + } + + /** + * You can update the config settings for a web site by issuing an HTTP PUT + * with a request body containing the updated settings. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166985.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param webSiteName Required. The name of the web site. + * @param parameters Required. Parameters supplied to the Update + * Configuration Web Site operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse updateConfiguration(String webSpaceName, String webSiteName, WebSiteUpdateConfigurationParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + if (webSiteName == null) { + throw new NullPointerException("webSiteName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("webSiteName", webSiteName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateConfigurationAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/config"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element siteConfigElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SiteConfig"); + requestDoc.appendChild(siteConfigElement); + + if (parameters.getAppSettings() != null) { + Element appSettingsDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AppSettings"); + for (Map.Entry entry : parameters.getAppSettings().entrySet()) { + String appSettingsKey = entry.getKey(); + String appSettingsValue = entry.getValue(); + Element appSettingsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NameValuePair"); + appSettingsDictionaryElement.appendChild(appSettingsElement); + + Element appSettingsKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + appSettingsKeyElement.appendChild(requestDoc.createTextNode(appSettingsKey)); + appSettingsElement.appendChild(appSettingsKeyElement); + + Element appSettingsValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + appSettingsValueElement.appendChild(requestDoc.createTextNode(appSettingsValue)); + appSettingsElement.appendChild(appSettingsValueElement); + } + siteConfigElement.appendChild(appSettingsDictionaryElement); + } + + if (parameters.getConnectionStrings() != null) { + Element connectionStringsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionStrings"); + for (WebSiteUpdateConfigurationParameters.ConnectionStringInfo connectionStringsItem : parameters.getConnectionStrings()) { + Element connStringInfoElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConnStringInfo"); + connectionStringsSequenceElement.appendChild(connStringInfoElement); + + if (connectionStringsItem.getConnectionString() != null) { + Element connectionStringElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionString"); + connectionStringElement.appendChild(requestDoc.createTextNode(connectionStringsItem.getConnectionString())); + connStringInfoElement.appendChild(connectionStringElement); + } + + if (connectionStringsItem.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(connectionStringsItem.getName())); + connStringInfoElement.appendChild(nameElement); + } + + if (connectionStringsItem.getType() != null) { + Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); + typeElement.appendChild(requestDoc.createTextNode(connectionStringsItem.getType())); + connStringInfoElement.appendChild(typeElement); + } + } + siteConfigElement.appendChild(connectionStringsSequenceElement); + } + + if (parameters.getDefaultDocuments() != null) { + Element defaultDocumentsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DefaultDocuments"); + for (String defaultDocumentsItem : parameters.getDefaultDocuments()) { + Element defaultDocumentsItemElement = requestDoc.createElementNS("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string"); + defaultDocumentsItemElement.appendChild(requestDoc.createTextNode(defaultDocumentsItem)); + defaultDocumentsSequenceElement.appendChild(defaultDocumentsItemElement); + } + siteConfigElement.appendChild(defaultDocumentsSequenceElement); + } + + if (parameters.isDetailedErrorLoggingEnabled() != null) { + Element detailedErrorLoggingEnabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DetailedErrorLoggingEnabled"); + detailedErrorLoggingEnabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isDetailedErrorLoggingEnabled()).toLowerCase())); + siteConfigElement.appendChild(detailedErrorLoggingEnabledElement); + } + + if (parameters.getDocumentRoot() != null) { + Element documentRootElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DocumentRoot"); + documentRootElement.appendChild(requestDoc.createTextNode(parameters.getDocumentRoot())); + siteConfigElement.appendChild(documentRootElement); + } + + if (parameters.getHandlerMappings() != null) { + Element handlerMappingsSequenceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HandlerMappings"); + for (WebSiteUpdateConfigurationParameters.HandlerMapping handlerMappingsItem : parameters.getHandlerMappings()) { + Element handlerMappingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HandlerMapping"); + handlerMappingsSequenceElement.appendChild(handlerMappingElement); + + if (handlerMappingsItem.getArguments() != null) { + Element argumentsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Arguments"); + argumentsElement.appendChild(requestDoc.createTextNode(handlerMappingsItem.getArguments())); + handlerMappingElement.appendChild(argumentsElement); + } + + if (handlerMappingsItem.getExtension() != null) { + Element extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); + extensionElement.appendChild(requestDoc.createTextNode(handlerMappingsItem.getExtension())); + handlerMappingElement.appendChild(extensionElement); + } + + if (handlerMappingsItem.getScriptProcessor() != null) { + Element scriptProcessorElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ScriptProcessor"); + scriptProcessorElement.appendChild(requestDoc.createTextNode(handlerMappingsItem.getScriptProcessor())); + handlerMappingElement.appendChild(scriptProcessorElement); + } + } + siteConfigElement.appendChild(handlerMappingsSequenceElement); + } + + if (parameters.isHttpLoggingEnabled() != null) { + Element httpLoggingEnabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "HttpLoggingEnabled"); + httpLoggingEnabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isHttpLoggingEnabled()).toLowerCase())); + siteConfigElement.appendChild(httpLoggingEnabledElement); + } + + if (parameters.getLogsDirectorySizeLimit() != null) { + Element logsDirectorySizeLimitElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "LogsDirectorySizeLimit"); + logsDirectorySizeLimitElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getLogsDirectorySizeLimit()))); + siteConfigElement.appendChild(logsDirectorySizeLimitElement); + } + + if (parameters.getManagedPipelineMode() != null) { + Element managedPipelineModeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ManagedPipelineMode"); + managedPipelineModeElement.appendChild(requestDoc.createTextNode(parameters.getManagedPipelineMode().toString())); + siteConfigElement.appendChild(managedPipelineModeElement); + } + + if (parameters.getMetadata() != null) { + Element metadataDictionaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Metadata"); + for (Map.Entry entry2 : parameters.getMetadata().entrySet()) { + String metadataKey = entry2.getKey(); + String metadataValue = entry2.getValue(); + Element metadataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NameValuePair"); + metadataDictionaryElement.appendChild(metadataElement); + + Element metadataKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + metadataKeyElement.appendChild(requestDoc.createTextNode(metadataKey)); + metadataElement.appendChild(metadataKeyElement); + + Element metadataValueElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); + metadataValueElement.appendChild(requestDoc.createTextNode(metadataValue)); + metadataElement.appendChild(metadataValueElement); + } + siteConfigElement.appendChild(metadataDictionaryElement); + } + + if (parameters.getNetFrameworkVersion() != null) { + Element netFrameworkVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NetFrameworkVersion"); + netFrameworkVersionElement.appendChild(requestDoc.createTextNode(parameters.getNetFrameworkVersion())); + siteConfigElement.appendChild(netFrameworkVersionElement); + } + + if (parameters.getNumberOfWorkers() != null) { + Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); + numberOfWorkersElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers()))); + siteConfigElement.appendChild(numberOfWorkersElement); + } + + if (parameters.getPhpVersion() != null) { + Element phpVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PhpVersion"); + phpVersionElement.appendChild(requestDoc.createTextNode(parameters.getPhpVersion())); + siteConfigElement.appendChild(phpVersionElement); + } + + if (parameters.getPublishingPassword() != null) { + Element publishingPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingPassword"); + publishingPasswordElement.appendChild(requestDoc.createTextNode(parameters.getPublishingPassword())); + siteConfigElement.appendChild(publishingPasswordElement); + } + + if (parameters.getPublishingUserName() != null) { + Element publishingUsernameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingUsername"); + publishingUsernameElement.appendChild(requestDoc.createTextNode(parameters.getPublishingUserName())); + siteConfigElement.appendChild(publishingUsernameElement); + } + + if (parameters.isRemoteDebuggingEnabled() != null) { + Element remoteDebuggingEnabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteDebuggingEnabled"); + remoteDebuggingEnabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isRemoteDebuggingEnabled()).toLowerCase())); + siteConfigElement.appendChild(remoteDebuggingEnabledElement); + } + + Element remoteDebuggingVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteDebuggingVersion"); + remoteDebuggingVersionElement.appendChild(requestDoc.createTextNode(parameters.getRemoteDebuggingVersion().toString())); + siteConfigElement.appendChild(remoteDebuggingVersionElement); + + if (parameters.isRequestTracingEnabled() != null) { + Element requestTracingEnabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RequestTracingEnabled"); + requestTracingEnabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isRequestTracingEnabled()).toLowerCase())); + siteConfigElement.appendChild(requestTracingEnabledElement); + } + + if (parameters.getRequestTracingExpirationTime() != null) { + Element requestTracingExpirationTimeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RequestTracingExpirationTime"); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + requestTracingExpirationTimeElement.appendChild(requestDoc.createTextNode(simpleDateFormat.format(parameters.getRequestTracingExpirationTime().getTime()))); + siteConfigElement.appendChild(requestTracingExpirationTimeElement); + } + + if (parameters.getScmType() != null) { + Element scmTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ScmType"); + scmTypeElement.appendChild(requestDoc.createTextNode(parameters.getScmType())); + siteConfigElement.appendChild(scmTypeElement); + } + + if (parameters.isUse32BitWorkerProcess() != null) { + Element use32BitWorkerProcessElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Use32BitWorkerProcess"); + use32BitWorkerProcessElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isUse32BitWorkerProcess()).toLowerCase())); + siteConfigElement.appendChild(use32BitWorkerProcessElement); + } + + if (parameters.isWebSocketsEnabled() != null) { + Element webSocketsEnabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WebSocketsEnabled"); + webSocketsEnabledElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isWebSocketsEnabled()).toLowerCase())); + siteConfigElement.appendChild(webSocketsEnabledElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSpaceOperations.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSpaceOperations.java new file mode 100644 index 0000000000000..83dac228f3b3f --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSpaceOperations.java @@ -0,0 +1,240 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.WebSiteListParameters; +import com.microsoft.windowsazure.management.websites.models.WebSpacesCreatePublishingUserParameters; +import com.microsoft.windowsazure.management.websites.models.WebSpacesCreatePublishingUserResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesGetDnsSuffixResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesGetResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListGeoRegionsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListPublishingUsersResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListWebSitesResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* Operations for managing web spaces beneath your subscription. +*/ +public interface WebSpaceOperations { + /** + * Creates a source control user with permissions to publish to this web + * space. + * + * @param username Required. The user name. + * @param password Required. The user password. + * @param parameters Optional. Parameters supplied to the Create Publishing + * User operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The Create Publishing User operation response. + */ + WebSpacesCreatePublishingUserResponse createPublishingUser(String username, String password, WebSpacesCreatePublishingUserParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * Creates a source control user with permissions to publish to this web + * space. + * + * @param username Required. The user name. + * @param password Required. The user password. + * @param parameters Optional. Parameters supplied to the Create Publishing + * User operation. + * @return The Create Publishing User operation response. + */ + Future createPublishingUserAsync(String username, String password, WebSpacesCreatePublishingUserParameters parameters); + + /** + * You can retrieve details for a specified web space name by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Web Space Details operation response. + */ + WebSpacesGetResponse get(String webSpaceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * You can retrieve details for a specified web space name by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @return The Get Web Space Details operation response. + */ + Future getAsync(String webSpaceName); + + /** + * Get the DNS Suffix for this subscription. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get DNS Suffix operation response. + */ + WebSpacesGetDnsSuffixResponse getDnsSuffix() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Get the DNS Suffix for this subscription. + * + * @return The Get DNS Suffix operation response. + */ + Future getDnsSuffixAsync(); + + /** + * You can list the web spaces under the current subscription by issuing a + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Web Spaces operation response. + */ + WebSpacesListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * You can list the web spaces under the current subscription by issuing a + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx for + * more information) + * + * @return The List Web Spaces operation response. + */ + Future listAsync(); + + /** + * Get the available geo regions for this web space. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Geo Regions operation response. + */ + WebSpacesListGeoRegionsResponse listGeoRegions() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Get the available geo regions for this web space. + * + * @return The List Geo Regions operation response. + */ + Future listGeoRegionsAsync(); + + /** + * Get the source control users allowed to publish to this web space. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Publishing Users operation response. + */ + WebSpacesListPublishingUsersResponse listPublishingUsers() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * Get the source control users allowed to publish to this web space. + * + * @return The List Publishing Users operation response. + */ + Future listPublishingUsersAsync(); + + /** + * You can retrieve a list of all web sites in a web space by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236429.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Optional. Additional parameters. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Web Sites operation response. + */ + WebSpacesListWebSitesResponse listWebSites(String webSpaceName, WebSiteListParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * You can retrieve a list of all web sites in a web space by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236429.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Optional. Additional parameters. + * @return The List Web Sites operation response. + */ + Future listWebSitesAsync(String webSpaceName, WebSiteListParameters parameters); +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSpaceOperationsImpl.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSpaceOperationsImpl.java new file mode 100644 index 0000000000000..88ba8a38102ff --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/WebSpaceOperationsImpl.java @@ -0,0 +1,1620 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.CommaStringBuilder; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.WebSite; +import com.microsoft.windowsazure.management.websites.models.WebSiteComputeMode; +import com.microsoft.windowsazure.management.websites.models.WebSiteListParameters; +import com.microsoft.windowsazure.management.websites.models.WebSiteMode; +import com.microsoft.windowsazure.management.websites.models.WebSiteRuntimeAvailabilityState; +import com.microsoft.windowsazure.management.websites.models.WebSiteSslState; +import com.microsoft.windowsazure.management.websites.models.WebSiteUsageState; +import com.microsoft.windowsazure.management.websites.models.WebSpaceAvailabilityState; +import com.microsoft.windowsazure.management.websites.models.WebSpaceStatus; +import com.microsoft.windowsazure.management.websites.models.WebSpaceWorkerSize; +import com.microsoft.windowsazure.management.websites.models.WebSpacesCreatePublishingUserParameters; +import com.microsoft.windowsazure.management.websites.models.WebSpacesCreatePublishingUserResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesGetDnsSuffixResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesGetResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListGeoRegionsResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListPublishingUsersResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListResponse; +import com.microsoft.windowsazure.management.websites.models.WebSpacesListWebSitesResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Operations for managing web spaces beneath your subscription. +*/ +public class WebSpaceOperationsImpl implements ServiceOperations, WebSpaceOperations { + /** + * Initializes a new instance of the WebSpaceOperationsImpl class. + * + * @param client Reference to the service client. + */ + WebSpaceOperationsImpl(WebSiteManagementClientImpl client) { + this.client = client; + } + + private WebSiteManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.websites.WebSiteManagementClientImpl. + * @return The Client value. + */ + public WebSiteManagementClientImpl getClient() { + return this.client; + } + + /** + * Creates a source control user with permissions to publish to this web + * space. + * + * @param username Required. The user name. + * @param password Required. The user password. + * @param parameters Optional. Parameters supplied to the Create Publishing + * User operation. + * @return The Create Publishing User operation response. + */ + @Override + public Future createPublishingUserAsync(final String username, final String password, final WebSpacesCreatePublishingUserParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSpacesCreatePublishingUserResponse call() throws Exception { + return createPublishingUser(username, password, parameters); + } + }); + } + + /** + * Creates a source control user with permissions to publish to this web + * space. + * + * @param username Required. The user name. + * @param password Required. The user password. + * @param parameters Optional. Parameters supplied to the Create Publishing + * User operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return The Create Publishing User operation response. + */ + @Override + public WebSpacesCreatePublishingUserResponse createPublishingUser(String username, String password, WebSpacesCreatePublishingUserParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (username == null) { + throw new NullPointerException("username"); + } + if (password == null) { + throw new NullPointerException("password"); + } + if (parameters != null) { + if (parameters.getPublishingPassword() == null) { + throw new NullPointerException("parameters.PublishingPassword"); + } + if (parameters.getPublishingUserName() == null) { + throw new NullPointerException("parameters.PublishingUserName"); + } + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("username", username); + tracingParameters.put("password", password); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createPublishingUserAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces" + "?" + "properties=publishingCredentials"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + if (parameters != null) { + Element userElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "User"); + requestDoc.appendChild(userElement); + + if (parameters.getName() != null) { + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + userElement.appendChild(nameElement); + } + + Element publishingPasswordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingPassword"); + publishingPasswordElement.appendChild(requestDoc.createTextNode(parameters.getPublishingPassword())); + userElement.appendChild(publishingPasswordElement); + + Element publishingUserNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "PublishingUserName"); + publishingUserNameElement.appendChild(requestDoc.createTextNode(parameters.getPublishingUserName())); + userElement.appendChild(publishingUserNameElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSpacesCreatePublishingUserResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSpacesCreatePublishingUserResponse(); + DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); + documentBuilderFactory2.setNamespaceAware(true); + DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); + Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); + + Element userElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "User"); + if (userElement2 != null) { + Element nameElement2 = XmlUtility.getElementByTagNameNS(userElement2, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance; + nameInstance = nameElement2.getTextContent(); + result.setName(nameInstance); + } + + Element publishingPasswordElement2 = XmlUtility.getElementByTagNameNS(userElement2, "http://schemas.microsoft.com/windowsazure", "PublishingPassword"); + if (publishingPasswordElement2 != null) { + String publishingPasswordInstance; + publishingPasswordInstance = publishingPasswordElement2.getTextContent(); + result.setPublishingPassword(publishingPasswordInstance); + } + + Element publishingUserNameElement2 = XmlUtility.getElementByTagNameNS(userElement2, "http://schemas.microsoft.com/windowsazure", "PublishingUserName"); + if (publishingUserNameElement2 != null) { + String publishingUserNameInstance; + publishingUserNameInstance = publishingUserNameElement2.getTextContent(); + result.setPublishingUserName(publishingUserNameInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve details for a specified web space name by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @return The Get Web Space Details operation response. + */ + @Override + public Future getAsync(final String webSpaceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSpacesGetResponse call() throws Exception { + return get(webSpaceName); + } + }); + } + + /** + * You can retrieve details for a specified web space name by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Web Space Details operation response. + */ + @Override + public WebSpacesGetResponse get(String webSpaceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSpacesGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSpacesGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element webSpacesElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "WebSpaces"); + if (webSpacesElement != null) { + Element availabilityStateElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "AvailabilityState"); + if (availabilityStateElement != null) { + WebSpaceAvailabilityState availabilityStateInstance; + availabilityStateInstance = WebSpaceAvailabilityState.valueOf(availabilityStateElement.getTextContent()); + result.setAvailabilityState(availabilityStateInstance); + } + + Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + if (currentNumberOfWorkersElement != null && (currentNumberOfWorkersElement.getTextContent() == null || currentNumberOfWorkersElement.getTextContent().isEmpty() == true) == false) { + boolean isNil = false; + Attr nilAttribute = currentNumberOfWorkersElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + int currentNumberOfWorkersInstance; + currentNumberOfWorkersInstance = DatatypeConverter.parseInt(currentNumberOfWorkersElement.getTextContent()); + result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance); + } + } + + Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + if (currentWorkerSizeElement != null && (currentWorkerSizeElement.getTextContent() == null || currentWorkerSizeElement.getTextContent().isEmpty() == true) == false) { + boolean isNil2 = false; + Attr nilAttribute2 = currentWorkerSizeElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + WebSpaceWorkerSize currentWorkerSizeInstance; + currentWorkerSizeInstance = WebSpaceWorkerSize.valueOf(currentWorkerSizeElement.getTextContent()); + result.setCurrentWorkerSize(currentWorkerSizeInstance); + } + } + + Element geoLocationElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "GeoLocation"); + if (geoLocationElement != null) { + String geoLocationInstance; + geoLocationInstance = geoLocationElement.getTextContent(); + result.setGeoLocation(geoLocationInstance); + } + + Element geoRegionElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "GeoRegion"); + if (geoRegionElement != null) { + String geoRegionInstance; + geoRegionInstance = geoRegionElement.getTextContent(); + result.setGeoRegion(geoRegionInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element planElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Plan"); + if (planElement != null) { + String planInstance; + planInstance = planElement.getTextContent(); + result.setPlan(planInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + WebSpaceStatus statusInstance; + statusInstance = WebSpaceStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element subscriptionElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Subscription"); + if (subscriptionElement != null) { + String subscriptionInstance; + subscriptionInstance = subscriptionElement.getTextContent(); + result.setSubscription(subscriptionInstance); + } + + Element workerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); + if (workerSizeElement != null && (workerSizeElement.getTextContent() == null || workerSizeElement.getTextContent().isEmpty() == true) == false) { + WebSpaceWorkerSize workerSizeInstance; + workerSizeInstance = WebSpaceWorkerSize.valueOf(workerSizeElement.getTextContent()); + result.setWorkerSize(workerSizeInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Get the DNS Suffix for this subscription. + * + * @return The Get DNS Suffix operation response. + */ + @Override + public Future getDnsSuffixAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSpacesGetDnsSuffixResponse call() throws Exception { + return getDnsSuffix(); + } + }); + } + + /** + * Get the DNS Suffix for this subscription. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The Get DNS Suffix operation response. + */ + @Override + public WebSpacesGetDnsSuffixResponse getDnsSuffix() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "getDnsSuffixAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces" + "?" + "properties=dnssuffix"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSpacesGetDnsSuffixResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSpacesGetDnsSuffixResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element stringElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "string"); + if (stringElement != null) { + result.setDnsSuffix(stringElement.getTextContent()); + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can list the web spaces under the current subscription by issuing a + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx for + * more information) + * + * @return The List Web Spaces operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSpacesListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * You can list the web spaces under the current subscription by issuing a + * GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Web Spaces operation response. + */ + @Override + public WebSpacesListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSpacesListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSpacesListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element webSpacesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "WebSpaces"); + if (webSpacesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(webSpacesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSpace").size(); i1 = i1 + 1) { + org.w3c.dom.Element webSpacesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(webSpacesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSpace").get(i1)); + WebSpacesListResponse.WebSpace webSpaceInstance = new WebSpacesListResponse.WebSpace(); + result.getWebSpaces().add(webSpaceInstance); + + Element availabilityStateElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "AvailabilityState"); + if (availabilityStateElement != null) { + WebSpaceAvailabilityState availabilityStateInstance; + availabilityStateInstance = WebSpaceAvailabilityState.valueOf(availabilityStateElement.getTextContent()); + webSpaceInstance.setAvailabilityState(availabilityStateInstance); + } + + Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers"); + if (currentNumberOfWorkersElement != null && (currentNumberOfWorkersElement.getTextContent() == null || currentNumberOfWorkersElement.getTextContent().isEmpty() == true) == false) { + boolean isNil = false; + Attr nilAttribute = currentNumberOfWorkersElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + int currentNumberOfWorkersInstance; + currentNumberOfWorkersInstance = DatatypeConverter.parseInt(currentNumberOfWorkersElement.getTextContent()); + webSpaceInstance.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance); + } + } + + Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize"); + if (currentWorkerSizeElement != null && (currentWorkerSizeElement.getTextContent() == null || currentWorkerSizeElement.getTextContent().isEmpty() == true) == false) { + boolean isNil2 = false; + Attr nilAttribute2 = currentWorkerSizeElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + WebSpaceWorkerSize currentWorkerSizeInstance; + currentWorkerSizeInstance = WebSpaceWorkerSize.valueOf(currentWorkerSizeElement.getTextContent()); + webSpaceInstance.setCurrentWorkerSize(currentWorkerSizeInstance); + } + } + + Element geoLocationElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "GeoLocation"); + if (geoLocationElement != null) { + String geoLocationInstance; + geoLocationInstance = geoLocationElement.getTextContent(); + webSpaceInstance.setGeoLocation(geoLocationInstance); + } + + Element geoRegionElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "GeoRegion"); + if (geoRegionElement != null) { + String geoRegionInstance; + geoRegionInstance = geoRegionElement.getTextContent(); + webSpaceInstance.setGeoRegion(geoRegionInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + webSpaceInstance.setName(nameInstance); + } + + Element planElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Plan"); + if (planElement != null) { + String planInstance; + planInstance = planElement.getTextContent(); + webSpaceInstance.setPlan(planInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + WebSpaceStatus statusInstance; + statusInstance = WebSpaceStatus.valueOf(statusElement.getTextContent()); + webSpaceInstance.setStatus(statusInstance); + } + + Element subscriptionElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "Subscription"); + if (subscriptionElement != null) { + String subscriptionInstance; + subscriptionInstance = subscriptionElement.getTextContent(); + webSpaceInstance.setSubscription(subscriptionInstance); + } + + Element workerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); + if (workerSizeElement != null && (workerSizeElement.getTextContent() == null || workerSizeElement.getTextContent().isEmpty() == true) == false) { + WebSpaceWorkerSize workerSizeInstance; + workerSizeInstance = WebSpaceWorkerSize.valueOf(workerSizeElement.getTextContent()); + webSpaceInstance.setWorkerSize(workerSizeInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Get the available geo regions for this web space. + * + * @return The List Geo Regions operation response. + */ + @Override + public Future listGeoRegionsAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSpacesListGeoRegionsResponse call() throws Exception { + return listGeoRegions(); + } + }); + } + + /** + * Get the available geo regions for this web space. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Geo Regions operation response. + */ + @Override + public WebSpacesListGeoRegionsResponse listGeoRegions() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listGeoRegionsAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces" + "?" + "properties=georegions"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSpacesListGeoRegionsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSpacesListGeoRegionsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element geoRegionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GeoRegions"); + if (geoRegionsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(geoRegionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "GeoRegion").size(); i1 = i1 + 1) { + org.w3c.dom.Element geoRegionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(geoRegionsSequenceElement, "http://schemas.microsoft.com/windowsazure", "GeoRegion").get(i1)); + WebSpacesListGeoRegionsResponse.GeoRegion geoRegionInstance = new WebSpacesListGeoRegionsResponse.GeoRegion(); + result.getGeoRegions().add(geoRegionInstance); + + Element descriptionElement = XmlUtility.getElementByTagNameNS(geoRegionsElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + geoRegionInstance.setDescription(descriptionInstance); + } + + Element nameElement = XmlUtility.getElementByTagNameNS(geoRegionsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + geoRegionInstance.setName(nameInstance); + } + + Element sortOrderElement = XmlUtility.getElementByTagNameNS(geoRegionsElement, "http://schemas.microsoft.com/windowsazure", "SortOrder"); + if (sortOrderElement != null) { + boolean isNil = false; + Attr nilAttribute = sortOrderElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + int sortOrderInstance; + sortOrderInstance = DatatypeConverter.parseInt(sortOrderElement.getTextContent()); + geoRegionInstance.setSortOrder(sortOrderInstance); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Get the source control users allowed to publish to this web space. + * + * @return The List Publishing Users operation response. + */ + @Override + public Future listPublishingUsersAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSpacesListPublishingUsersResponse call() throws Exception { + return listPublishingUsers(); + } + }); + } + + /** + * Get the source control users allowed to publish to this web space. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Publishing Users operation response. + */ + @Override + public WebSpacesListPublishingUsersResponse listPublishingUsers() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listPublishingUsersAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces" + "?" + "properties=publishingUsers"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSpacesListPublishingUsersResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSpacesListPublishingUsersResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element arrayOfstringSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "ArrayOfstring"); + if (arrayOfstringSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(arrayOfstringSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i1 = i1 + 1) { + org.w3c.dom.Element arrayOfstringElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(arrayOfstringSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i1)); + WebSpacesListPublishingUsersResponse.User stringInstance = new WebSpacesListPublishingUsersResponse.User(); + result.getUsers().add(stringInstance); + + String stringInstance2; + stringInstance2 = arrayOfstringElement.getTextContent(); + stringInstance.setName(stringInstance2); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * You can retrieve a list of all web sites in a web space by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236429.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Optional. Additional parameters. + * @return The List Web Sites operation response. + */ + @Override + public Future listWebSitesAsync(final String webSpaceName, final WebSiteListParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public WebSpacesListWebSitesResponse call() throws Exception { + return listWebSites(webSpaceName, parameters); + } + }); + } + + /** + * You can retrieve a list of all web sites in a web space by issuing an + * HTTP GET request. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/dn236429.aspx for + * more information) + * + * @param webSpaceName Required. The name of the web space. + * @param parameters Optional. Additional parameters. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The List Web Sites operation response. + */ + @Override + public WebSpacesListWebSitesResponse listWebSites(String webSpaceName, WebSiteListParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (webSpaceName == null) { + throw new NullPointerException("webSpaceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("webSpaceName", webSpaceName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "listWebSitesAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services/WebSpaces/" + webSpaceName.trim() + "/sites" + "?"; + if (parameters != null && parameters.getPropertiesToInclude() != null && parameters.getPropertiesToInclude().size() > 0) { + url = url + "&" + "propertiesToInclude=" + URLEncoder.encode(CommaStringBuilder.join(parameters.getPropertiesToInclude()), "UTF-8"); + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-08-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + WebSpacesListWebSitesResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new WebSpacesListWebSitesResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element sitesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Sites"); + if (sitesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sitesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Site").size(); i1 = i1 + 1) { + org.w3c.dom.Element sitesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sitesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Site").get(i1)); + WebSite siteInstance = new WebSite(); + result.getWebSites().add(siteInstance); + + Element adminEnabledElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "AdminEnabled"); + if (adminEnabledElement != null) { + boolean adminEnabledInstance; + adminEnabledInstance = DatatypeConverter.parseBoolean(adminEnabledElement.getTextContent().toLowerCase()); + siteInstance.setAdminEnabled(adminEnabledInstance); + } + + Element availabilityStateElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "AvailabilityState"); + if (availabilityStateElement != null) { + WebSpaceAvailabilityState availabilityStateInstance; + availabilityStateInstance = WebSpaceAvailabilityState.valueOf(availabilityStateElement.getTextContent()); + siteInstance.setAvailabilityState(availabilityStateInstance); + } + + Element computeModeElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "ComputeMode"); + if (computeModeElement != null) { + WebSiteComputeMode computeModeInstance; + computeModeInstance = WebSiteComputeMode.valueOf(computeModeElement.getTextContent()); + siteInstance.setComputeMode(computeModeInstance); + } + + Element enabledElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "Enabled"); + if (enabledElement != null) { + boolean enabledInstance; + enabledInstance = DatatypeConverter.parseBoolean(enabledElement.getTextContent().toLowerCase()); + siteInstance.setEnabled(enabledInstance); + } + + Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "EnabledHostNames"); + if (enabledHostNamesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i2 = i2 + 1) { + org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(enabledHostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i2)); + siteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent()); + } + } + + Element hostNameSslStatesSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "HostNameSslStates"); + if (hostNameSslStatesSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").size(); i3 = i3 + 1) { + org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNameSslStatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState").get(i3)); + WebSite.WebSiteHostNameSslState webSiteHostNameSslStateInstance = new WebSite.WebSiteHostNameSslState(); + siteInstance.getHostNameSslStates().add(webSiteHostNameSslStateInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + webSiteHostNameSslStateInstance.setName(nameInstance); + } + + Element sslStateElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "SslState"); + if (sslStateElement != null) { + WebSiteSslState sslStateInstance; + sslStateInstance = WebSiteSslState.valueOf(sslStateElement.getTextContent()); + webSiteHostNameSslStateInstance.setSslState(sslStateInstance); + } + + Element thumbprintElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement != null) { + boolean isNil = false; + Attr nilAttribute = thumbprintElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute != null) { + isNil = "true".equals(nilAttribute.getValue()); + } + if (isNil == false) { + String thumbprintInstance; + thumbprintInstance = thumbprintElement.getTextContent(); + webSiteHostNameSslStateInstance.setThumbprint(thumbprintInstance); + } + } + + Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement, "http://schemas.microsoft.com/windowsazure", "VirtualIP"); + if (virtualIPElement != null) { + boolean isNil2 = false; + Attr nilAttribute2 = virtualIPElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute2 != null) { + isNil2 = "true".equals(nilAttribute2.getValue()); + } + if (isNil2 == false) { + InetAddress virtualIPInstance; + virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent()); + webSiteHostNameSslStateInstance.setVirtualIP(virtualIPInstance); + } + } + } + } + + Element hostNamesSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement != null) { + for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i4 = i4 + 1) { + org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i4)); + siteInstance.getHostNames().add(hostNamesElement.getTextContent()); + } + } + + Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc"); + if (lastModifiedTimeUtcElement != null) { + Calendar lastModifiedTimeUtcInstance; + lastModifiedTimeUtcInstance = DatatypeConverter.parseDateTime(lastModifiedTimeUtcElement.getTextContent()); + siteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance); + } + + Element nameElement2 = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement2 != null) { + String nameInstance2; + nameInstance2 = nameElement2.getTextContent(); + siteInstance.setName(nameInstance2); + } + + Element ownerElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "Owner"); + if (ownerElement != null) { + boolean isNil3 = false; + Attr nilAttribute3 = ownerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute3 != null) { + isNil3 = "true".equals(nilAttribute3.getValue()); + } + if (isNil3 == false) { + String ownerInstance; + ownerInstance = ownerElement.getTextContent(); + siteInstance.setOwner(ownerInstance); + } + } + + Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "RepositorySiteName"); + if (repositorySiteNameElement != null) { + String repositorySiteNameInstance; + repositorySiteNameInstance = repositorySiteNameElement.getTextContent(); + siteInstance.setRepositorySiteName(repositorySiteNameInstance); + } + + Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState"); + if (runtimeAvailabilityStateElement != null) { + WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance; + runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState.valueOf(runtimeAvailabilityStateElement.getTextContent()); + siteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance); + } + + Element sSLCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "SSLCertificates"); + if (sSLCertificatesSequenceElement != null) { + boolean isNil4 = false; + Attr nilAttribute4 = sSLCertificatesSequenceElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute4 != null) { + isNil4 = "true".equals(nilAttribute4.getValue()); + } + if (isNil4 == false) { + for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").size(); i5 = i5 + 1) { + org.w3c.dom.Element sSLCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(sSLCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Certificate").get(i5)); + WebSite.WebSiteSslCertificate certificateInstance = new WebSite.WebSiteSslCertificate(); + siteInstance.getSslCertificates().add(certificateInstance); + + Element expirationDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ExpirationDate"); + if (expirationDateElement != null && (expirationDateElement.getTextContent() == null || expirationDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil5 = false; + Attr nilAttribute5 = expirationDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute5 != null) { + isNil5 = "true".equals(nilAttribute5.getValue()); + } + if (isNil5 == false) { + Calendar expirationDateInstance; + expirationDateInstance = DatatypeConverter.parseDateTime(expirationDateElement.getTextContent()); + certificateInstance.setExpirationDate(expirationDateInstance); + } + } + + Element friendlyNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "FriendlyName"); + if (friendlyNameElement != null) { + boolean isNil6 = false; + Attr nilAttribute6 = friendlyNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute6 != null) { + isNil6 = "true".equals(nilAttribute6.getValue()); + } + if (isNil6 == false) { + String friendlyNameInstance; + friendlyNameInstance = friendlyNameElement.getTextContent(); + certificateInstance.setFriendlyName(friendlyNameInstance); + } + } + + Element hostNamesSequenceElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "HostNames"); + if (hostNamesSequenceElement2 != null) { + boolean isNil7 = false; + Attr nilAttribute7 = hostNamesSequenceElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute7 != null) { + isNil7 = "true".equals(nilAttribute7.getValue()); + } + if (isNil7 == false) { + for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").size(); i6 = i6 + 1) { + org.w3c.dom.Element hostNamesElement2 = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostNamesSequenceElement2, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string").get(i6)); + certificateInstance.getHostNames().add(hostNamesElement2.getTextContent()); + } + } + } + + Element issueDateElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "IssueDate"); + if (issueDateElement != null && (issueDateElement.getTextContent() == null || issueDateElement.getTextContent().isEmpty() == true) == false) { + boolean isNil8 = false; + Attr nilAttribute8 = issueDateElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute8 != null) { + isNil8 = "true".equals(nilAttribute8.getValue()); + } + if (isNil8 == false) { + Calendar issueDateInstance; + issueDateInstance = DatatypeConverter.parseDateTime(issueDateElement.getTextContent()); + certificateInstance.setIssueDate(issueDateInstance); + } + } + + Element issuerElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Issuer"); + if (issuerElement != null) { + boolean isNil9 = false; + Attr nilAttribute9 = issuerElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute9 != null) { + isNil9 = "true".equals(nilAttribute9.getValue()); + } + if (isNil9 == false) { + String issuerInstance; + issuerInstance = issuerElement.getTextContent(); + certificateInstance.setIssuer(issuerInstance); + } + } + + Element passwordElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Password"); + if (passwordElement != null) { + boolean isNil10 = false; + Attr nilAttribute10 = passwordElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute10 != null) { + isNil10 = "true".equals(nilAttribute10.getValue()); + } + if (isNil10 == false) { + String passwordInstance; + passwordInstance = passwordElement.getTextContent(); + certificateInstance.setPassword(passwordInstance); + } + } + + Element pfxBlobElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "PfxBlob"); + if (pfxBlobElement != null) { + boolean isNil11 = false; + Attr nilAttribute11 = pfxBlobElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute11 != null) { + isNil11 = "true".equals(nilAttribute11.getValue()); + } + if (isNil11 == false) { + byte[] pfxBlobInstance; + pfxBlobInstance = pfxBlobElement.getTextContent() != null ? Base64.decode(pfxBlobElement.getTextContent()) : null; + certificateInstance.setPfxBlob(pfxBlobInstance); + } + } + + Element selfLinkElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement != null) { + boolean isNil12 = false; + Attr nilAttribute12 = selfLinkElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute12 != null) { + isNil12 = "true".equals(nilAttribute12.getValue()); + } + if (isNil12 == false) { + URI selfLinkInstance; + selfLinkInstance = new URI(selfLinkElement.getTextContent()); + certificateInstance.setSelfLinkUri(selfLinkInstance); + } + } + + Element siteNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SiteName"); + if (siteNameElement != null) { + boolean isNil13 = false; + Attr nilAttribute13 = siteNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute13 != null) { + isNil13 = "true".equals(nilAttribute13.getValue()); + } + if (isNil13 == false) { + String siteNameInstance; + siteNameInstance = siteNameElement.getTextContent(); + certificateInstance.setSiteName(siteNameInstance); + } + } + + Element subjectNameElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubjectName"); + if (subjectNameElement != null) { + boolean isNil14 = false; + Attr nilAttribute14 = subjectNameElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute14 != null) { + isNil14 = "true".equals(nilAttribute14.getValue()); + } + if (isNil14 == false) { + String subjectNameInstance; + subjectNameInstance = subjectNameElement.getTextContent(); + certificateInstance.setSubjectName(subjectNameInstance); + } + } + + Element thumbprintElement2 = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); + if (thumbprintElement2 != null) { + boolean isNil15 = false; + Attr nilAttribute15 = thumbprintElement2.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute15 != null) { + isNil15 = "true".equals(nilAttribute15.getValue()); + } + if (isNil15 == false) { + String thumbprintInstance2; + thumbprintInstance2 = thumbprintElement2.getTextContent(); + certificateInstance.setThumbprint(thumbprintInstance2); + } + } + + Element toDeleteElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ToDelete"); + if (toDeleteElement != null && (toDeleteElement.getTextContent() == null || toDeleteElement.getTextContent().isEmpty() == true) == false) { + boolean isNil16 = false; + Attr nilAttribute16 = toDeleteElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute16 != null) { + isNil16 = "true".equals(nilAttribute16.getValue()); + } + if (isNil16 == false) { + boolean toDeleteInstance; + toDeleteInstance = DatatypeConverter.parseBoolean(toDeleteElement.getTextContent().toLowerCase()); + certificateInstance.setIsToBeDeleted(toDeleteInstance); + } + } + + Element validElement = XmlUtility.getElementByTagNameNS(sSLCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Valid"); + if (validElement != null && (validElement.getTextContent() == null || validElement.getTextContent().isEmpty() == true) == false) { + boolean isNil17 = false; + Attr nilAttribute17 = validElement.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); + if (nilAttribute17 != null) { + isNil17 = "true".equals(nilAttribute17.getValue()); + } + if (isNil17 == false) { + boolean validInstance; + validInstance = DatatypeConverter.parseBoolean(validElement.getTextContent().toLowerCase()); + certificateInstance.setIsValid(validInstance); + } + } + } + } + } + + Element selfLinkElement2 = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "SelfLink"); + if (selfLinkElement2 != null) { + URI selfLinkInstance2; + selfLinkInstance2 = new URI(selfLinkElement2.getTextContent()); + siteInstance.setUri(selfLinkInstance2); + } + + Element serverFarmElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); + if (serverFarmElement != null) { + String serverFarmInstance; + serverFarmInstance = serverFarmElement.getTextContent(); + siteInstance.setServerFarm(serverFarmInstance); + } + + Element siteModeElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "SiteMode"); + if (siteModeElement != null) { + WebSiteMode siteModeInstance; + siteModeInstance = WebSiteMode.valueOf(siteModeElement.getTextContent()); + siteInstance.setSiteMode(siteModeInstance); + } + + Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "SiteProperties"); + if (sitePropertiesElement != null) { + WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties(); + siteInstance.setSiteProperties(sitePropertiesInstance); + + Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AppSettings"); + if (appSettingsSequenceElement != null) { + for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i7 = i7 + 1) { + org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(appSettingsSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i7)); + String appSettingsKey = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String appSettingsValue = XmlUtility.getElementByTagNameNS(appSettingsElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue); + } + } + + Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Metadata"); + if (metadataSequenceElement != null) { + for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i8 = i8 + 1) { + org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(metadataSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i8)); + String metadataKey = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String metadataValue = XmlUtility.getElementByTagNameNS(metadataElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue); + } + } + + Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Properties"); + if (propertiesSequenceElement != null) { + for (int i9 = 0; i9 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").size(); i9 = i9 + 1) { + org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(propertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "NameValuePair").get(i9)); + String propertiesKey = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Name").getTextContent(); + String propertiesValue = XmlUtility.getElementByTagNameNS(propertiesElement, "http://schemas.microsoft.com/windowsazure", "Value").getTextContent(); + sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue); + } + } + } + + Element stateElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "State"); + if (stateElement != null) { + String stateInstance; + stateInstance = stateElement.getTextContent(); + siteInstance.setState(stateInstance); + } + + Element usageStateElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "UsageState"); + if (usageStateElement != null) { + WebSiteUsageState usageStateInstance; + usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent()); + siteInstance.setUsageState(usageStateInstance); + } + + Element webSpaceElement = XmlUtility.getElementByTagNameNS(sitesElement, "http://schemas.microsoft.com/windowsazure", "WebSpace"); + if (webSpaceElement != null) { + String webSpaceInstance; + webSpaceInstance = webSpaceElement.getTextContent(); + siteInstance.setWebSpace(webSpaceInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/GeoRegionNames.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/GeoRegionNames.java new file mode 100644 index 0000000000000..d33108b0f4f7f --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/GeoRegionNames.java @@ -0,0 +1,38 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +public abstract class GeoRegionNames { + public static final String EASTUS = "East US"; + + public static final String WESTUS = "West US"; + + public static final String NORTHCENTRALUS = "North Central US"; + + public static final String NORTHEUROPE = "North Europe"; + + public static final String WESTEUROPE = "West Europe"; + + public static final String EASTASIA = "East Asia"; +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/HistoricalUsageMetricNames.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/HistoricalUsageMetricNames.java new file mode 100644 index 0000000000000..af9fa632d44f3 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/HistoricalUsageMetricNames.java @@ -0,0 +1,69 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* Supported historical usage metric names. +*/ +public abstract class HistoricalUsageMetricNames { + public static final String CPUTIME = "CpuTime"; + + public static final String BYTESRECEIVED = "BytesReceived"; + + public static final String BYTESSENT = "BytesSent"; + + public static final String INCOMINGREQUESTBYTES = "IncomingRequestBytes"; + + public static final String INCOMINGREQUESTRESPONSEBYTES = "IncomingRequestResponseBytes"; + + public static final String OUTGOINGREQUESTBYTES = "OutgoingRequestBytes"; + + public static final String OUTGOINGREQUESTRESPONSEBYTES = "OutgoingRequestResponseBytes"; + + public static final String LOCALREADBYTES = "LocalReadBytes"; + + public static final String LOCALWRITTENBYTES = "LocalWrittenBytes"; + + public static final String NETWORKREADBYTES = "NetworkReadBytes"; + + public static final String NETWORKWRITTENBYTES = "NetworkWrittenBytes"; + + public static final String REQUESTS = "Requests"; + + public static final String HTTP2XX = "Http2xx"; + + public static final String HTTP3XX = "Http3xx"; + + public static final String HTTP401 = "Http401"; + + public static final String HTTP403 = "Http403"; + + public static final String HTTP404 = "Http404"; + + public static final String HTTP406 = "Http406"; + + public static final String HTTP4XX = "Http4xx"; + + public static final String HTTP5XX = "Http5xx"; +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ManagedPipelineMode.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ManagedPipelineMode.java new file mode 100644 index 0000000000000..70b284f48d76c --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ManagedPipelineMode.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The managed pipeline mode of a web site. +*/ +public enum ManagedPipelineMode { + /** + * Integrated Managed Pipeline Mode. + */ + Integrated, + + /** + * Classic Managed Pipeline Mode. + */ + Classic, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/RemoteDebuggingVersion.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/RemoteDebuggingVersion.java new file mode 100644 index 0000000000000..da4884f561da9 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/RemoteDebuggingVersion.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The remote debugging version. +*/ +public enum RemoteDebuggingVersion { + /** + * Visual Studio 2012. + */ + VS2012, + + /** + * Visual Studio 2013. + */ + VS2013, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmCreateParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmCreateParameters.java new file mode 100644 index 0000000000000..067269a2326d7 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmCreateParameters.java @@ -0,0 +1,123 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* Parameters supplied to the Create Server Farm operation. +*/ +public class ServerFarmCreateParameters { + private Integer currentNumberOfWorkers; + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @return The CurrentNumberOfWorkers value. + */ + public Integer getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final Integer currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private ServerFarmWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @return The CurrentWorkerSize value. + */ + public ServerFarmWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final ServerFarmWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private int numberOfWorkers; + + /** + * Required. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @return The NumberOfWorkers value. + */ + public int getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Required. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final int numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private ServerFarmStatus status; + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @return The Status value. + */ + public ServerFarmStatus getStatus() { + return this.status; + } + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @param statusValue The Status value. + */ + public void setStatus(final ServerFarmStatus statusValue) { + this.status = statusValue; + } + + private ServerFarmWorkerSize workerSize; + + /** + * Required. The instance size. Possible values are Small, Medium, or Large. + * @return The WorkerSize value. + */ + public ServerFarmWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Required. The instance size. Possible values are Small, Medium, or Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final ServerFarmWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmCreateResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmCreateResponse.java new file mode 100644 index 0000000000000..e315903a1c971 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmCreateResponse.java @@ -0,0 +1,143 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Create Server Farm operation response. +*/ +public class ServerFarmCreateResponse extends OperationResponse { + private int currentNumberOfWorkers; + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @return The CurrentNumberOfWorkers value. + */ + public int getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final int currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private ServerFarmWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @return The CurrentWorkerSize value. + */ + public ServerFarmWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final ServerFarmWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private String name; + + /** + * Optional. The name of the server farm. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the server farm. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private int numberOfWorkers; + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @return The NumberOfWorkers value. + */ + public int getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final int numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private ServerFarmStatus status; + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @return The Status value. + */ + public ServerFarmStatus getStatus() { + return this.status; + } + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @param statusValue The Status value. + */ + public void setStatus(final ServerFarmStatus statusValue) { + this.status = statusValue; + } + + private ServerFarmWorkerSize workerSize; + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @return The WorkerSize value. + */ + public ServerFarmWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final ServerFarmWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmGetResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmGetResponse.java new file mode 100644 index 0000000000000..2b2bbe1dab46a --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmGetResponse.java @@ -0,0 +1,143 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Server Farm operation response. +*/ +public class ServerFarmGetResponse extends OperationResponse { + private int currentNumberOfWorkers; + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @return The CurrentNumberOfWorkers value. + */ + public int getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final int currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private ServerFarmWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @return The CurrentWorkerSize value. + */ + public ServerFarmWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final ServerFarmWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private String name; + + /** + * Optional. The name of the server farm. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the server farm. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private int numberOfWorkers; + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @return The NumberOfWorkers value. + */ + public int getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final int numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private ServerFarmStatus status; + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @return The Status value. + */ + public ServerFarmStatus getStatus() { + return this.status; + } + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @param statusValue The Status value. + */ + public void setStatus(final ServerFarmStatus statusValue) { + this.status = statusValue; + } + + private ServerFarmWorkerSize workerSize; + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @return The WorkerSize value. + */ + public ServerFarmWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final ServerFarmWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmListResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmListResponse.java new file mode 100644 index 0000000000000..7a1473805b454 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmListResponse.java @@ -0,0 +1,191 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Server Farm operation response. +*/ +public class ServerFarmListResponse extends OperationResponse implements Iterable { + private ArrayList serverFarms; + + /** + * Optional. The server farms associated with the specified subscription. + * @return The ServerFarms value. + */ + public ArrayList getServerFarms() { + return this.serverFarms; + } + + /** + * Optional. The server farms associated with the specified subscription. + * @param serverFarmsValue The ServerFarms value. + */ + public void setServerFarms(final ArrayList serverFarmsValue) { + this.serverFarms = serverFarmsValue; + } + + /** + * Initializes a new instance of the ServerFarmListResponse class. + * + */ + public ServerFarmListResponse() { + super(); + this.serverFarms = new ArrayList(); + } + + /** + * Gets the sequence of ServerFarms. + * + */ + public Iterator iterator() { + return this.getServerFarms().iterator(); + } + + /** + * A server farm associated with the specified subscription. + */ + public static class ServerFarm { + private int currentNumberOfWorkers; + + /** + * Optional. The current number of Virtual Machines (VMs) in the server + * farm. + * @return The CurrentNumberOfWorkers value. + */ + public int getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of Virtual Machines (VMs) in the server + * farm. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final int currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private ServerFarmWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, + * or Large. + * @return The CurrentWorkerSize value. + */ + public ServerFarmWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, + * or Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final ServerFarmWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private String name; + + /** + * Optional. The name of the server farm. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the server farm. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private int numberOfWorkers; + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @return The NumberOfWorkers value. + */ + public int getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final int numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private ServerFarmStatus status; + + /** + * Optional. The server farm status. Possible values are Ready or + * Pending. + * @return The Status value. + */ + public ServerFarmStatus getStatus() { + return this.status; + } + + /** + * Optional. The server farm status. Possible values are Ready or + * Pending. + * @param statusValue The Status value. + */ + public void setStatus(final ServerFarmStatus statusValue) { + this.status = statusValue; + } + + private ServerFarmWorkerSize workerSize; + + /** + * Optional. The instance size. Possible values are Small, Medium, or + * Large. + * @return The WorkerSize value. + */ + public ServerFarmWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Optional. The instance size. Possible values are Small, Medium, or + * Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final ServerFarmWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmStatus.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmStatus.java new file mode 100644 index 0000000000000..d4374ea33ce19 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmStatus.java @@ -0,0 +1,30 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +public enum ServerFarmStatus { + Ready, + + Pending, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmUpdateParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmUpdateParameters.java new file mode 100644 index 0000000000000..783a47dc7b263 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmUpdateParameters.java @@ -0,0 +1,123 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* Parameters supplied to the Update Server Farm operation. +*/ +public class ServerFarmUpdateParameters { + private Integer currentNumberOfWorkers; + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @return The CurrentNumberOfWorkers value. + */ + public Integer getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final Integer currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private ServerFarmWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @return The CurrentWorkerSize value. + */ + public ServerFarmWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final ServerFarmWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private int numberOfWorkers; + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @return The NumberOfWorkers value. + */ + public int getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final int numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private ServerFarmStatus status; + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @return The Status value. + */ + public ServerFarmStatus getStatus() { + return this.status; + } + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @param statusValue The Status value. + */ + public void setStatus(final ServerFarmStatus statusValue) { + this.status = statusValue; + } + + private ServerFarmWorkerSize workerSize; + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @return The WorkerSize value. + */ + public ServerFarmWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final ServerFarmWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmUpdateResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmUpdateResponse.java new file mode 100644 index 0000000000000..89fedadd67fb4 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmUpdateResponse.java @@ -0,0 +1,143 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Update Server Farm operation response. +*/ +public class ServerFarmUpdateResponse extends OperationResponse { + private int currentNumberOfWorkers; + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @return The CurrentNumberOfWorkers value. + */ + public int getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of Virtual Machines (VMs) in the server farm. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final int currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private ServerFarmWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @return The CurrentWorkerSize value. + */ + public ServerFarmWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final ServerFarmWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private String name; + + /** + * Optional. The name of the server farm. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the server farm. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private int numberOfWorkers; + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @return The NumberOfWorkers value. + */ + public int getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Optional. The instance count, which is the number of virtual machines + * dedicated to the farm. Supported values are 1-10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final int numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private ServerFarmStatus status; + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @return The Status value. + */ + public ServerFarmStatus getStatus() { + return this.status; + } + + /** + * Optional. The server farm status. Possible values are Ready or Pending. + * @param statusValue The Status value. + */ + public void setStatus(final ServerFarmStatus statusValue) { + this.status = statusValue; + } + + private ServerFarmWorkerSize workerSize; + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @return The WorkerSize value. + */ + public ServerFarmWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Optional. The instance size. Possible values are Small, Medium, or Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final ServerFarmWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmWorkerSize.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmWorkerSize.java new file mode 100644 index 0000000000000..25abbb5c2d759 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/ServerFarmWorkerSize.java @@ -0,0 +1,32 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +public enum ServerFarmWorkerSize { + Small, + + Medium, + + Large, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSite.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSite.java new file mode 100644 index 0000000000000..906b11f661ee5 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSite.java @@ -0,0 +1,882 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import java.net.InetAddress; +import java.net.URI; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; + +/** +* Describes a web site. +*/ +public class WebSite { + private boolean adminEnabled; + + /** + * Optional. Read-only. This value is always true. + * @return The AdminEnabled value. + */ + public boolean isAdminEnabled() { + return this.adminEnabled; + } + + /** + * Optional. Read-only. This value is always true. + * @param adminEnabledValue The AdminEnabled value. + */ + public void setAdminEnabled(final boolean adminEnabledValue) { + this.adminEnabled = adminEnabledValue; + } + + private WebSpaceAvailabilityState availabilityState; + + /** + * Optional. The state of the availability of management information for the + * web site. Possible values are Normal or Limited. Normal means that the + * web site is running correctly and that management information for the + * web site is available. Limited means that only partial management + * information for the web site is available and that detailed web site + * information is unavailable. + * @return The AvailabilityState value. + */ + public WebSpaceAvailabilityState getAvailabilityState() { + return this.availabilityState; + } + + /** + * Optional. The state of the availability of management information for the + * web site. Possible values are Normal or Limited. Normal means that the + * web site is running correctly and that management information for the + * web site is available. Limited means that only partial management + * information for the web site is available and that detailed web site + * information is unavailable. + * @param availabilityStateValue The AvailabilityState value. + */ + public void setAvailabilityState(final WebSpaceAvailabilityState availabilityStateValue) { + this.availabilityState = availabilityStateValue; + } + + private WebSiteComputeMode computeMode; + + /** + * Optional. The Compute Mode for the web site. Possible values are Shared + * or Dedicated. + * @return The ComputeMode value. + */ + public WebSiteComputeMode getComputeMode() { + return this.computeMode; + } + + /** + * Optional. The Compute Mode for the web site. Possible values are Shared + * or Dedicated. + * @param computeModeValue The ComputeMode value. + */ + public void setComputeMode(final WebSiteComputeMode computeModeValue) { + this.computeMode = computeModeValue; + } + + private boolean enabled; + + /** + * Optional. The current state of the web site. This is true if the site is + * enabled and false otherwise. Setting this value to false disables the + * site (takes the site offline). + * @return The Enabled value. + */ + public boolean isEnabled() { + return this.enabled; + } + + /** + * Optional. The current state of the web site. This is true if the site is + * enabled and false otherwise. Setting this value to false disables the + * site (takes the site offline). + * @param enabledValue The Enabled value. + */ + public void setEnabled(final boolean enabledValue) { + this.enabled = enabledValue; + } + + private ArrayList enabledHostNames; + + /** + * Optional. An array of strings that contains enabled host names for the + * web site. By default, these are [SiteName].azurewebsites.net and + * [SiteName].scm.azurewebsites.net. + * @return The EnabledHostNames value. + */ + public ArrayList getEnabledHostNames() { + return this.enabledHostNames; + } + + /** + * Optional. An array of strings that contains enabled host names for the + * web site. By default, these are [SiteName].azurewebsites.net and + * [SiteName].scm.azurewebsites.net. + * @param enabledHostNamesValue The EnabledHostNames value. + */ + public void setEnabledHostNames(final ArrayList enabledHostNamesValue) { + this.enabledHostNames = enabledHostNamesValue; + } + + private ArrayList hostNames; + + /** + * Optional. An array of strings that contains the public host names for the + * web site, including custom domains. Important: When you add a custom + * domain in a PUT operation, be sure to include every host name that you + * want for the web site. To delete a custom domain name in a PUT + * operation, include all of the host names for the web site that you want + * to keep, but leave out the one that you want to delete. + * @return The HostNames value. + */ + public ArrayList getHostNames() { + return this.hostNames; + } + + /** + * Optional. An array of strings that contains the public host names for the + * web site, including custom domains. Important: When you add a custom + * domain in a PUT operation, be sure to include every host name that you + * want for the web site. To delete a custom domain name in a PUT + * operation, include all of the host names for the web site that you want + * to keep, but leave out the one that you want to delete. + * @param hostNamesValue The HostNames value. + */ + public void setHostNames(final ArrayList hostNamesValue) { + this.hostNames = hostNamesValue; + } + + private ArrayList hostNameSslStates; + + /** + * Optional. SSL states bound to the web site. + * @return The HostNameSslStates value. + */ + public ArrayList getHostNameSslStates() { + return this.hostNameSslStates; + } + + /** + * Optional. SSL states bound to the web site. + * @param hostNameSslStatesValue The HostNameSslStates value. + */ + public void setHostNameSslStates(final ArrayList hostNameSslStatesValue) { + this.hostNameSslStates = hostNameSslStatesValue; + } + + private Calendar lastModifiedTimeUtc; + + /** + * Optional. A dateTime value that contains, in Coordinated Universal Time, + * the last time the web site was modified. + * @return The LastModifiedTimeUtc value. + */ + public Calendar getLastModifiedTimeUtc() { + return this.lastModifiedTimeUtc; + } + + /** + * Optional. A dateTime value that contains, in Coordinated Universal Time, + * the last time the web site was modified. + * @param lastModifiedTimeUtcValue The LastModifiedTimeUtc value. + */ + public void setLastModifiedTimeUtc(final Calendar lastModifiedTimeUtcValue) { + this.lastModifiedTimeUtc = lastModifiedTimeUtcValue; + } + + private String name; + + /** + * Optional. The name of the web site. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the web site. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String owner; + + /** + * Optional. The owner of the web site. + * @return The Owner value. + */ + public String getOwner() { + return this.owner; + } + + /** + * Optional. The owner of the web site. + * @param ownerValue The Owner value. + */ + public void setOwner(final String ownerValue) { + this.owner = ownerValue; + } + + private String repositorySiteName; + + /** + * Optional. The name of the web site repository. + * @return The RepositorySiteName value. + */ + public String getRepositorySiteName() { + return this.repositorySiteName; + } + + /** + * Optional. The name of the web site repository. + * @param repositorySiteNameValue The RepositorySiteName value. + */ + public void setRepositorySiteName(final String repositorySiteNameValue) { + this.repositorySiteName = repositorySiteNameValue; + } + + private WebSiteRuntimeAvailabilityState runtimeAvailabilityState; + + /** + * Optional. The current availability state for the web site. Possible + * values are Normal, Degraded, or NotAvailable: Normal: the web site is + * running correctly; Degraded: the web site is running temporarily in a + * degraded mode (typically with less memory and a shared instance); Not + * Available: due to an unexpected issue, the site has been excluded from + * provisioning. This typically occurs only for free sites. + * @return The RuntimeAvailabilityState value. + */ + public WebSiteRuntimeAvailabilityState getRuntimeAvailabilityState() { + return this.runtimeAvailabilityState; + } + + /** + * Optional. The current availability state for the web site. Possible + * values are Normal, Degraded, or NotAvailable: Normal: the web site is + * running correctly; Degraded: the web site is running temporarily in a + * degraded mode (typically with less memory and a shared instance); Not + * Available: due to an unexpected issue, the site has been excluded from + * provisioning. This typically occurs only for free sites. + * @param runtimeAvailabilityStateValue The RuntimeAvailabilityState value. + */ + public void setRuntimeAvailabilityState(final WebSiteRuntimeAvailabilityState runtimeAvailabilityStateValue) { + this.runtimeAvailabilityState = runtimeAvailabilityStateValue; + } + + private String serverFarm; + + /** + * Optional. A string defining the web site server farm. If a server farm + * exists, this value is DefaultServerFarm. + * @return The ServerFarm value. + */ + public String getServerFarm() { + return this.serverFarm; + } + + /** + * Optional. A string defining the web site server farm. If a server farm + * exists, this value is DefaultServerFarm. + * @param serverFarmValue The ServerFarm value. + */ + public void setServerFarm(final String serverFarmValue) { + this.serverFarm = serverFarmValue; + } + + private WebSiteMode siteMode; + + /** + * Optional. A string representing the web site mode. If the web site mode + * is Free, this value is Limited. If the web site mode is Shared, this + * value is Basic. Note: The SiteMode value is not used for Reserved mode. + * Reserved mode uses the ComputeMode setting. + * @return The SiteMode value. + */ + public WebSiteMode getSiteMode() { + return this.siteMode; + } + + /** + * Optional. A string representing the web site mode. If the web site mode + * is Free, this value is Limited. If the web site mode is Shared, this + * value is Basic. Note: The SiteMode value is not used for Reserved mode. + * Reserved mode uses the ComputeMode setting. + * @param siteModeValue The SiteMode value. + */ + public void setSiteMode(final WebSiteMode siteModeValue) { + this.siteMode = siteModeValue; + } + + private WebSite.WebSiteProperties siteProperties; + + /** + * Optional. The web site properties of the web site. Contains AppSettings, + * Metadata, and Properties. + * @return The SiteProperties value. + */ + public WebSite.WebSiteProperties getSiteProperties() { + return this.siteProperties; + } + + /** + * Optional. The web site properties of the web site. Contains AppSettings, + * Metadata, and Properties. + * @param sitePropertiesValue The SiteProperties value. + */ + public void setSiteProperties(final WebSite.WebSiteProperties sitePropertiesValue) { + this.siteProperties = sitePropertiesValue; + } + + private ArrayList sslCertificates; + + /** + * Optional. SSL certificates bound to the web site. + * @return The SslCertificates value. + */ + public ArrayList getSslCertificates() { + return this.sslCertificates; + } + + /** + * Optional. SSL certificates bound to the web site. + * @param sslCertificatesValue The SslCertificates value. + */ + public void setSslCertificates(final ArrayList sslCertificatesValue) { + this.sslCertificates = sslCertificatesValue; + } + + private String state; + + /** + * Optional. A string that describes the state of the web site. Possible + * values are Stopped or Running. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. A string that describes the state of the web site. Possible + * values are Stopped or Running. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + private URI uri; + + /** + * Optional. Direct URL to the web site endpoint on Azure Web Sites, + * including the subscription ID, web space name, and web site name. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. Direct URL to the web site endpoint on Azure Web Sites, + * including the subscription ID, web space name, and web site name. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + + private WebSiteUsageState usageState; + + /** + * Optional. The usage state of the web site. Possible values are Normal or + * Exceeded. If any quota is exceeded, the UsageState value changes to + * Exceeded and the site goes offline. + * @return The UsageState value. + */ + public WebSiteUsageState getUsageState() { + return this.usageState; + } + + /** + * Optional. The usage state of the web site. Possible values are Normal or + * Exceeded. If any quota is exceeded, the UsageState value changes to + * Exceeded and the site goes offline. + * @param usageStateValue The UsageState value. + */ + public void setUsageState(final WebSiteUsageState usageStateValue) { + this.usageState = usageStateValue; + } + + private String webSpace; + + /** + * Optional. The name of the web space in which the web site is located. + * This property is read-only. + * @return The WebSpace value. + */ + public String getWebSpace() { + return this.webSpace; + } + + /** + * Optional. The name of the web space in which the web site is located. + * This property is read-only. + * @param webSpaceValue The WebSpace value. + */ + public void setWebSpace(final String webSpaceValue) { + this.webSpace = webSpaceValue; + } + + /** + * Initializes a new instance of the WebSite class. + * + */ + public WebSite() { + this.enabledHostNames = new ArrayList(); + this.hostNames = new ArrayList(); + this.hostNameSslStates = new ArrayList(); + this.sslCertificates = new ArrayList(); + } + + /** + * SSL state bound to a web site. + */ + public static class WebSiteHostNameSslState { + private String name; + + /** + * Optional. The URL of the web site. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The URL of the web site. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private WebSiteSslState sslState; + + /** + * Optional. The SSL state. Possible values are Disabled, SniEnabled, or + * IpBasedEnabled. + * @return The SslState value. + */ + public WebSiteSslState getSslState() { + return this.sslState; + } + + /** + * Optional. The SSL state. Possible values are Disabled, SniEnabled, or + * IpBasedEnabled. + * @param sslStateValue The SslState value. + */ + public void setSslState(final WebSiteSslState sslStateValue) { + this.sslState = sslStateValue; + } + + private String thumbprint; + + /** + * Optional. A string containing the thumbprint of the SSL certificate. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. A string containing the thumbprint of the SSL certificate. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private InetAddress virtualIP; + + /** + * Optional. A string containing the IP address assigned to the hostname + * if the hostname uses IP SSL. + * @return The VirtualIP value. + */ + public InetAddress getVirtualIP() { + return this.virtualIP; + } + + /** + * Optional. A string containing the IP address assigned to the hostname + * if the hostname uses IP SSL. + * @param virtualIPValue The VirtualIP value. + */ + public void setVirtualIP(final InetAddress virtualIPValue) { + this.virtualIP = virtualIPValue; + } + } + + public static class WebSiteProperties { + private HashMap appSettings; + + /** + * Optional. A set of name/value pairs that contain application settings + * for a web site. + * @return The AppSettings value. + */ + public HashMap getAppSettings() { + return this.appSettings; + } + + /** + * Optional. A set of name/value pairs that contain application settings + * for a web site. + * @param appSettingsValue The AppSettings value. + */ + public void setAppSettings(final HashMap appSettingsValue) { + this.appSettings = appSettingsValue; + } + + private HashMap metadata; + + /** + * Optional. A set of name/value pairs that contain metadata information + * for a web site. + * @return The Metadata value. + */ + public HashMap getMetadata() { + return this.metadata; + } + + /** + * Optional. A set of name/value pairs that contain metadata information + * for a web site. + * @param metadataValue The Metadata value. + */ + public void setMetadata(final HashMap metadataValue) { + this.metadata = metadataValue; + } + + private HashMap properties; + + /** + * Optional. A set of name/value pairs that contain properties for a web + * site. + * @return The Properties value. + */ + public HashMap getProperties() { + return this.properties; + } + + /** + * Optional. A set of name/value pairs that contain properties for a web + * site. + * @param propertiesValue The Properties value. + */ + public void setProperties(final HashMap propertiesValue) { + this.properties = propertiesValue; + } + + /** + * Initializes a new instance of the WebSiteProperties class. + * + */ + public WebSiteProperties() { + this.appSettings = new HashMap(); + this.metadata = new HashMap(); + this.properties = new HashMap(); + } + } + + /** + * The SSL certificate properties. + */ + public static class WebSiteSslCertificate { + private Calendar expirationDate; + + /** + * Optional. A dateTime value that contains the expiration date of the + * certificate. + * @return The ExpirationDate value. + */ + public Calendar getExpirationDate() { + return this.expirationDate; + } + + /** + * Optional. A dateTime value that contains the expiration date of the + * certificate. + * @param expirationDateValue The ExpirationDate value. + */ + public void setExpirationDate(final Calendar expirationDateValue) { + this.expirationDate = expirationDateValue; + } + + private String friendlyName; + + /** + * Optional. A string that contains the friendly name of the certificate. + * @return The FriendlyName value. + */ + public String getFriendlyName() { + return this.friendlyName; + } + + /** + * Optional. A string that contains the friendly name of the certificate. + * @param friendlyNameValue The FriendlyName value. + */ + public void setFriendlyName(final String friendlyNameValue) { + this.friendlyName = friendlyNameValue; + } + + private ArrayList hostNames; + + /** + * Optional. An array of strings that contain the host names to which + * the certificate is bound. + * @return The HostNames value. + */ + public ArrayList getHostNames() { + return this.hostNames; + } + + /** + * Optional. An array of strings that contain the host names to which + * the certificate is bound. + * @param hostNamesValue The HostNames value. + */ + public void setHostNames(final ArrayList hostNamesValue) { + this.hostNames = hostNamesValue; + } + + private Calendar issueDate; + + /** + * Optional. A dateTime value that contains the date that the + * certificate was issued. + * @return The IssueDate value. + */ + public Calendar getIssueDate() { + return this.issueDate; + } + + /** + * Optional. A dateTime value that contains the date that the + * certificate was issued. + * @param issueDateValue The IssueDate value. + */ + public void setIssueDate(final Calendar issueDateValue) { + this.issueDate = issueDateValue; + } + + private String issuer; + + /** + * Optional. A string that identifies the issuer of the certificate. + * @return The Issuer value. + */ + public String getIssuer() { + return this.issuer; + } + + /** + * Optional. A string that identifies the issuer of the certificate. + * @param issuerValue The Issuer value. + */ + public void setIssuer(final String issuerValue) { + this.issuer = issuerValue; + } + + private Boolean isToBeDeleted; + + /** + * Optional. Indicates if the certificate is to be deleted. + * @return The IsToBeDeleted value. + */ + public Boolean isToBeDeleted() { + return this.isToBeDeleted; + } + + /** + * Optional. Indicates if the certificate is to be deleted. + * @param isToBeDeletedValue The IsToBeDeleted value. + */ + public void setIsToBeDeleted(final Boolean isToBeDeletedValue) { + this.isToBeDeleted = isToBeDeletedValue; + } + + private Boolean isValid; + + /** + * Optional. Indicates if the certificate is valid. + * @return The IsValid value. + */ + public Boolean isValid() { + return this.isValid; + } + + /** + * Optional. Indicates if the certificate is valid. + * @param isValidValue The IsValid value. + */ + public void setIsValid(final Boolean isValidValue) { + this.isValid = isValidValue; + } + + private String password; + + /** + * Optional. A string that contains the password for the certificate. + * @return The Password value. + */ + public String getPassword() { + return this.password; + } + + /** + * Optional. A string that contains the password for the certificate. + * @param passwordValue The Password value. + */ + public void setPassword(final String passwordValue) { + this.password = passwordValue; + } + + private byte[] pfxBlob; + + /** + * Optional. A base64Binary value that contains the PfxBlob of the + * certificate. + * @return The PfxBlob value. + */ + public byte[] getPfxBlob() { + return this.pfxBlob; + } + + /** + * Optional. A base64Binary value that contains the PfxBlob of the + * certificate. + * @param pfxBlobValue The PfxBlob value. + */ + public void setPfxBlob(final byte[] pfxBlobValue) { + this.pfxBlob = pfxBlobValue; + } + + private URI selfLinkUri; + + /** + * Optional. An anyURI value that contains the endpoint of the site to + * which the certificate is bound. + * @return The SelfLinkUri value. + */ + public URI getSelfLinkUri() { + return this.selfLinkUri; + } + + /** + * Optional. An anyURI value that contains the endpoint of the site to + * which the certificate is bound. + * @param selfLinkUriValue The SelfLinkUri value. + */ + public void setSelfLinkUri(final URI selfLinkUriValue) { + this.selfLinkUri = selfLinkUriValue; + } + + private String siteName; + + /** + * Optional. A string that contains the name of the site to which the + * certificate is bound. + * @return The SiteName value. + */ + public String getSiteName() { + return this.siteName; + } + + /** + * Optional. A string that contains the name of the site to which the + * certificate is bound. + * @param siteNameValue The SiteName value. + */ + public void setSiteName(final String siteNameValue) { + this.siteName = siteNameValue; + } + + private String subjectName; + + /** + * Optional. A string that contains the name of the entity to whom the + * certificate was issued. + * @return The SubjectName value. + */ + public String getSubjectName() { + return this.subjectName; + } + + /** + * Optional. A string that contains the name of the entity to whom the + * certificate was issued. + * @param subjectNameValue The SubjectName value. + */ + public void setSubjectName(final String subjectNameValue) { + this.subjectName = subjectNameValue; + } + + private String thumbprint; + + /** + * Optional. A string that contains the certificate thumbprint. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. A string that contains the certificate thumbprint. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + /** + * Initializes a new instance of the WebSiteSslCertificate class. + * + */ + public WebSiteSslCertificate() { + this.hostNames = new ArrayList(); + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteComputeMode.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteComputeMode.java new file mode 100644 index 0000000000000..101fa3a95aaf0 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteComputeMode.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The compute mode for a web site. +*/ +public enum WebSiteComputeMode { + Shared, + + Dedicated, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteCreateParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteCreateParameters.java new file mode 100644 index 0000000000000..9f746827e25c0 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteCreateParameters.java @@ -0,0 +1,250 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import java.util.ArrayList; + +/** +* Parameters supplied to the Create Web Site operation. +*/ +public class WebSiteCreateParameters { + private WebSiteComputeMode computeMode; + + /** + * Optional. The compute mode for the web site. This value should be Shared + * for the Free or Paid Shared offerings or Dedicated for the Standard + * offering. The default value is Shared. If you set ComputeMode to + * Dedicated, you must specify a value for the ServerFarm element. + * @return The ComputeMode value. + */ + public WebSiteComputeMode getComputeMode() { + return this.computeMode; + } + + /** + * Optional. The compute mode for the web site. This value should be Shared + * for the Free or Paid Shared offerings or Dedicated for the Standard + * offering. The default value is Shared. If you set ComputeMode to + * Dedicated, you must specify a value for the ServerFarm element. + * @param computeModeValue The ComputeMode value. + */ + public void setComputeMode(final WebSiteComputeMode computeModeValue) { + this.computeMode = computeModeValue; + } + + private ArrayList hostNames; + + /** + * Optional. The fully qualified domain name for web site. Only one host + * name can be specified in the azurewebsites.net domain. The host name + * should match the name of the web site. Custom domains can only be + * specified for Shared or Standard web sites. + * @return The HostNames value. + */ + public ArrayList getHostNames() { + return this.hostNames; + } + + /** + * Optional. The fully qualified domain name for web site. Only one host + * name can be specified in the azurewebsites.net domain. The host name + * should match the name of the web site. Custom domains can only be + * specified for Shared or Standard web sites. + * @param hostNamesValue The HostNames value. + */ + public void setHostNames(final ArrayList hostNamesValue) { + this.hostNames = hostNamesValue; + } + + private String name; + + /** + * Required. The name of the web site. This should match the host name in + * the default domain. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. The name of the web site. This should match the host name in + * the default domain. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String serverFarm; + + /** + * Optional. The name of the Server Farm associated with this web site. This + * is a required value for Standard mode. + * @return The ServerFarm value. + */ + public String getServerFarm() { + return this.serverFarm; + } + + /** + * Optional. The name of the Server Farm associated with this web site. This + * is a required value for Standard mode. + * @param serverFarmValue The ServerFarm value. + */ + public void setServerFarm(final String serverFarmValue) { + this.serverFarm = serverFarmValue; + } + + private WebSiteMode siteMode; + + /** + * Optional. The web site mode. This value is Limited for the Free offering + * and Basic for the Paid and Shared offerings. The default value is + * Limited. Note: Standard mode does not use the SiteMode setting; it uses + * the ComputeMode setting. For more information, see Upgrade or Downgrade + * a Web Site. + * @return The SiteMode value. + */ + public WebSiteMode getSiteMode() { + return this.siteMode; + } + + /** + * Optional. The web site mode. This value is Limited for the Free offering + * and Basic for the Paid and Shared offerings. The default value is + * Limited. Note: Standard mode does not use the SiteMode setting; it uses + * the ComputeMode setting. For more information, see Upgrade or Downgrade + * a Web Site. + * @param siteModeValue The SiteMode value. + */ + public void setSiteMode(final WebSiteMode siteModeValue) { + this.siteMode = siteModeValue; + } + + private WebSiteCreateParameters.WebSpaceDetails webSpace; + + /** + * Optional. Information about the web space to create. + * @return The WebSpace value. + */ + public WebSiteCreateParameters.WebSpaceDetails getWebSpace() { + return this.webSpace; + } + + /** + * Optional. Information about the web space to create. + * @param webSpaceValue The WebSpace value. + */ + public void setWebSpace(final WebSiteCreateParameters.WebSpaceDetails webSpaceValue) { + this.webSpace = webSpaceValue; + } + + private String webSpaceName; + + /** + * Required. The name of the web space. + * @return The WebSpaceName value. + */ + public String getWebSpaceName() { + return this.webSpaceName; + } + + /** + * Required. The name of the web space. + * @param webSpaceNameValue The WebSpaceName value. + */ + public void setWebSpaceName(final String webSpaceNameValue) { + this.webSpaceName = webSpaceNameValue; + } + + /** + * Initializes a new instance of the WebSiteCreateParameters class. + * + */ + public WebSiteCreateParameters() { + this.hostNames = new ArrayList(); + } + + /** + * Information about the web space to create. + */ + public static class WebSpaceDetails { + private String geoRegion; + + /** + * Required. The geographical region of the web space that will be + * created. + * @return The GeoRegion value. + */ + public String getGeoRegion() { + return this.geoRegion; + } + + /** + * Required. The geographical region of the web space that will be + * created. + * @param geoRegionValue The GeoRegion value. + */ + public void setGeoRegion(final String geoRegionValue) { + this.geoRegion = geoRegionValue; + } + + private String name; + + /** + * Required. The name of the web space. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. The name of the web space. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String plan; + + /** + * Required. The web space plan. This value must be VirtualDedicatedPlan. + * @return The Plan value. + */ + public String getPlan() { + return this.plan; + } + + /** + * Required. The web space plan. This value must be VirtualDedicatedPlan. + * @param planValue The Plan value. + */ + public void setPlan(final String planValue) { + this.plan = planValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteCreateResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteCreateResponse.java new file mode 100644 index 0000000000000..ed019eea14142 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteCreateResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Create Web Site operation response. +*/ +public class WebSiteCreateResponse extends OperationResponse { + private WebSite webSite; + + /** + * Optional. Details of the created web site. + * @return The WebSite value. + */ + public WebSite getWebSite() { + return this.webSite; + } + + /** + * Optional. Details of the created web site. + * @param webSiteValue The WebSite value. + */ + public void setWebSite(final WebSite webSiteValue) { + this.webSite = webSiteValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteDeleteParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteDeleteParameters.java new file mode 100644 index 0000000000000..d4c393bf3a544 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteDeleteParameters.java @@ -0,0 +1,87 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* Parameters supplied to the Delete Web Site operation. +*/ +public class WebSiteDeleteParameters { + private boolean deleteAllSlots; + + /** + * Required. Indicates if all slots for the web site should be deleted. + * @return The DeleteAllSlots value. + */ + public boolean isDeleteAllSlots() { + return this.deleteAllSlots; + } + + /** + * Required. Indicates if all slots for the web site should be deleted. + * @param deleteAllSlotsValue The DeleteAllSlots value. + */ + public void setDeleteAllSlots(final boolean deleteAllSlotsValue) { + this.deleteAllSlots = deleteAllSlotsValue; + } + + private boolean deleteEmptyServerFarm; + + /** + * Required. Indicates if the server farm should be deleted. You can delete + * the server farm if the web site being deleted is the last web site in a + * server farm. + * @return The DeleteEmptyServerFarm value. + */ + public boolean isDeleteEmptyServerFarm() { + return this.deleteEmptyServerFarm; + } + + /** + * Required. Indicates if the server farm should be deleted. You can delete + * the server farm if the web site being deleted is the last web site in a + * server farm. + * @param deleteEmptyServerFarmValue The DeleteEmptyServerFarm value. + */ + public void setDeleteEmptyServerFarm(final boolean deleteEmptyServerFarmValue) { + this.deleteEmptyServerFarm = deleteEmptyServerFarmValue; + } + + private boolean deleteMetrics; + + /** + * Required. Indicates if the metrics for the web site should be deleted. + * @return The DeleteMetrics value. + */ + public boolean isDeleteMetrics() { + return this.deleteMetrics; + } + + /** + * Required. Indicates if the metrics for the web site should be deleted. + * @param deleteMetricsValue The DeleteMetrics value. + */ + public void setDeleteMetrics(final boolean deleteMetricsValue) { + this.deleteMetrics = deleteMetricsValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteDeleteRepositoryResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteDeleteRepositoryResponse.java new file mode 100644 index 0000000000000..daf87679395fc --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteDeleteRepositoryResponse.java @@ -0,0 +1,50 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* The Delete Repository Web Site operation response. +*/ +public class WebSiteDeleteRepositoryResponse extends OperationResponse { + private URI uri; + + /** + * Optional. The URI of the web site repository. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The URI of the web site repository. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetConfigurationResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetConfigurationResponse.java new file mode 100644 index 0000000000000..4ff2a8c4319cb --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetConfigurationResponse.java @@ -0,0 +1,606 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; + +/** +* The Get Configuration Web Site operation response. +*/ +public class WebSiteGetConfigurationResponse extends OperationResponse { + private HashMap appSettings; + + /** + * Optional. A set of name/value pairs that contain application settings for + * a web site. + * @return The AppSettings value. + */ + public HashMap getAppSettings() { + return this.appSettings; + } + + /** + * Optional. A set of name/value pairs that contain application settings for + * a web site. + * @param appSettingsValue The AppSettings value. + */ + public void setAppSettings(final HashMap appSettingsValue) { + this.appSettings = appSettingsValue; + } + + private ArrayList connectionStrings; + + /** + * Optional. The connection strings for database and other external + * resources. + * @return The ConnectionStrings value. + */ + public ArrayList getConnectionStrings() { + return this.connectionStrings; + } + + /** + * Optional. The connection strings for database and other external + * resources. + * @param connectionStringsValue The ConnectionStrings value. + */ + public void setConnectionStrings(final ArrayList connectionStringsValue) { + this.connectionStrings = connectionStringsValue; + } + + private ArrayList defaultDocuments; + + /** + * Optional. One or more string elements that list, in order of preference, + * the name of the file that a web site returns when the web site's domain + * name is requested by itself. For example, if the default document for + * http://contoso.com is default.htm, the page + * http://www.contoso.com/default.htm is returned when the browser is + * pointed to http://www.contoso.com. + * @return The DefaultDocuments value. + */ + public ArrayList getDefaultDocuments() { + return this.defaultDocuments; + } + + /** + * Optional. One or more string elements that list, in order of preference, + * the name of the file that a web site returns when the web site's domain + * name is requested by itself. For example, if the default document for + * http://contoso.com is default.htm, the page + * http://www.contoso.com/default.htm is returned when the browser is + * pointed to http://www.contoso.com. + * @param defaultDocumentsValue The DefaultDocuments value. + */ + public void setDefaultDocuments(final ArrayList defaultDocumentsValue) { + this.defaultDocuments = defaultDocumentsValue; + } + + private Boolean detailedErrorLoggingEnabled; + + /** + * Optional. Indicates if detailed error logging is enabled. + * @return The DetailedErrorLoggingEnabled value. + */ + public Boolean isDetailedErrorLoggingEnabled() { + return this.detailedErrorLoggingEnabled; + } + + /** + * Optional. Indicates if detailed error logging is enabled. + * @param detailedErrorLoggingEnabledValue The DetailedErrorLoggingEnabled + * value. + */ + public void setDetailedErrorLoggingEnabled(final Boolean detailedErrorLoggingEnabledValue) { + this.detailedErrorLoggingEnabled = detailedErrorLoggingEnabledValue; + } + + private String documentRoot; + + /** + * Optional. The document root. + * @return The DocumentRoot value. + */ + public String getDocumentRoot() { + return this.documentRoot; + } + + /** + * Optional. The document root. + * @param documentRootValue The DocumentRoot value. + */ + public void setDocumentRoot(final String documentRootValue) { + this.documentRoot = documentRootValue; + } + + private ArrayList handlerMappings; + + /** + * Optional. Specifies custom executable programs for handling requests for + * specific file name extensions. + * @return The HandlerMappings value. + */ + public ArrayList getHandlerMappings() { + return this.handlerMappings; + } + + /** + * Optional. Specifies custom executable programs for handling requests for + * specific file name extensions. + * @param handlerMappingsValue The HandlerMappings value. + */ + public void setHandlerMappings(final ArrayList handlerMappingsValue) { + this.handlerMappings = handlerMappingsValue; + } + + private Boolean httpLoggingEnabled; + + /** + * Optional. Indicates if HTTP error logging is enabled. + * @return The HttpLoggingEnabled value. + */ + public Boolean isHttpLoggingEnabled() { + return this.httpLoggingEnabled; + } + + /** + * Optional. Indicates if HTTP error logging is enabled. + * @param httpLoggingEnabledValue The HttpLoggingEnabled value. + */ + public void setHttpLoggingEnabled(final Boolean httpLoggingEnabledValue) { + this.httpLoggingEnabled = httpLoggingEnabledValue; + } + + private Integer logsDirectorySizeLimit; + + /** + * Optional. The size limit of the logs directory. + * @return The LogsDirectorySizeLimit value. + */ + public Integer getLogsDirectorySizeLimit() { + return this.logsDirectorySizeLimit; + } + + /** + * Optional. The size limit of the logs directory. + * @param logsDirectorySizeLimitValue The LogsDirectorySizeLimit value. + */ + public void setLogsDirectorySizeLimit(final Integer logsDirectorySizeLimitValue) { + this.logsDirectorySizeLimit = logsDirectorySizeLimitValue; + } + + private ManagedPipelineMode managedPipelineMode; + + /** + * Optional. The managed pipeline mode. + * @return The ManagedPipelineMode value. + */ + public ManagedPipelineMode getManagedPipelineMode() { + return this.managedPipelineMode; + } + + /** + * Optional. The managed pipeline mode. + * @param managedPipelineModeValue The ManagedPipelineMode value. + */ + public void setManagedPipelineMode(final ManagedPipelineMode managedPipelineModeValue) { + this.managedPipelineMode = managedPipelineModeValue; + } + + private HashMap metadata; + + /** + * Optional. Name/value pairs for source control or other information. + * @return The Metadata value. + */ + public HashMap getMetadata() { + return this.metadata; + } + + /** + * Optional. Name/value pairs for source control or other information. + * @param metadataValue The Metadata value. + */ + public void setMetadata(final HashMap metadataValue) { + this.metadata = metadataValue; + } + + private String netFrameworkVersion; + + /** + * Optional. The .NET Framework version. Supported values are v2.0 and v4.0. + * @return The NetFrameworkVersion value. + */ + public String getNetFrameworkVersion() { + return this.netFrameworkVersion; + } + + /** + * Optional. The .NET Framework version. Supported values are v2.0 and v4.0. + * @param netFrameworkVersionValue The NetFrameworkVersion value. + */ + public void setNetFrameworkVersion(final String netFrameworkVersionValue) { + this.netFrameworkVersion = netFrameworkVersionValue; + } + + private Integer numberOfWorkers; + + /** + * Optional. The number of web workers allotted to the web site. If the web + * site mode is Free, this value is 1. If the web site mode is Shared, this + * value can range from 1 through 6. If the web site mode is Standard, this + * value can range from 1 through 10. + * @return The NumberOfWorkers value. + */ + public Integer getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Optional. The number of web workers allotted to the web site. If the web + * site mode is Free, this value is 1. If the web site mode is Shared, this + * value can range from 1 through 6. If the web site mode is Standard, this + * value can range from 1 through 10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final Integer numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private String phpVersion; + + /** + * Optional. The web site PHP version. Supported values are an empty string + * (an empty string disables PHP), 5.3, and 5.4. + * @return The PhpVersion value. + */ + public String getPhpVersion() { + return this.phpVersion; + } + + /** + * Optional. The web site PHP version. Supported values are an empty string + * (an empty string disables PHP), 5.3, and 5.4. + * @param phpVersionValue The PhpVersion value. + */ + public void setPhpVersion(final String phpVersionValue) { + this.phpVersion = phpVersionValue; + } + + private String publishingPassword; + + /** + * Optional. Hash value of the password used for publishing the web site. + * @return The PublishingPassword value. + */ + public String getPublishingPassword() { + return this.publishingPassword; + } + + /** + * Optional. Hash value of the password used for publishing the web site. + * @param publishingPasswordValue The PublishingPassword value. + */ + public void setPublishingPassword(final String publishingPasswordValue) { + this.publishingPassword = publishingPasswordValue; + } + + private String publishingUserName; + + /** + * Optional. The user name used for publishing the web site. This is + * normally a dollar sign prepended to the web site name (for example, + * "$contoso"). + * @return The PublishingUserName value. + */ + public String getPublishingUserName() { + return this.publishingUserName; + } + + /** + * Optional. The user name used for publishing the web site. This is + * normally a dollar sign prepended to the web site name (for example, + * "$contoso"). + * @param publishingUserNameValue The PublishingUserName value. + */ + public void setPublishingUserName(final String publishingUserNameValue) { + this.publishingUserName = publishingUserNameValue; + } + + private Boolean remoteDebuggingEnabled; + + /** + * Optional. Indicates if remote debugging is enabled. + * @return The RemoteDebuggingEnabled value. + */ + public Boolean isRemoteDebuggingEnabled() { + return this.remoteDebuggingEnabled; + } + + /** + * Optional. Indicates if remote debugging is enabled. + * @param remoteDebuggingEnabledValue The RemoteDebuggingEnabled value. + */ + public void setRemoteDebuggingEnabled(final Boolean remoteDebuggingEnabledValue) { + this.remoteDebuggingEnabled = remoteDebuggingEnabledValue; + } + + private RemoteDebuggingVersion remoteDebuggingVersion; + + /** + * Optional. The remote debugging version. + * @return The RemoteDebuggingVersion value. + */ + public RemoteDebuggingVersion getRemoteDebuggingVersion() { + return this.remoteDebuggingVersion; + } + + /** + * Optional. The remote debugging version. + * @param remoteDebuggingVersionValue The RemoteDebuggingVersion value. + */ + public void setRemoteDebuggingVersion(final RemoteDebuggingVersion remoteDebuggingVersionValue) { + this.remoteDebuggingVersion = remoteDebuggingVersionValue; + } + + private Boolean requestTracingEnabled; + + /** + * Optional. Indicates if request tracing is enabled. + * @return The RequestTracingEnabled value. + */ + public Boolean isRequestTracingEnabled() { + return this.requestTracingEnabled; + } + + /** + * Optional. Indicates if request tracing is enabled. + * @param requestTracingEnabledValue The RequestTracingEnabled value. + */ + public void setRequestTracingEnabled(final Boolean requestTracingEnabledValue) { + this.requestTracingEnabled = requestTracingEnabledValue; + } + + private Calendar requestTracingExpirationTime; + + /** + * Optional. Time remaining until request tracing expires. + * @return The RequestTracingExpirationTime value. + */ + public Calendar getRequestTracingExpirationTime() { + return this.requestTracingExpirationTime; + } + + /** + * Optional. Time remaining until request tracing expires. + * @param requestTracingExpirationTimeValue The RequestTracingExpirationTime + * value. + */ + public void setRequestTracingExpirationTime(final Calendar requestTracingExpirationTimeValue) { + this.requestTracingExpirationTime = requestTracingExpirationTimeValue; + } + + private String scmType; + + /** + * Optional. The source control method that the web site is using (for + * example, Local Git). If deployment from source control has not been set + * up for the web site, this value is None. + * @return The ScmType value. + */ + public String getScmType() { + return this.scmType; + } + + /** + * Optional. The source control method that the web site is using (for + * example, Local Git). If deployment from source control has not been set + * up for the web site, this value is None. + * @param scmTypeValue The ScmType value. + */ + public void setScmType(final String scmTypeValue) { + this.scmType = scmTypeValue; + } + + private Boolean use32BitWorkerProcess; + + /** + * Optional. Indicates if 32-bit mode is enabled. + * @return The Use32BitWorkerProcess value. + */ + public Boolean isUse32BitWorkerProcess() { + return this.use32BitWorkerProcess; + } + + /** + * Optional. Indicates if 32-bit mode is enabled. + * @param use32BitWorkerProcessValue The Use32BitWorkerProcess value. + */ + public void setUse32BitWorkerProcess(final Boolean use32BitWorkerProcessValue) { + this.use32BitWorkerProcess = use32BitWorkerProcessValue; + } + + private Boolean webSocketsEnabled; + + /** + * Optional. Indicates if Web Sockets are enabled. + * @return The WebSocketsEnabled value. + */ + public Boolean isWebSocketsEnabled() { + return this.webSocketsEnabled; + } + + /** + * Optional. Indicates if Web Sockets are enabled. + * @param webSocketsEnabledValue The WebSocketsEnabled value. + */ + public void setWebSocketsEnabled(final Boolean webSocketsEnabledValue) { + this.webSocketsEnabled = webSocketsEnabledValue; + } + + /** + * Initializes a new instance of the WebSiteGetConfigurationResponse class. + * + */ + public WebSiteGetConfigurationResponse() { + super(); + this.appSettings = new HashMap(); + this.connectionStrings = new ArrayList(); + this.defaultDocuments = new ArrayList(); + this.handlerMappings = new ArrayList(); + this.metadata = new HashMap(); + } + + /** + * Connection string for database and other external resources. + */ + public static class ConnectionStringInfo { + private String connectionString; + + /** + * Optional. The database connection string. + * @return The ConnectionString value. + */ + public String getConnectionString() { + return this.connectionString; + } + + /** + * Optional. The database connection string. + * @param connectionStringValue The ConnectionString value. + */ + public void setConnectionString(final String connectionStringValue) { + this.connectionString = connectionStringValue; + } + + private String name; + + /** + * Optional. The name of the connection string. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the connection string. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String type; + + /** + * Optional. The type of the connection string (for example, "MySQL"). + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. The type of the connection string (for example, "MySQL"). + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + } + + /** + * Specifies a custom executable program for handling requests for specific + * file name extensions. + */ + public static class HandlerMapping { + private String arguments; + + /** + * Optional. A string that contains optional arguments for the script + * processor specified by the + * SiteConfig.HandlerMappings.HandlerMapping.ScriptProcessor element. + * @return The Arguments value. + */ + public String getArguments() { + return this.arguments; + } + + /** + * Optional. A string that contains optional arguments for the script + * processor specified by the + * SiteConfig.HandlerMappings.HandlerMapping.ScriptProcessor element. + * @param argumentsValue The Arguments value. + */ + public void setArguments(final String argumentsValue) { + this.arguments = argumentsValue; + } + + private String extension; + + /** + * Optional. A string that specifies the extension of the file type that + * the script processor will handle (for example, *.php). + * @return The Extension value. + */ + public String getExtension() { + return this.extension; + } + + /** + * Optional. A string that specifies the extension of the file type that + * the script processor will handle (for example, *.php). + * @param extensionValue The Extension value. + */ + public void setExtension(final String extensionValue) { + this.extension = extensionValue; + } + + private String scriptProcessor; + + /** + * Optional. The absolute path to the location of the executable file + * that will handle the files specified in the + * SiteConfig.HandlerMappings.HandlerMapping.Extension element. + * @return The ScriptProcessor value. + */ + public String getScriptProcessor() { + return this.scriptProcessor; + } + + /** + * Optional. The absolute path to the location of the executable file + * that will handle the files specified in the + * SiteConfig.HandlerMappings.HandlerMapping.Extension element. + * @param scriptProcessorValue The ScriptProcessor value. + */ + public void setScriptProcessor(final String scriptProcessorValue) { + this.scriptProcessor = scriptProcessorValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetHistoricalUsageMetricsParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetHistoricalUsageMetricsParameters.java new file mode 100644 index 0000000000000..cab32820ed617 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetHistoricalUsageMetricsParameters.java @@ -0,0 +1,103 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import java.util.ArrayList; +import java.util.Calendar; + +/** +* Parameters supplied to the Get Historical Usage Metrics Web Site operation. +*/ +public class WebSiteGetHistoricalUsageMetricsParameters { + private Calendar endTime; + + /** + * Optional. The ending time of the metrics to return. If this parameter is + * not specified, the current time is used. + * @return The EndTime value. + */ + public Calendar getEndTime() { + return this.endTime; + } + + /** + * Optional. The ending time of the metrics to return. If this parameter is + * not specified, the current time is used. + * @param endTimeValue The EndTime value. + */ + public void setEndTime(final Calendar endTimeValue) { + this.endTime = endTimeValue; + } + + private ArrayList metricNames; + + /** + * Optional. Specifies a comma-separated list of the names of the metrics to + * return. If the names parameter is not specified, then all available + * metrics are returned. + * @return The MetricNames value. + */ + public ArrayList getMetricNames() { + return this.metricNames; + } + + /** + * Optional. Specifies a comma-separated list of the names of the metrics to + * return. If the names parameter is not specified, then all available + * metrics are returned. + * @param metricNamesValue The MetricNames value. + */ + public void setMetricNames(final ArrayList metricNamesValue) { + this.metricNames = metricNamesValue; + } + + private Calendar startTime; + + /** + * Optional. The starting time of the metrics to return. If this parameter + * is not specified, the beginning of the current hour is used. + * @return The StartTime value. + */ + public Calendar getStartTime() { + return this.startTime; + } + + /** + * Optional. The starting time of the metrics to return. If this parameter + * is not specified, the beginning of the current hour is used. + * @param startTimeValue The StartTime value. + */ + public void setStartTime(final Calendar startTimeValue) { + this.startTime = startTimeValue; + } + + /** + * Initializes a new instance of the + * WebSiteGetHistoricalUsageMetricsParameters class. + * + */ + public WebSiteGetHistoricalUsageMetricsParameters() { + this.metricNames = new ArrayList(); + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetHistoricalUsageMetricsResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetHistoricalUsageMetricsResponse.java new file mode 100644 index 0000000000000..848629197d0f4 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetHistoricalUsageMetricsResponse.java @@ -0,0 +1,387 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; + +/** +* The Get Historical Usage Metrics Web Site operation response. +*/ +public class WebSiteGetHistoricalUsageMetricsResponse extends OperationResponse implements Iterable { + private ArrayList usageMetrics; + + /** + * Optional. Historical metric snapshots for the web site. + * @return The UsageMetrics value. + */ + public ArrayList getUsageMetrics() { + return this.usageMetrics; + } + + /** + * Optional. Historical metric snapshots for the web site. + * @param usageMetricsValue The UsageMetrics value. + */ + public void setUsageMetrics(final ArrayList usageMetricsValue) { + this.usageMetrics = usageMetricsValue; + } + + /** + * Initializes a new instance of the + * WebSiteGetHistoricalUsageMetricsResponse class. + * + */ + public WebSiteGetHistoricalUsageMetricsResponse() { + super(); + this.usageMetrics = new ArrayList(); + } + + /** + * Gets the sequence of UsageMetrics. + * + */ + public Iterator iterator() { + return this.getUsageMetrics().iterator(); + } + + /** + * Historical metric snapshot for the web site. + */ + public static class HistoricalUsageMetric { + private String code; + + /** + * Optional. Reports whether the metric data was returned successfully. + * @return The Code value. + */ + public String getCode() { + return this.code; + } + + /** + * Optional. Reports whether the metric data was returned successfully. + * @param codeValue The Code value. + */ + public void setCode(final String codeValue) { + this.code = codeValue; + } + + private WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricData data; + + /** + * Optional. Historical metric snapshot data for the web site. + * @return The Data value. + */ + public WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricData getData() { + return this.data; + } + + /** + * Optional. Historical metric snapshot data for the web site. + * @param dataValue The Data value. + */ + public void setData(final WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricData dataValue) { + this.data = dataValue; + } + + private String message; + + /** + * Optional. A string for optional message content. + * @return The Message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Optional. A string for optional message content. + * @param messageValue The Message value. + */ + public void setMessage(final String messageValue) { + this.message = messageValue; + } + } + + /** + * Historical metric snapshot data for the web site. + */ + public static class HistoricalUsageMetricData { + private String displayName; + + /** + * Optional. The display name of the metric, including spaces. + * @return The DisplayName value. + */ + public String getDisplayName() { + return this.displayName; + } + + /** + * Optional. The display name of the metric, including spaces. + * @param displayNameValue The DisplayName value. + */ + public void setDisplayName(final String displayNameValue) { + this.displayName = displayNameValue; + } + + private Calendar endTime; + + /** + * Optional. The end time of the data reported. + * @return The EndTime value. + */ + public Calendar getEndTime() { + return this.endTime; + } + + /** + * Optional. The end time of the data reported. + * @param endTimeValue The EndTime value. + */ + public void setEndTime(final Calendar endTimeValue) { + this.endTime = endTimeValue; + } + + private String name; + + /** + * Optional. The name of the metric. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the metric. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String primaryAggregationType; + + /** + * Optional. The primary data aggregation type. This value is usually + * Total. + * @return The PrimaryAggregationType value. + */ + public String getPrimaryAggregationType() { + return this.primaryAggregationType; + } + + /** + * Optional. The primary data aggregation type. This value is usually + * Total. + * @param primaryAggregationTypeValue The PrimaryAggregationType value. + */ + public void setPrimaryAggregationType(final String primaryAggregationTypeValue) { + this.primaryAggregationType = primaryAggregationTypeValue; + } + + private Calendar startTime; + + /** + * Optional. The start time of the data reported. + * @return The StartTime value. + */ + public Calendar getStartTime() { + return this.startTime; + } + + /** + * Optional. The start time of the data reported. + * @param startTimeValue The StartTime value. + */ + public void setStartTime(final Calendar startTimeValue) { + this.startTime = startTimeValue; + } + + private String timeGrain; + + /** + * Optional. Length of time (rollup) during which the information was + * gathered. For more information, see Supported Rollups. + * @return The TimeGrain value. + */ + public String getTimeGrain() { + return this.timeGrain; + } + + /** + * Optional. Length of time (rollup) during which the information was + * gathered. For more information, see Supported Rollups. + * @param timeGrainValue The TimeGrain value. + */ + public void setTimeGrain(final String timeGrainValue) { + this.timeGrain = timeGrainValue; + } + + private String unit; + + /** + * Optional. The unit of measurement for the metric (for example, + * milliseconds, bytes, or count). + * @return The Unit value. + */ + public String getUnit() { + return this.unit; + } + + /** + * Optional. The unit of measurement for the metric (for example, + * milliseconds, bytes, or count). + * @param unitValue The Unit value. + */ + public void setUnit(final String unitValue) { + this.unit = unitValue; + } + + private ArrayList values; + + /** + * Optional. One or more MetricSample elements. + * @return The Values value. + */ + public ArrayList getValues() { + return this.values; + } + + /** + * Optional. One or more MetricSample elements. + * @param valuesValue The Values value. + */ + public void setValues(final ArrayList valuesValue) { + this.values = valuesValue; + } + + /** + * Initializes a new instance of the HistoricalUsageMetricData class. + * + */ + public HistoricalUsageMetricData() { + this.values = new ArrayList(); + } + } + + /** + * Historical metric snapshot data sample. + */ + public static class HistoricalUsageMetricSample { + private int count; + + /** + * Optional. The metric sample count. This value is usually 1. + * @return The Count value. + */ + public int getCount() { + return this.count; + } + + /** + * Optional. The metric sample count. This value is usually 1. + * @param countValue The Count value. + */ + public void setCount(final int countValue) { + this.count = countValue; + } + + private String maximum; + + /** + * Optional. Maximum value recorded. + * @return The Maximum value. + */ + public String getMaximum() { + return this.maximum; + } + + /** + * Optional. Maximum value recorded. + * @param maximumValue The Maximum value. + */ + public void setMaximum(final String maximumValue) { + this.maximum = maximumValue; + } + + private String minimum; + + /** + * Optional. Minimum value recorded. + * @return The Minimum value. + */ + public String getMinimum() { + return this.minimum; + } + + /** + * Optional. Minimum value recorded. + * @param minimumValue The Minimum value. + */ + public void setMinimum(final String minimumValue) { + this.minimum = minimumValue; + } + + private Calendar timeCreated; + + /** + * Optional. Time the metric was taken. + * @return The TimeCreated value. + */ + public Calendar getTimeCreated() { + return this.timeCreated; + } + + /** + * Optional. Time the metric was taken. + * @param timeCreatedValue The TimeCreated value. + */ + public void setTimeCreated(final Calendar timeCreatedValue) { + this.timeCreated = timeCreatedValue; + } + + private String total; + + /** + * Optional. Value of the metric sample for the time taken. + * @return The Total value. + */ + public String getTotal() { + return this.total; + } + + /** + * Optional. Value of the metric sample for the time taken. + * @param totalValue The Total value. + */ + public void setTotal(final String totalValue) { + this.total = totalValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetParameters.java new file mode 100644 index 0000000000000..5fd78ebd57647 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetParameters.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import java.util.ArrayList; + +/** +* Parameters supplied to the Get Web Site operation. +*/ +public class WebSiteGetParameters { + private ArrayList propertiesToInclude; + + /** + * Optional. Specifies a list of the names of any addtional parameters to + * return. + * @return The PropertiesToInclude value. + */ + public ArrayList getPropertiesToInclude() { + return this.propertiesToInclude; + } + + /** + * Optional. Specifies a list of the names of any addtional parameters to + * return. + * @param propertiesToIncludeValue The PropertiesToInclude value. + */ + public void setPropertiesToInclude(final ArrayList propertiesToIncludeValue) { + this.propertiesToInclude = propertiesToIncludeValue; + } + + /** + * Initializes a new instance of the WebSiteGetParameters class. + * + */ + public WebSiteGetParameters() { + this.propertiesToInclude = new ArrayList(); + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetPublishProfileResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetPublishProfileResponse.java new file mode 100644 index 0000000000000..a44dbf5da7c4f --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetPublishProfileResponse.java @@ -0,0 +1,406 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The Get Publish Profile Web Site operation response. +*/ +public class WebSiteGetPublishProfileResponse extends OperationResponse implements Iterable { + private ArrayList publishProfiles; + + /** + * Optional. The web site publish profiles. + * @return The PublishProfiles value. + */ + public ArrayList getPublishProfiles() { + return this.publishProfiles; + } + + /** + * Optional. The web site publish profiles. + * @param publishProfilesValue The PublishProfiles value. + */ + public void setPublishProfiles(final ArrayList publishProfilesValue) { + this.publishProfiles = publishProfilesValue; + } + + /** + * Initializes a new instance of the WebSiteGetPublishProfileResponse class. + * + */ + public WebSiteGetPublishProfileResponse() { + super(); + this.publishProfiles = new ArrayList(); + } + + /** + * Gets the sequence of PublishProfiles. + * + */ + public Iterator iterator() { + return this.getPublishProfiles().iterator(); + } + + /** + * Attributes that contain information for a single database connection. + */ + public static class Database { + private String connectionString; + + /** + * Optional. The database connection string. + * @return The ConnectionString value. + */ + public String getConnectionString() { + return this.connectionString; + } + + /** + * Optional. The database connection string. + * @param connectionStringValue The ConnectionString value. + */ + public void setConnectionString(final String connectionStringValue) { + this.connectionString = connectionStringValue; + } + + private String name; + + /** + * Optional. The friendly name of the connection string. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The friendly name of the connection string. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String providerName; + + /** + * Optional. The name of database provider (for example, "SQL" or + * "MySQL"). + * @return The ProviderName value. + */ + public String getProviderName() { + return this.providerName; + } + + /** + * Optional. The name of database provider (for example, "SQL" or + * "MySQL"). + * @param providerNameValue The ProviderName value. + */ + public void setProviderName(final String providerNameValue) { + this.providerName = providerNameValue; + } + + private String type; + + /** + * Optional. The type of database provider. + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. The type of database provider. + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + } + + /** + * Attributes that hold publish profile values. + */ + public static class PublishProfile { + private URI controlPanelUri; + + /** + * Optional. The URL of the control panel for the web site. + * @return The ControlPanelUri value. + */ + public URI getControlPanelUri() { + return this.controlPanelUri; + } + + /** + * Optional. The URL of the control panel for the web site. + * @param controlPanelUriValue The ControlPanelUri value. + */ + public void setControlPanelUri(final URI controlPanelUriValue) { + this.controlPanelUri = controlPanelUriValue; + } + + private ArrayList databases; + + /** + * Optional. Connection information for the databases used by the web + * site application. + * @return The Databases value. + */ + public ArrayList getDatabases() { + return this.databases; + } + + /** + * Optional. Connection information for the databases used by the web + * site application. + * @param databasesValue The Databases value. + */ + public void setDatabases(final ArrayList databasesValue) { + this.databases = databasesValue; + } + + private URI destinationAppUri; + + /** + * Optional. The URL of the web site that will be published to. + * @return The DestinationAppUri value. + */ + public URI getDestinationAppUri() { + return this.destinationAppUri; + } + + /** + * Optional. The URL of the web site that will be published to. + * @param destinationAppUriValue The DestinationAppUri value. + */ + public void setDestinationAppUri(final URI destinationAppUriValue) { + this.destinationAppUri = destinationAppUriValue; + } + + private boolean ftpPassiveMode; + + /** + * Optional. Indicates if FTP passive mode is being used. This attribute + * applies only if publishMethod is set to FTP. + * @return The FtpPassiveMode value. + */ + public boolean isFtpPassiveMode() { + return this.ftpPassiveMode; + } + + /** + * Optional. Indicates if FTP passive mode is being used. This attribute + * applies only if publishMethod is set to FTP. + * @param ftpPassiveModeValue The FtpPassiveMode value. + */ + public void setFtpPassiveMode(final boolean ftpPassiveModeValue) { + this.ftpPassiveMode = ftpPassiveModeValue; + } + + private URI hostingProviderForumUri; + + /** + * Optional. The URL of the forum of the hosting provider. + * @return The HostingProviderForumUri value. + */ + public URI getHostingProviderForumUri() { + return this.hostingProviderForumUri; + } + + /** + * Optional. The URL of the forum of the hosting provider. + * @param hostingProviderForumUriValue The HostingProviderForumUri value. + */ + public void setHostingProviderForumUri(final URI hostingProviderForumUriValue) { + this.hostingProviderForumUri = hostingProviderForumUriValue; + } + + private String mSDeploySite; + + /** + * Optional. The name of the web site that will be published to. This + * attribute applies only if publishMethod is set to MSDeploy. + * @return The MSDeploySite value. + */ + public String getMSDeploySite() { + return this.mSDeploySite; + } + + /** + * Optional. The name of the web site that will be published to. This + * attribute applies only if publishMethod is set to MSDeploy. + * @param mSDeploySiteValue The MSDeploySite value. + */ + public void setMSDeploySite(final String mSDeploySiteValue) { + this.mSDeploySite = mSDeploySiteValue; + } + + private String mySqlConnectionString; + + /** + * Optional. The MySQL database connection string for the web site + * application, if the web site connects to a MySQL database. + * @return The MySqlConnectionString value. + */ + public String getMySqlConnectionString() { + return this.mySqlConnectionString; + } + + /** + * Optional. The MySQL database connection string for the web site + * application, if the web site connects to a MySQL database. + * @param mySqlConnectionStringValue The MySqlConnectionString value. + */ + public void setMySqlConnectionString(final String mySqlConnectionStringValue) { + this.mySqlConnectionString = mySqlConnectionStringValue; + } + + private String profileName; + + /** + * Optional. The unique name of the publish profile. + * @return The ProfileName value. + */ + public String getProfileName() { + return this.profileName; + } + + /** + * Optional. The unique name of the publish profile. + * @param profileNameValue The ProfileName value. + */ + public void setProfileName(final String profileNameValue) { + this.profileName = profileNameValue; + } + + private String publishMethod; + + /** + * Optional. The publish method, such as MSDeploy or FTP. + * @return The PublishMethod value. + */ + public String getPublishMethod() { + return this.publishMethod; + } + + /** + * Optional. The publish method, such as MSDeploy or FTP. + * @param publishMethodValue The PublishMethod value. + */ + public void setPublishMethod(final String publishMethodValue) { + this.publishMethod = publishMethodValue; + } + + private String publishUrl; + + /** + * Optional. The URL to which content will be uploaded. + * @return The PublishUrl value. + */ + public String getPublishUrl() { + return this.publishUrl; + } + + /** + * Optional. The URL to which content will be uploaded. + * @param publishUrlValue The PublishUrl value. + */ + public void setPublishUrl(final String publishUrlValue) { + this.publishUrl = publishUrlValue; + } + + private String sqlServerConnectionString; + + /** + * Optional. The SQL Server database connection string for the web site + * application, if the web site connects to a SQL Server database. + * @return The SqlServerConnectionString value. + */ + public String getSqlServerConnectionString() { + return this.sqlServerConnectionString; + } + + /** + * Optional. The SQL Server database connection string for the web site + * application, if the web site connects to a SQL Server database. + * @param sqlServerConnectionStringValue The SqlServerConnectionString + * value. + */ + public void setSqlServerConnectionString(final String sqlServerConnectionStringValue) { + this.sqlServerConnectionString = sqlServerConnectionStringValue; + } + + private String userName; + + /** + * Optional. The name of the user that will be used for publishing. + * @return The UserName value. + */ + public String getUserName() { + return this.userName; + } + + /** + * Optional. The name of the user that will be used for publishing. + * @param userNameValue The UserName value. + */ + public void setUserName(final String userNameValue) { + this.userName = userNameValue; + } + + private String userPassword; + + /** + * Optional. Hash value of the password that will be used for publishing. + * @return The UserPassword value. + */ + public String getUserPassword() { + return this.userPassword; + } + + /** + * Optional. Hash value of the password that will be used for publishing. + * @param userPasswordValue The UserPassword value. + */ + public void setUserPassword(final String userPasswordValue) { + this.userPassword = userPasswordValue; + } + + /** + * Initializes a new instance of the PublishProfile class. + * + */ + public PublishProfile() { + this.databases = new ArrayList(); + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetRepositoryResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetRepositoryResponse.java new file mode 100644 index 0000000000000..37d83ef00272d --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetRepositoryResponse.java @@ -0,0 +1,50 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; + +/** +* The Get Repository Web Site operation response. +*/ +public class WebSiteGetRepositoryResponse extends OperationResponse { + private URI uri; + + /** + * Optional. The URI of the web site repository. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The URI of the web site repository. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetResponse.java new file mode 100644 index 0000000000000..fc72de809be8d --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Web Site operation response. +*/ +public class WebSiteGetResponse extends OperationResponse { + private WebSite webSite; + + /** + * Optional. Details for the requested web site. + * @return The WebSite value. + */ + public WebSite getWebSite() { + return this.webSite; + } + + /** + * Optional. Details for the requested web site. + * @param webSiteValue The WebSite value. + */ + public void setWebSite(final WebSite webSiteValue) { + this.webSite = webSiteValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetUsageMetricsResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetUsageMetricsResponse.java new file mode 100644 index 0000000000000..6f3bb231c2bd3 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteGetUsageMetricsResponse.java @@ -0,0 +1,262 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; + +/** +* The Get Usage Metrics Web Site operation response. +*/ +public class WebSiteGetUsageMetricsResponse extends OperationResponse implements Iterable { + private ArrayList usageMetrics; + + /** + * Optional. The usage metrics for the web site. + * @return The UsageMetrics value. + */ + public ArrayList getUsageMetrics() { + return this.usageMetrics; + } + + /** + * Optional. The usage metrics for the web site. + * @param usageMetricsValue The UsageMetrics value. + */ + public void setUsageMetrics(final ArrayList usageMetricsValue) { + this.usageMetrics = usageMetricsValue; + } + + /** + * Initializes a new instance of the WebSiteGetUsageMetricsResponse class. + * + */ + public WebSiteGetUsageMetricsResponse() { + super(); + this.usageMetrics = new ArrayList(); + } + + /** + * Gets the sequence of UsageMetrics. + * + */ + public Iterator iterator() { + return this.getUsageMetrics().iterator(); + } + + /** + * A specific usage metric. + */ + public static class UsageMetric { + private WebSiteComputeMode computeMode; + + /** + * Optional. The compute mode of the web site. For web sites in Standard + * Mode, the return value is Dedicated. For web sites in Free or Shared + * mode, the return value is Shared. + * @return The ComputeMode value. + */ + public WebSiteComputeMode getComputeMode() { + return this.computeMode; + } + + /** + * Optional. The compute mode of the web site. For web sites in Standard + * Mode, the return value is Dedicated. For web sites in Free or Shared + * mode, the return value is Shared. + * @param computeModeValue The ComputeMode value. + */ + public void setComputeMode(final WebSiteComputeMode computeModeValue) { + this.computeMode = computeModeValue; + } + + private String currentValue; + + /** + * Optional. The current value of the metric specified, expressed in + * terms of the measurement specified by the Unit element. + * @return The CurrentValue value. + */ + public String getCurrentValue() { + return this.currentValue; + } + + /** + * Optional. The current value of the metric specified, expressed in + * terms of the measurement specified by the Unit element. + * @param currentValueValue The CurrentValue value. + */ + public void setCurrentValue(final String currentValueValue) { + this.currentValue = currentValueValue; + } + + private String displayName; + + /** + * Optional. The display name of the metric (includes spaces). + * @return The DisplayName value. + */ + public String getDisplayName() { + return this.displayName; + } + + /** + * Optional. The display name of the metric (includes spaces). + * @param displayNameValue The DisplayName value. + */ + public void setDisplayName(final String displayNameValue) { + this.displayName = displayNameValue; + } + + private String limit; + + /** + * Optional. The maximum point that the given metric can reach. The + * limit resets at the time specified by the NextResetTime element. If + * the limit is reached before the reset time, the site will be + * stopped. A value of -1 means unlimited. Resources with limits + * typically include CPU Time, Memory Usage, and File System Storage. + * Important: Site level Limits information is only meaningful for + * Shared and Standard web sites. For free web sites, limits are + * enforced at the web space level. + * @return The Limit value. + */ + public String getLimit() { + return this.limit; + } + + /** + * Optional. The maximum point that the given metric can reach. The + * limit resets at the time specified by the NextResetTime element. If + * the limit is reached before the reset time, the site will be + * stopped. A value of -1 means unlimited. Resources with limits + * typically include CPU Time, Memory Usage, and File System Storage. + * Important: Site level Limits information is only meaningful for + * Shared and Standard web sites. For free web sites, limits are + * enforced at the web space level. + * @param limitValue The Limit value. + */ + public void setLimit(final String limitValue) { + this.limit = limitValue; + } + + private String name; + + /** + * Optional. The name of the metric, without spaces. The value is + * usually the same as that of the ResourceName element. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the metric, without spaces. The value is + * usually the same as that of the ResourceName element. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private Calendar nextResetTime; + + /** + * Optional. The time at which the metric will be reset. + * @return The NextResetTime value. + */ + public Calendar getNextResetTime() { + return this.nextResetTime; + } + + /** + * Optional. The time at which the metric will be reset. + * @param nextResetTimeValue The NextResetTime value. + */ + public void setNextResetTime(final Calendar nextResetTimeValue) { + this.nextResetTime = nextResetTimeValue; + } + + private String resourceName; + + /** + * Optional. The name of the resource being measured. + * @return The ResourceName value. + */ + public String getResourceName() { + return this.resourceName; + } + + /** + * Optional. The name of the resource being measured. + * @param resourceNameValue The ResourceName value. + */ + public void setResourceName(final String resourceNameValue) { + this.resourceName = resourceNameValue; + } + + private WebSiteMode siteMode; + + /** + * Optional. The scaling for the web site. Web sites in Free Mode return + * a value of Limited. Web sites in Shared Mode return a value of + * Basic. Sites in Standard Mode return null. + * @return The SiteMode value. + */ + public WebSiteMode getSiteMode() { + return this.siteMode; + } + + /** + * Optional. The scaling for the web site. Web sites in Free Mode return + * a value of Limited. Web sites in Shared Mode return a value of + * Basic. Sites in Standard Mode return null. + * @param siteModeValue The SiteMode value. + */ + public void setSiteMode(final WebSiteMode siteModeValue) { + this.siteMode = siteModeValue; + } + + private String unit; + + /** + * Optional. The unit of measure for the given metric. + * @return The Unit value. + */ + public String getUnit() { + return this.unit; + } + + /** + * Optional. The unit of measure for the given metric. + * @param unitValue The Unit value. + */ + public void setUnit(final String unitValue) { + this.unit = unitValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteInstanceIdsResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteInstanceIdsResponse.java new file mode 100644 index 0000000000000..fcba8e3c859ee --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteInstanceIdsResponse.java @@ -0,0 +1,70 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The web site instance ids reponse. +*/ +public class WebSiteInstanceIdsResponse extends OperationResponse implements Iterable { + private ArrayList instanceIds; + + /** + * Optional. The identifiers of the currently running instances of the web + * site. + * @return The InstanceIds value. + */ + public ArrayList getInstanceIds() { + return this.instanceIds; + } + + /** + * Optional. The identifiers of the currently running instances of the web + * site. + * @param instanceIdsValue The InstanceIds value. + */ + public void setInstanceIds(final ArrayList instanceIdsValue) { + this.instanceIds = instanceIdsValue; + } + + /** + * Initializes a new instance of the WebSiteInstanceIdsResponse class. + * + */ + public WebSiteInstanceIdsResponse() { + super(); + this.instanceIds = new ArrayList(); + } + + /** + * Gets the sequence of InstanceIds. + * + */ + public Iterator iterator() { + return this.getInstanceIds().iterator(); + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteIsHostnameAvailableResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteIsHostnameAvailableResponse.java new file mode 100644 index 0000000000000..fe581ade06aef --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteIsHostnameAvailableResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Is Hostname Available Web Site operation response. +*/ +public class WebSiteIsHostnameAvailableResponse extends OperationResponse { + private boolean isAvailable; + + /** + * Optional. Indicates if the site name is available. + * @return The IsAvailable value. + */ + public boolean isAvailable() { + return this.isAvailable; + } + + /** + * Optional. Indicates if the site name is available. + * @param isAvailableValue The IsAvailable value. + */ + public void setIsAvailable(final boolean isAvailableValue) { + this.isAvailable = isAvailableValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteListParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteListParameters.java new file mode 100644 index 0000000000000..e4fa341d8e38f --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteListParameters.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import java.util.ArrayList; + +/** +* The List Web Sites operation parameters. +*/ +public class WebSiteListParameters { + private ArrayList propertiesToInclude; + + /** + * Optional. Specifies a list of the names of any additional parameters to + * return. + * @return The PropertiesToInclude value. + */ + public ArrayList getPropertiesToInclude() { + return this.propertiesToInclude; + } + + /** + * Optional. Specifies a list of the names of any additional parameters to + * return. + * @param propertiesToIncludeValue The PropertiesToInclude value. + */ + public void setPropertiesToInclude(final ArrayList propertiesToIncludeValue) { + this.propertiesToInclude = propertiesToIncludeValue; + } + + /** + * Initializes a new instance of the WebSiteListParameters class. + * + */ + public WebSiteListParameters() { + this.propertiesToInclude = new ArrayList(); + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteMode.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteMode.java new file mode 100644 index 0000000000000..acaa0fc35fd77 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteMode.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The operation mode of a web site. +*/ +public enum WebSiteMode { + /** + * This value is Limited for the Free offering. The default value is Limited. + */ + Limited, + + /** + * This value is Basic for the Paid and Shared offerings. + */ + Basic, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteOperationStatus.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteOperationStatus.java new file mode 100644 index 0000000000000..1260b3330d0cf --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteOperationStatus.java @@ -0,0 +1,54 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The status of the asynchronous operation. +*/ +public enum WebSiteOperationStatus { + /** + * The asynchronous request is in progress. + */ + InProgress, + + /** + * The asynchronous request failed. + */ + Failed, + + /** + * The asynchronous request succeeded. + */ + Succeeded, + + /** + * The asynchronous request timed out. + */ + TimedOut, + + /** + * The asynchronous request was created. + */ + Created, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteOperationStatusResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteOperationStatusResponse.java new file mode 100644 index 0000000000000..85b11fd149a05 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteOperationStatusResponse.java @@ -0,0 +1,314 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Calendar; + +/** +* The response body contains the status of the specified long-running +* operation, indicating whether it has succeeded, is inprogress, has timed +* out, or has failed. Note that this status is distinct from the HTTP status +* code returned for the Get Operation Status operation itself. If the +* long-running operation failed, the response body includes error information +* regarding the failure. +*/ +public class WebSiteOperationStatusResponse extends OperationResponse { + private Calendar createdTime; + + /** + * Optional. The time when the operation was created. + * @return The CreatedTime value. + */ + public Calendar getCreatedTime() { + return this.createdTime; + } + + /** + * Optional. The time when the operation was created. + * @param createdTimeValue The CreatedTime value. + */ + public void setCreatedTime(final Calendar createdTimeValue) { + this.createdTime = createdTimeValue; + } + + private ArrayList errors; + + /** + * Optional. The list of errors that occurred during the operation. + * @return The Errors value. + */ + public ArrayList getErrors() { + return this.errors; + } + + /** + * Optional. The list of errors that occurred during the operation. + * @param errorsValue The Errors value. + */ + public void setErrors(final ArrayList errorsValue) { + this.errors = errorsValue; + } + + private Calendar expirationTime; + + /** + * Optional. The time when the operation will time out. + * @return The ExpirationTime value. + */ + public Calendar getExpirationTime() { + return this.expirationTime; + } + + /** + * Optional. The time when the operation will time out. + * @param expirationTimeValue The ExpirationTime value. + */ + public void setExpirationTime(final Calendar expirationTimeValue) { + this.expirationTime = expirationTimeValue; + } + + private String geoMasterOperationId; + + /** + * Optional. The GeoMaster Operation ID for this operation, if any. + * @return The GeoMasterOperationId value. + */ + public String getGeoMasterOperationId() { + return this.geoMasterOperationId; + } + + /** + * Optional. The GeoMaster Operation ID for this operation, if any. + * @param geoMasterOperationIdValue The GeoMasterOperationId value. + */ + public void setGeoMasterOperationId(final String geoMasterOperationIdValue) { + this.geoMasterOperationId = geoMasterOperationIdValue; + } + + private Calendar modifiedTime; + + /** + * Optional. The time when the operation was last modified. + * @return The ModifiedTime value. + */ + public Calendar getModifiedTime() { + return this.modifiedTime; + } + + /** + * Optional. The time when the operation was last modified. + * @param modifiedTimeValue The ModifiedTime value. + */ + public void setModifiedTime(final Calendar modifiedTimeValue) { + this.modifiedTime = modifiedTimeValue; + } + + private String name; + + /** + * Optional. The name of the operation. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the operation. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String operationId; + + /** + * Optional. The Operation ID for this operation. Used to poll for operation + * status. + * @return The OperationId value. + */ + public String getOperationId() { + return this.operationId; + } + + /** + * Optional. The Operation ID for this operation. Used to poll for operation + * status. + * @param operationIdValue The OperationId value. + */ + public void setOperationId(final String operationIdValue) { + this.operationId = operationIdValue; + } + + private WebSiteOperationStatus status; + + /** + * Optional. The status of the asynchronous operation. + * @return The Status value. + */ + public WebSiteOperationStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the asynchronous operation. + * @param statusValue The Status value. + */ + public void setStatus(final WebSiteOperationStatus statusValue) { + this.status = statusValue; + } + + /** + * Initializes a new instance of the WebSiteOperationStatusResponse class. + * + */ + public WebSiteOperationStatusResponse() { + super(); + this.errors = new ArrayList(); + } + + /** + * Information about an error that occured during the operation. + */ + public static class Error { + private String code; + + /** + * Optional. The error code. + * @return The Code value. + */ + public String getCode() { + return this.code; + } + + /** + * Optional. The error code. + * @param codeValue The Code value. + */ + public void setCode(final String codeValue) { + this.code = codeValue; + } + + private String extendedCode; + + /** + * Optional. The extended error code. + * @return The ExtendedCode value. + */ + public String getExtendedCode() { + return this.extendedCode; + } + + /** + * Optional. The extended error code. + * @param extendedCodeValue The ExtendedCode value. + */ + public void setExtendedCode(final String extendedCodeValue) { + this.extendedCode = extendedCodeValue; + } + + private String innerErrors; + + /** + * Optional. The inner errors for this operation. + * @return The InnerErrors value. + */ + public String getInnerErrors() { + return this.innerErrors; + } + + /** + * Optional. The inner errors for this operation. + * @param innerErrorsValue The InnerErrors value. + */ + public void setInnerErrors(final String innerErrorsValue) { + this.innerErrors = innerErrorsValue; + } + + private String message; + + /** + * Optional. The error message. + * @return The Message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Optional. The error message. + * @param messageValue The Message value. + */ + public void setMessage(final String messageValue) { + this.message = messageValue; + } + + private String messageTemplate; + + /** + * Optional. The message template. + * @return The MessageTemplate value. + */ + public String getMessageTemplate() { + return this.messageTemplate; + } + + /** + * Optional. The message template. + * @param messageTemplateValue The MessageTemplate value. + */ + public void setMessageTemplate(final String messageTemplateValue) { + this.messageTemplate = messageTemplateValue; + } + + private ArrayList parameters; + + /** + * Optional. The parameters for the message template. + * @return The Parameters value. + */ + public ArrayList getParameters() { + return this.parameters; + } + + /** + * Optional. The parameters for the message template. + * @param parametersValue The Parameters value. + */ + public void setParameters(final ArrayList parametersValue) { + this.parameters = parametersValue; + } + + /** + * Initializes a new instance of the Error class. + * + */ + public Error() { + this.parameters = new ArrayList(); + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteRuntimeAvailabilityState.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteRuntimeAvailabilityState.java new file mode 100644 index 0000000000000..29b69f6c5afff --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteRuntimeAvailabilityState.java @@ -0,0 +1,46 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The runtime availability of a website. +*/ +public enum WebSiteRuntimeAvailabilityState { + /** + * The web site is running correctly. + */ + Normal, + + /** + * The web site is running temporarily in a degraded mode (typically with + * less memory and a shared instance). + */ + Degraded, + + /** + * Due to an unexpected issue, the site has been excluded from provisioning. + * This typically occurs only for free sites. + */ + NotAvailable, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteSslState.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteSslState.java new file mode 100644 index 0000000000000..9b0294b959681 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteSslState.java @@ -0,0 +1,35 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* A web site's SSL state. +*/ +public enum WebSiteSslState { + Disabled, + + SniEnabled, + + IpBasedEnabled, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateConfigurationParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateConfigurationParameters.java new file mode 100644 index 0000000000000..517eed6c84f7c --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateConfigurationParameters.java @@ -0,0 +1,603 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; + +/** +* The parameters supplied Update Configuration Web Site operation. +*/ +public class WebSiteUpdateConfigurationParameters { + private HashMap appSettings; + + /** + * Optional. A set of name/value pairs that contain application settings for + * a web site. + * @return The AppSettings value. + */ + public HashMap getAppSettings() { + return this.appSettings; + } + + /** + * Optional. A set of name/value pairs that contain application settings for + * a web site. + * @param appSettingsValue The AppSettings value. + */ + public void setAppSettings(final HashMap appSettingsValue) { + this.appSettings = appSettingsValue; + } + + private ArrayList connectionStrings; + + /** + * Optional. Connection strings for database and other external resources. + * @return The ConnectionStrings value. + */ + public ArrayList getConnectionStrings() { + return this.connectionStrings; + } + + /** + * Optional. Connection strings for database and other external resources. + * @param connectionStringsValue The ConnectionStrings value. + */ + public void setConnectionStrings(final ArrayList connectionStringsValue) { + this.connectionStrings = connectionStringsValue; + } + + private ArrayList defaultDocuments; + + /** + * Optional. Elements that list, in order of preference, the name of the + * file that a web site returns when the web site's domain name is + * requested by itself. For example, if the default document for + * http://contoso.com is default.htm, the page + * http://www.contoso.com/default.htm is returned when the browser is + * pointed to http://www.contoso.com. + * @return The DefaultDocuments value. + */ + public ArrayList getDefaultDocuments() { + return this.defaultDocuments; + } + + /** + * Optional. Elements that list, in order of preference, the name of the + * file that a web site returns when the web site's domain name is + * requested by itself. For example, if the default document for + * http://contoso.com is default.htm, the page + * http://www.contoso.com/default.htm is returned when the browser is + * pointed to http://www.contoso.com. + * @param defaultDocumentsValue The DefaultDocuments value. + */ + public void setDefaultDocuments(final ArrayList defaultDocumentsValue) { + this.defaultDocuments = defaultDocumentsValue; + } + + private Boolean detailedErrorLoggingEnabled; + + /** + * Optional. Indicated if detailed error logging is enabled. + * @return The DetailedErrorLoggingEnabled value. + */ + public Boolean isDetailedErrorLoggingEnabled() { + return this.detailedErrorLoggingEnabled; + } + + /** + * Optional. Indicated if detailed error logging is enabled. + * @param detailedErrorLoggingEnabledValue The DetailedErrorLoggingEnabled + * value. + */ + public void setDetailedErrorLoggingEnabled(final Boolean detailedErrorLoggingEnabledValue) { + this.detailedErrorLoggingEnabled = detailedErrorLoggingEnabledValue; + } + + private String documentRoot; + + /** + * Optional. The document root. + * @return The DocumentRoot value. + */ + public String getDocumentRoot() { + return this.documentRoot; + } + + /** + * Optional. The document root. + * @param documentRootValue The DocumentRoot value. + */ + public void setDocumentRoot(final String documentRootValue) { + this.documentRoot = documentRootValue; + } + + private ArrayList handlerMappings; + + /** + * Optional. Specifies custom executable programs for handling requests for + * specific file name extensions. + * @return The HandlerMappings value. + */ + public ArrayList getHandlerMappings() { + return this.handlerMappings; + } + + /** + * Optional. Specifies custom executable programs for handling requests for + * specific file name extensions. + * @param handlerMappingsValue The HandlerMappings value. + */ + public void setHandlerMappings(final ArrayList handlerMappingsValue) { + this.handlerMappings = handlerMappingsValue; + } + + private Boolean httpLoggingEnabled; + + /** + * Optional. Indicates if HTTP error logging is enabled. + * @return The HttpLoggingEnabled value. + */ + public Boolean isHttpLoggingEnabled() { + return this.httpLoggingEnabled; + } + + /** + * Optional. Indicates if HTTP error logging is enabled. + * @param httpLoggingEnabledValue The HttpLoggingEnabled value. + */ + public void setHttpLoggingEnabled(final Boolean httpLoggingEnabledValue) { + this.httpLoggingEnabled = httpLoggingEnabledValue; + } + + private Integer logsDirectorySizeLimit; + + /** + * Optional. The size limit of the logs directory. + * @return The LogsDirectorySizeLimit value. + */ + public Integer getLogsDirectorySizeLimit() { + return this.logsDirectorySizeLimit; + } + + /** + * Optional. The size limit of the logs directory. + * @param logsDirectorySizeLimitValue The LogsDirectorySizeLimit value. + */ + public void setLogsDirectorySizeLimit(final Integer logsDirectorySizeLimitValue) { + this.logsDirectorySizeLimit = logsDirectorySizeLimitValue; + } + + private ManagedPipelineMode managedPipelineMode; + + /** + * Optional. The managed pipeline mode. + * @return The ManagedPipelineMode value. + */ + public ManagedPipelineMode getManagedPipelineMode() { + return this.managedPipelineMode; + } + + /** + * Optional. The managed pipeline mode. + * @param managedPipelineModeValue The ManagedPipelineMode value. + */ + public void setManagedPipelineMode(final ManagedPipelineMode managedPipelineModeValue) { + this.managedPipelineMode = managedPipelineModeValue; + } + + private HashMap metadata; + + /** + * Optional. Name/value pairs for source control or other information. + * @return The Metadata value. + */ + public HashMap getMetadata() { + return this.metadata; + } + + /** + * Optional. Name/value pairs for source control or other information. + * @param metadataValue The Metadata value. + */ + public void setMetadata(final HashMap metadataValue) { + this.metadata = metadataValue; + } + + private String netFrameworkVersion; + + /** + * Optional. The .NET Framework version. Supported values are v2.0 and v4.0. + * @return The NetFrameworkVersion value. + */ + public String getNetFrameworkVersion() { + return this.netFrameworkVersion; + } + + /** + * Optional. The .NET Framework version. Supported values are v2.0 and v4.0. + * @param netFrameworkVersionValue The NetFrameworkVersion value. + */ + public void setNetFrameworkVersion(final String netFrameworkVersionValue) { + this.netFrameworkVersion = netFrameworkVersionValue; + } + + private Integer numberOfWorkers; + + /** + * Optional. The number of web workers allotted to the web site. If the site + * mode is Free, this value is 1. If the site mode is Shared, this value + * can range from 1 through 6. If the site mode is Standard, this value can + * range from 1 through 10. + * @return The NumberOfWorkers value. + */ + public Integer getNumberOfWorkers() { + return this.numberOfWorkers; + } + + /** + * Optional. The number of web workers allotted to the web site. If the site + * mode is Free, this value is 1. If the site mode is Shared, this value + * can range from 1 through 6. If the site mode is Standard, this value can + * range from 1 through 10. + * @param numberOfWorkersValue The NumberOfWorkers value. + */ + public void setNumberOfWorkers(final Integer numberOfWorkersValue) { + this.numberOfWorkers = numberOfWorkersValue; + } + + private String phpVersion; + + /** + * Optional. The web site's PHP version. Supported values are an empty + * string (an empty string disables PHP), 5.3, and 5.4. + * @return The PhpVersion value. + */ + public String getPhpVersion() { + return this.phpVersion; + } + + /** + * Optional. The web site's PHP version. Supported values are an empty + * string (an empty string disables PHP), 5.3, and 5.4. + * @param phpVersionValue The PhpVersion value. + */ + public void setPhpVersion(final String phpVersionValue) { + this.phpVersion = phpVersionValue; + } + + private String publishingPassword; + + /** + * Optional. Hash value of the password used for publishing the web site. + * @return The PublishingPassword value. + */ + public String getPublishingPassword() { + return this.publishingPassword; + } + + /** + * Optional. Hash value of the password used for publishing the web site. + * @param publishingPasswordValue The PublishingPassword value. + */ + public void setPublishingPassword(final String publishingPasswordValue) { + this.publishingPassword = publishingPasswordValue; + } + + private String publishingUserName; + + /** + * Optional. The user name used for publishing the web site. This is + * normally a dollar sign prepended to the web site name (for example, + * "$contoso"). + * @return The PublishingUserName value. + */ + public String getPublishingUserName() { + return this.publishingUserName; + } + + /** + * Optional. The user name used for publishing the web site. This is + * normally a dollar sign prepended to the web site name (for example, + * "$contoso"). + * @param publishingUserNameValue The PublishingUserName value. + */ + public void setPublishingUserName(final String publishingUserNameValue) { + this.publishingUserName = publishingUserNameValue; + } + + private Boolean remoteDebuggingEnabled; + + /** + * Optional. Indicates if remote debugging is enabled. + * @return The RemoteDebuggingEnabled value. + */ + public Boolean isRemoteDebuggingEnabled() { + return this.remoteDebuggingEnabled; + } + + /** + * Optional. Indicates if remote debugging is enabled. + * @param remoteDebuggingEnabledValue The RemoteDebuggingEnabled value. + */ + public void setRemoteDebuggingEnabled(final Boolean remoteDebuggingEnabledValue) { + this.remoteDebuggingEnabled = remoteDebuggingEnabledValue; + } + + private RemoteDebuggingVersion remoteDebuggingVersion; + + /** + * Optional. The remote debugging version. + * @return The RemoteDebuggingVersion value. + */ + public RemoteDebuggingVersion getRemoteDebuggingVersion() { + return this.remoteDebuggingVersion; + } + + /** + * Optional. The remote debugging version. + * @param remoteDebuggingVersionValue The RemoteDebuggingVersion value. + */ + public void setRemoteDebuggingVersion(final RemoteDebuggingVersion remoteDebuggingVersionValue) { + this.remoteDebuggingVersion = remoteDebuggingVersionValue; + } + + private Boolean requestTracingEnabled; + + /** + * Optional. Indicates if request tracing is enabled. + * @return The RequestTracingEnabled value. + */ + public Boolean isRequestTracingEnabled() { + return this.requestTracingEnabled; + } + + /** + * Optional. Indicates if request tracing is enabled. + * @param requestTracingEnabledValue The RequestTracingEnabled value. + */ + public void setRequestTracingEnabled(final Boolean requestTracingEnabledValue) { + this.requestTracingEnabled = requestTracingEnabledValue; + } + + private Calendar requestTracingExpirationTime; + + /** + * Optional. Time remaining until request tracing expires. + * @return The RequestTracingExpirationTime value. + */ + public Calendar getRequestTracingExpirationTime() { + return this.requestTracingExpirationTime; + } + + /** + * Optional. Time remaining until request tracing expires. + * @param requestTracingExpirationTimeValue The RequestTracingExpirationTime + * value. + */ + public void setRequestTracingExpirationTime(final Calendar requestTracingExpirationTimeValue) { + this.requestTracingExpirationTime = requestTracingExpirationTimeValue; + } + + private String scmType; + + /** + * Optional. The source control method that the web site is using (for + * example, Local Git). If deployment from source control has not been set + * up for the web site, this value is None. + * @return The ScmType value. + */ + public String getScmType() { + return this.scmType; + } + + /** + * Optional. The source control method that the web site is using (for + * example, Local Git). If deployment from source control has not been set + * up for the web site, this value is None. + * @param scmTypeValue The ScmType value. + */ + public void setScmType(final String scmTypeValue) { + this.scmType = scmTypeValue; + } + + private Boolean use32BitWorkerProcess; + + /** + * Optional. Indicates if 32-bit mode is enabled. + * @return The Use32BitWorkerProcess value. + */ + public Boolean isUse32BitWorkerProcess() { + return this.use32BitWorkerProcess; + } + + /** + * Optional. Indicates if 32-bit mode is enabled. + * @param use32BitWorkerProcessValue The Use32BitWorkerProcess value. + */ + public void setUse32BitWorkerProcess(final Boolean use32BitWorkerProcessValue) { + this.use32BitWorkerProcess = use32BitWorkerProcessValue; + } + + private Boolean webSocketsEnabled; + + /** + * Optional. Indicates if Web Sockets are enabled. + * @return The WebSocketsEnabled value. + */ + public Boolean isWebSocketsEnabled() { + return this.webSocketsEnabled; + } + + /** + * Optional. Indicates if Web Sockets are enabled. + * @param webSocketsEnabledValue The WebSocketsEnabled value. + */ + public void setWebSocketsEnabled(final Boolean webSocketsEnabledValue) { + this.webSocketsEnabled = webSocketsEnabledValue; + } + + /** + * Initializes a new instance of the WebSiteUpdateConfigurationParameters + * class. + * + */ + public WebSiteUpdateConfigurationParameters() { + this.appSettings = new HashMap(); + this.connectionStrings = new ArrayList(); + this.defaultDocuments = new ArrayList(); + this.handlerMappings = new ArrayList(); + this.metadata = new HashMap(); + } + + /** + * Connection string information for database and other external resources. + */ + public static class ConnectionStringInfo { + private String connectionString; + + /** + * Optional. The database connection string. + * @return The ConnectionString value. + */ + public String getConnectionString() { + return this.connectionString; + } + + /** + * Optional. The database connection string. + * @param connectionStringValue The ConnectionString value. + */ + public void setConnectionString(final String connectionStringValue) { + this.connectionString = connectionStringValue; + } + + private String name; + + /** + * Optional. The name of the connection string. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the connection string. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String type; + + /** + * Optional. The type of the connection string (for example, "MySQL"). + * @return The Type value. + */ + public String getType() { + return this.type; + } + + /** + * Optional. The type of the connection string (for example, "MySQL"). + * @param typeValue The Type value. + */ + public void setType(final String typeValue) { + this.type = typeValue; + } + } + + /** + * Specifies a custom executable program for handling requests for specific + * file name extensions. + */ + public static class HandlerMapping { + private String arguments; + + /** + * Optional. A string that contains optional arguments for the script + * processor specified by the + * SiteConfig.HandlerMappings.HandlerMapping.ScriptProcessor element. + * @return The Arguments value. + */ + public String getArguments() { + return this.arguments; + } + + /** + * Optional. A string that contains optional arguments for the script + * processor specified by the + * SiteConfig.HandlerMappings.HandlerMapping.ScriptProcessor element. + * @param argumentsValue The Arguments value. + */ + public void setArguments(final String argumentsValue) { + this.arguments = argumentsValue; + } + + private String extension; + + /** + * Optional. A string that specifies the extension of the file type that + * the script processor will handle (for example, *.php). + * @return The Extension value. + */ + public String getExtension() { + return this.extension; + } + + /** + * Optional. A string that specifies the extension of the file type that + * the script processor will handle (for example, *.php). + * @param extensionValue The Extension value. + */ + public void setExtension(final String extensionValue) { + this.extension = extensionValue; + } + + private String scriptProcessor; + + /** + * Optional. The absolute path to the location of the executable file + * that will handle the files specified in the + * SiteConfig.HandlerMappings.HandlerMapping.Extension element. + * @return The ScriptProcessor value. + */ + public String getScriptProcessor() { + return this.scriptProcessor; + } + + /** + * Optional. The absolute path to the location of the executable file + * that will handle the files specified in the + * SiteConfig.HandlerMappings.HandlerMapping.Extension element. + * @param scriptProcessorValue The ScriptProcessor value. + */ + public void setScriptProcessor(final String scriptProcessorValue) { + this.scriptProcessor = scriptProcessorValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateParameters.java new file mode 100644 index 0000000000000..5bdab393dbb96 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateParameters.java @@ -0,0 +1,407 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import java.util.ArrayList; + +/** +* Parameters supplied to the Update Web Site operation. +*/ +public class WebSiteUpdateParameters { + private WebSpaceAvailabilityState availabilityState; + + /** + * Optional. The state of the availability of management information for the + * web site. Possible values are Normal or Limited. Normal means that the + * web site is running correctly and that management information for the + * web site is available. Limited means that only partial management + * information for the web site is available and that detailed web site + * information is unavailable. + * @return The AvailabilityState value. + */ + public WebSpaceAvailabilityState getAvailabilityState() { + return this.availabilityState; + } + + /** + * Optional. The state of the availability of management information for the + * web site. Possible values are Normal or Limited. Normal means that the + * web site is running correctly and that management information for the + * web site is available. Limited means that only partial management + * information for the web site is available and that detailed web site + * information is unavailable. + * @param availabilityStateValue The AvailabilityState value. + */ + public void setAvailabilityState(final WebSpaceAvailabilityState availabilityStateValue) { + this.availabilityState = availabilityStateValue; + } + + private WebSiteComputeMode computeMode; + + /** + * Optional. The Compute Mode for the web site. Possible values are Shared + * or Dedicated. + * @return The ComputeMode value. + */ + public WebSiteComputeMode getComputeMode() { + return this.computeMode; + } + + /** + * Optional. The Compute Mode for the web site. Possible values are Shared + * or Dedicated. + * @param computeModeValue The ComputeMode value. + */ + public void setComputeMode(final WebSiteComputeMode computeModeValue) { + this.computeMode = computeModeValue; + } + + private Boolean enabled; + + /** + * Optional. Indicates if the site is enabled. Setting this value to false + * disables the site (takes the site offline). + * @return The Enabled value. + */ + public Boolean isEnabled() { + return this.enabled; + } + + /** + * Optional. Indicates if the site is enabled. Setting this value to false + * disables the site (takes the site offline). + * @param enabledValue The Enabled value. + */ + public void setEnabled(final Boolean enabledValue) { + this.enabled = enabledValue; + } + + private ArrayList hostNames; + + /** + * Optional. An array of strings that contains the public host names for the + * web site, including custom domains. Important: When you add a custom + * domain in a PUT operation, be sure to include every host name that you + * want for the web site. To delete a custom domain name in a PUT + * operation, include all of the host names for the web site that you want + * to keep, but leave out the one that you want to delete. + * @return The HostNames value. + */ + public ArrayList getHostNames() { + return this.hostNames; + } + + /** + * Optional. An array of strings that contains the public host names for the + * web site, including custom domains. Important: When you add a custom + * domain in a PUT operation, be sure to include every host name that you + * want for the web site. To delete a custom domain name in a PUT + * operation, include all of the host names for the web site that you want + * to keep, but leave out the one that you want to delete. + * @param hostNamesValue The HostNames value. + */ + public void setHostNames(final ArrayList hostNamesValue) { + this.hostNames = hostNamesValue; + } + + private ArrayList hostNameSslStates; + + /** + * Optional. SSL states bound to the web site. + * @return The HostNameSslStates value. + */ + public ArrayList getHostNameSslStates() { + return this.hostNameSslStates; + } + + /** + * Optional. SSL states bound to the web site. + * @param hostNameSslStatesValue The HostNameSslStates value. + */ + public void setHostNameSslStates(final ArrayList hostNameSslStatesValue) { + this.hostNameSslStates = hostNameSslStatesValue; + } + + private WebSiteRuntimeAvailabilityState runtimeAvailabilityState; + + /** + * Optional. The current runtime availability state. Possible values are + * Normal, Degraded, or NotAvailable: Normal: the web site is running + * correctly; Degraded: the web site is running temporarily in a degraded + * mode (typically with less memory and a shared instance). Not Available: + * due to an unexpected issue, the web site has been excluded from + * provisioning. This typically occurs only for free sites. + * @return The RuntimeAvailabilityState value. + */ + public WebSiteRuntimeAvailabilityState getRuntimeAvailabilityState() { + return this.runtimeAvailabilityState; + } + + /** + * Optional. The current runtime availability state. Possible values are + * Normal, Degraded, or NotAvailable: Normal: the web site is running + * correctly; Degraded: the web site is running temporarily in a degraded + * mode (typically with less memory and a shared instance). Not Available: + * due to an unexpected issue, the web site has been excluded from + * provisioning. This typically occurs only for free sites. + * @param runtimeAvailabilityStateValue The RuntimeAvailabilityState value. + */ + public void setRuntimeAvailabilityState(final WebSiteRuntimeAvailabilityState runtimeAvailabilityStateValue) { + this.runtimeAvailabilityState = runtimeAvailabilityStateValue; + } + + private String serverFarm; + + /** + * Optional. String specifying the server farm. If a server farm exists, + * this value is DefaultServerFarm. + * @return The ServerFarm value. + */ + public String getServerFarm() { + return this.serverFarm; + } + + /** + * Optional. String specifying the server farm. If a server farm exists, + * this value is DefaultServerFarm. + * @param serverFarmValue The ServerFarm value. + */ + public void setServerFarm(final String serverFarmValue) { + this.serverFarm = serverFarmValue; + } + + private WebSiteMode siteMode; + + /** + * Optional. String that represents the web site mode. If the web site mode + * is Free, this value is Limited. If the web site mode is Shared, this + * value is Basic. Note: The SiteMode value is not used for Reserved mode. + * Reserved mode uses the ComputeMode setting. + * @return The SiteMode value. + */ + public WebSiteMode getSiteMode() { + return this.siteMode; + } + + /** + * Optional. String that represents the web site mode. If the web site mode + * is Free, this value is Limited. If the web site mode is Shared, this + * value is Basic. Note: The SiteMode value is not used for Reserved mode. + * Reserved mode uses the ComputeMode setting. + * @param siteModeValue The SiteMode value. + */ + public void setSiteMode(final WebSiteMode siteModeValue) { + this.siteMode = siteModeValue; + } + + private ArrayList sslCertificates; + + /** + * Optional. SSL certificates bound to the web site. + * @return The SslCertificates value. + */ + public ArrayList getSslCertificates() { + return this.sslCertificates; + } + + /** + * Optional. SSL certificates bound to the web site. + * @param sslCertificatesValue The SslCertificates value. + */ + public void setSslCertificates(final ArrayList sslCertificatesValue) { + this.sslCertificates = sslCertificatesValue; + } + + private String state; + + /** + * Optional. A string that describes the state of the web site. Possible + * values include Stopped, Running, or QuotaExceeded. + * @return The State value. + */ + public String getState() { + return this.state; + } + + /** + * Optional. A string that describes the state of the web site. Possible + * values include Stopped, Running, or QuotaExceeded. + * @param stateValue The State value. + */ + public void setState(final String stateValue) { + this.state = stateValue; + } + + /** + * Initializes a new instance of the WebSiteUpdateParameters class. + * + */ + public WebSiteUpdateParameters() { + this.hostNames = new ArrayList(); + this.hostNameSslStates = new ArrayList(); + this.sslCertificates = new ArrayList(); + } + + /** + * SSL state bound to the web site. + */ + public static class WebSiteHostNameSslState { + private WebSiteSslState sslState; + + /** + * Optional. The SSL state. Possible values are Disabled, SniEnabled, or + * IpBasedEnabled. + * @return The SslState value. + */ + public WebSiteSslState getSslState() { + return this.sslState; + } + + /** + * Optional. The SSL state. Possible values are Disabled, SniEnabled, or + * IpBasedEnabled. + * @param sslStateValue The SslState value. + */ + public void setSslState(final WebSiteSslState sslStateValue) { + this.sslState = sslStateValue; + } + + private String thumbprint; + + /** + * Optional. A string that contains the thumbprint of the SSL + * certificate. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. A string that contains the thumbprint of the SSL + * certificate. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + + private Boolean toUpdate; + + /** + * Optional. Indicates whether the SSL state will be updated. + * @return The ToUpdate value. + */ + public Boolean isToUpdate() { + return this.toUpdate; + } + + /** + * Optional. Indicates whether the SSL state will be updated. + * @param toUpdateValue The ToUpdate value. + */ + public void setToUpdate(final Boolean toUpdateValue) { + this.toUpdate = toUpdateValue; + } + } + + /** + * The properties for an SSL certificate. + */ + public static class WebSiteSslCertificate { + private Boolean isToBeDeleted; + + /** + * Optional. Indicates if the certificate is to be deleted. + * @return The IsToBeDeleted value. + */ + public Boolean isToBeDeleted() { + return this.isToBeDeleted; + } + + /** + * Optional. Indicates if the certificate is to be deleted. + * @param isToBeDeletedValue The IsToBeDeleted value. + */ + public void setIsToBeDeleted(final Boolean isToBeDeletedValue) { + this.isToBeDeleted = isToBeDeletedValue; + } + + private String password; + + /** + * Optional. A string that contains the password for the certificate. + * @return The Password value. + */ + public String getPassword() { + return this.password; + } + + /** + * Optional. A string that contains the password for the certificate. + * @param passwordValue The Password value. + */ + public void setPassword(final String passwordValue) { + this.password = passwordValue; + } + + private byte[] pfxBlob; + + /** + * Optional. A base64Binary value that contains the PfxBlob of the + * certificate. + * @return The PfxBlob value. + */ + public byte[] getPfxBlob() { + return this.pfxBlob; + } + + /** + * Optional. A base64Binary value that contains the PfxBlob of the + * certificate. + * @param pfxBlobValue The PfxBlob value. + */ + public void setPfxBlob(final byte[] pfxBlobValue) { + this.pfxBlob = pfxBlobValue; + } + + private String thumbprint; + + /** + * Optional. A string that contains the certificate thumbprint. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. A string that contains the certificate thumbprint. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateResponse.java new file mode 100644 index 0000000000000..416e6d86c1c00 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUpdateResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Update Web Site operation response. +*/ +public class WebSiteUpdateResponse extends OperationResponse { + private WebSite webSite; + + /** + * Optional. Details of the updated web site. + * @return The WebSite value. + */ + public WebSite getWebSite() { + return this.webSite; + } + + /** + * Optional. Details of the updated web site. + * @param webSiteValue The WebSite value. + */ + public void setWebSite(final WebSite webSiteValue) { + this.webSite = webSiteValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUsageState.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUsageState.java new file mode 100644 index 0000000000000..e45ae84da85b8 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteUsageState.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* Usage of a web site's quota. +*/ +public enum WebSiteUsageState { + Normal, + + Exceeded, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceAvailabilityState.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceAvailabilityState.java new file mode 100644 index 0000000000000..c0708e3bd21ea --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceAvailabilityState.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The availability of a web space. +*/ +public enum WebSpaceAvailabilityState { + Normal, + + Limited, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceNames.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceNames.java new file mode 100644 index 0000000000000..7bf838483d2e1 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceNames.java @@ -0,0 +1,38 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +public abstract class WebSpaceNames { + public static final String EASTUSWEBSPACE = "eastuswebspace"; + + public static final String WESTUSWEBSPACE = "westuswebspace"; + + public static final String NORTHCENTRALUSWEBSPACE = "northcentraluswebspace"; + + public static final String NORTHEUROPEWEBSPACE = "northeuropewebspace"; + + public static final String WESTEUROPEWEBSPACE = "westeuropewebspace"; + + public static final String EASTASIAWEBSPACE = "eastasiawebspace"; +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacePlanNames.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacePlanNames.java new file mode 100644 index 0000000000000..a993d08809013 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacePlanNames.java @@ -0,0 +1,31 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* A web space plan. +*/ +public abstract class WebSpacePlanNames { + public static final String VIRTUALDEDICATEDPLAN = "VirtualDedicatedPlan"; +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceStatus.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceStatus.java new file mode 100644 index 0000000000000..1dfc056a12034 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceStatus.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The status of a web space. +*/ +public enum WebSpaceStatus { + Ready, + + Limited, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceWorkerSize.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceWorkerSize.java new file mode 100644 index 0000000000000..1e38dba972178 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpaceWorkerSize.java @@ -0,0 +1,35 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* The size of a web space worker. +*/ +public enum WebSpaceWorkerSize { + Small, + + Medium, + + Large, +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesCreatePublishingUserParameters.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesCreatePublishingUserParameters.java new file mode 100644 index 0000000000000..5f445e3551d61 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesCreatePublishingUserParameters.java @@ -0,0 +1,83 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +/** +* Parameters supplied to the Create Publishing User operation. +*/ +public class WebSpacesCreatePublishingUserParameters { + private String name; + + /** + * Optional. The publishing user name. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The publishing user name. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String publishingPassword; + + /** + * Required. The publishing user password. + * @return The PublishingPassword value. + */ + public String getPublishingPassword() { + return this.publishingPassword; + } + + /** + * Required. The publishing user password. + * @param publishingPasswordValue The PublishingPassword value. + */ + public void setPublishingPassword(final String publishingPasswordValue) { + this.publishingPassword = publishingPasswordValue; + } + + private String publishingUserName; + + /** + * Required. The publishing user username. + * @return The PublishingUserName value. + */ + public String getPublishingUserName() { + return this.publishingUserName; + } + + /** + * Required. The publishing user username. + * @param publishingUserNameValue The PublishingUserName value. + */ + public void setPublishingUserName(final String publishingUserNameValue) { + this.publishingUserName = publishingUserNameValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesCreatePublishingUserResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesCreatePublishingUserResponse.java new file mode 100644 index 0000000000000..f1b7bbc33a44f --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesCreatePublishingUserResponse.java @@ -0,0 +1,85 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Create Publishing User operation response. +*/ +public class WebSpacesCreatePublishingUserResponse extends OperationResponse { + private String name; + + /** + * Optional. The publishing user name. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The publishing user name. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String publishingPassword; + + /** + * Optional. The publishing user password. + * @return The PublishingPassword value. + */ + public String getPublishingPassword() { + return this.publishingPassword; + } + + /** + * Optional. The publishing user password. + * @param publishingPasswordValue The PublishingPassword value. + */ + public void setPublishingPassword(final String publishingPasswordValue) { + this.publishingPassword = publishingPasswordValue; + } + + private String publishingUserName; + + /** + * Optional. The publishing user username. + * @return The PublishingUserName value. + */ + public String getPublishingUserName() { + return this.publishingUserName; + } + + /** + * Optional. The publishing user username. + * @param publishingUserNameValue The PublishingUserName value. + */ + public void setPublishingUserName(final String publishingUserNameValue) { + this.publishingUserName = publishingUserNameValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesGetDnsSuffixResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesGetDnsSuffixResponse.java new file mode 100644 index 0000000000000..d2a28b8c72e83 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesGetDnsSuffixResponse.java @@ -0,0 +1,49 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get DNS Suffix operation response. +*/ +public class WebSpacesGetDnsSuffixResponse extends OperationResponse { + private String dnsSuffix; + + /** + * Optional. The DNS Suffix used for the web space. + * @return The DnsSuffix value. + */ + public String getDnsSuffix() { + return this.dnsSuffix; + } + + /** + * Optional. The DNS Suffix used for the web space. + * @param dnsSuffixValue The DnsSuffix value. + */ + public void setDnsSuffix(final String dnsSuffixValue) { + this.dnsSuffix = dnsSuffixValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesGetResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesGetResponse.java new file mode 100644 index 0000000000000..bbd0b1e2a0318 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesGetResponse.java @@ -0,0 +1,221 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Web Space Details operation response. +*/ +public class WebSpacesGetResponse extends OperationResponse { + private WebSpaceAvailabilityState availabilityState; + + /** + * Optional. The current availability state. Possible values are Normal or + * Limited. + * @return The AvailabilityState value. + */ + public WebSpaceAvailabilityState getAvailabilityState() { + return this.availabilityState; + } + + /** + * Optional. The current availability state. Possible values are Normal or + * Limited. + * @param availabilityStateValue The AvailabilityState value. + */ + public void setAvailabilityState(final WebSpaceAvailabilityState availabilityStateValue) { + this.availabilityState = availabilityStateValue; + } + + private Integer currentNumberOfWorkers; + + /** + * Optional. The current number of workers. + * @return The CurrentNumberOfWorkers value. + */ + public Integer getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of workers. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final Integer currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private WebSpaceWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @return The CurrentWorkerSize value. + */ + public WebSpaceWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, or + * Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final WebSpaceWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private String geoLocation; + + /** + * Optional. The location of the datacenter for the web space. + * @return The GeoLocation value. + */ + public String getGeoLocation() { + return this.geoLocation; + } + + /** + * Optional. The location of the datacenter for the web space. + * @param geoLocationValue The GeoLocation value. + */ + public void setGeoLocation(final String geoLocationValue) { + this.geoLocation = geoLocationValue; + } + + private String geoRegion; + + /** + * Optional. The geographical region where the web space is located. + * @return The GeoRegion value. + */ + public String getGeoRegion() { + return this.geoRegion; + } + + /** + * Optional. The geographical region where the web space is located. + * @param geoRegionValue The GeoRegion value. + */ + public void setGeoRegion(final String geoRegionValue) { + this.geoRegion = geoRegionValue; + } + + private String name; + + /** + * Optional. The name of the web space. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the web space. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String plan; + + /** + * Optional. The web space plan name. + * @return The Plan value. + */ + public String getPlan() { + return this.plan; + } + + /** + * Optional. The web space plan name. + * @param planValue The Plan value. + */ + public void setPlan(final String planValue) { + this.plan = planValue; + } + + private WebSpaceStatus status; + + /** + * Optional. The status of the Web Space. Possible values are Ready or + * Limited. Note: The Limited status occurs only if the datacenter is + * encountering an operational issue. + * @return The Status value. + */ + public WebSpaceStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the Web Space. Possible values are Ready or + * Limited. Note: The Limited status occurs only if the datacenter is + * encountering an operational issue. + * @param statusValue The Status value. + */ + public void setStatus(final WebSpaceStatus statusValue) { + this.status = statusValue; + } + + private String subscription; + + /** + * Optional. The subscription ID. + * @return The Subscription value. + */ + public String getSubscription() { + return this.subscription; + } + + /** + * Optional. The subscription ID. + * @param subscriptionValue The Subscription value. + */ + public void setSubscription(final String subscriptionValue) { + this.subscription = subscriptionValue; + } + + private WebSpaceWorkerSize workerSize; + + /** + * Optional. The worker size. Possible values are Small, Medium, and Large. + * For JSON, the equivalents are 0 = Small, 1 = Medium, and 2 = Large. + * @return The WorkerSize value. + */ + public WebSpaceWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Optional. The worker size. Possible values are Small, Medium, and Large. + * For JSON, the equivalents are 0 = Small, 1 = Medium, and 2 = Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final WebSpaceWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListGeoRegionsResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListGeoRegionsResponse.java new file mode 100644 index 0000000000000..5c5295eff297b --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListGeoRegionsResponse.java @@ -0,0 +1,127 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Geo Regions operation response. +*/ +public class WebSpacesListGeoRegionsResponse extends OperationResponse implements Iterable { + private ArrayList geoRegions; + + /** + * Optional. The available geo regions. + * @return The GeoRegions value. + */ + public ArrayList getGeoRegions() { + return this.geoRegions; + } + + /** + * Optional. The available geo regions. + * @param geoRegionsValue The GeoRegions value. + */ + public void setGeoRegions(final ArrayList geoRegionsValue) { + this.geoRegions = geoRegionsValue; + } + + /** + * Initializes a new instance of the WebSpacesListGeoRegionsResponse class. + * + */ + public WebSpacesListGeoRegionsResponse() { + super(); + this.geoRegions = new ArrayList(); + } + + /** + * Gets the sequence of GeoRegions. + * + */ + public Iterator iterator() { + return this.getGeoRegions().iterator(); + } + + /** + * An available geo region for a web space. + */ + public static class GeoRegion { + private String description; + + /** + * Optional. Description of the geo region. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. Description of the geo region. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String name; + + /** + * Optional. Name of the geo region. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. Name of the geo region. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private int sortOrder; + + /** + * Optional. Sort order for the geo region. + * @return The SortOrder value. + */ + public int getSortOrder() { + return this.sortOrder; + } + + /** + * Optional. Sort order for the geo region. + * @param sortOrderValue The SortOrder value. + */ + public void setSortOrder(final int sortOrderValue) { + this.sortOrder = sortOrderValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListPublishingUsersResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListPublishingUsersResponse.java new file mode 100644 index 0000000000000..9e00f1ab96d04 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListPublishingUsersResponse.java @@ -0,0 +1,92 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Publishing Users operation response. +*/ +public class WebSpacesListPublishingUsersResponse extends OperationResponse implements Iterable { + private ArrayList users; + + /** + * Optional. The publishing users. + * @return The Users value. + */ + public ArrayList getUsers() { + return this.users; + } + + /** + * Optional. The publishing users. + * @param usersValue The Users value. + */ + public void setUsers(final ArrayList usersValue) { + this.users = usersValue; + } + + /** + * Initializes a new instance of the WebSpacesListPublishingUsersResponse + * class. + * + */ + public WebSpacesListPublishingUsersResponse() { + super(); + this.users = new ArrayList(); + } + + /** + * Gets the sequence of Users. + * + */ + public Iterator iterator() { + return this.getUsers().iterator(); + } + + /** + * Information about a single publishing user. + */ + public static class User { + private String name; + + /** + * Optional. The publishing user name. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The publishing user name. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListResponse.java new file mode 100644 index 0000000000000..cf8e245ebfbc4 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListResponse.java @@ -0,0 +1,263 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Web Spaces operation response. +*/ +public class WebSpacesListResponse extends OperationResponse implements Iterable { + private ArrayList webSpaces; + + /** + * Optional. The web spaces associated with the specified subscription. + * @return The WebSpaces value. + */ + public ArrayList getWebSpaces() { + return this.webSpaces; + } + + /** + * Optional. The web spaces associated with the specified subscription. + * @param webSpacesValue The WebSpaces value. + */ + public void setWebSpaces(final ArrayList webSpacesValue) { + this.webSpaces = webSpacesValue; + } + + /** + * Initializes a new instance of the WebSpacesListResponse class. + * + */ + public WebSpacesListResponse() { + super(); + this.webSpaces = new ArrayList(); + } + + /** + * Gets the sequence of WebSpaces. + * + */ + public Iterator iterator() { + return this.getWebSpaces().iterator(); + } + + /** + * A web space associated with the specified subscription. + */ + public static class WebSpace { + private WebSpaceAvailabilityState availabilityState; + + /** + * Optional. Possible values are Normal or Limited. + * @return The AvailabilityState value. + */ + public WebSpaceAvailabilityState getAvailabilityState() { + return this.availabilityState; + } + + /** + * Optional. Possible values are Normal or Limited. + * @param availabilityStateValue The AvailabilityState value. + */ + public void setAvailabilityState(final WebSpaceAvailabilityState availabilityStateValue) { + this.availabilityState = availabilityStateValue; + } + + private Integer currentNumberOfWorkers; + + /** + * Optional. The current number of workers. + * @return The CurrentNumberOfWorkers value. + */ + public Integer getCurrentNumberOfWorkers() { + return this.currentNumberOfWorkers; + } + + /** + * Optional. The current number of workers. + * @param currentNumberOfWorkersValue The CurrentNumberOfWorkers value. + */ + public void setCurrentNumberOfWorkers(final Integer currentNumberOfWorkersValue) { + this.currentNumberOfWorkers = currentNumberOfWorkersValue; + } + + private WebSpaceWorkerSize currentWorkerSize; + + /** + * Optional. The current worker size. Possible values are Small, Medium, + * or Large. + * @return The CurrentWorkerSize value. + */ + public WebSpaceWorkerSize getCurrentWorkerSize() { + return this.currentWorkerSize; + } + + /** + * Optional. The current worker size. Possible values are Small, Medium, + * or Large. + * @param currentWorkerSizeValue The CurrentWorkerSize value. + */ + public void setCurrentWorkerSize(final WebSpaceWorkerSize currentWorkerSizeValue) { + this.currentWorkerSize = currentWorkerSizeValue; + } + + private String geoLocation; + + /** + * Optional. The location of the datacenter for the web space. + * @return The GeoLocation value. + */ + public String getGeoLocation() { + return this.geoLocation; + } + + /** + * Optional. The location of the datacenter for the web space. + * @param geoLocationValue The GeoLocation value. + */ + public void setGeoLocation(final String geoLocationValue) { + this.geoLocation = geoLocationValue; + } + + private String geoRegion; + + /** + * Optional. The geographical region where the web space is located. + * @return The GeoRegion value. + */ + public String getGeoRegion() { + return this.geoRegion; + } + + /** + * Optional. The geographical region where the web space is located. + * @param geoRegionValue The GeoRegion value. + */ + public void setGeoRegion(final String geoRegionValue) { + this.geoRegion = geoRegionValue; + } + + private String name; + + /** + * Optional. The name of the web space. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of the web space. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private String plan; + + /** + * Optional. The web space plan name. + * @return The Plan value. + */ + public String getPlan() { + return this.plan; + } + + /** + * Optional. The web space plan name. + * @param planValue The Plan value. + */ + public void setPlan(final String planValue) { + this.plan = planValue; + } + + private WebSpaceStatus status; + + /** + * Optional. The status of the Web Space. Possible values are Ready or + * Limited. Note: The Limited status occurs only if the datacenter is + * encountering an operational issue. + * @return The Status value. + */ + public WebSpaceStatus getStatus() { + return this.status; + } + + /** + * Optional. The status of the Web Space. Possible values are Ready or + * Limited. Note: The Limited status occurs only if the datacenter is + * encountering an operational issue. + * @param statusValue The Status value. + */ + public void setStatus(final WebSpaceStatus statusValue) { + this.status = statusValue; + } + + private String subscription; + + /** + * Optional. The subscription ID. + * @return The Subscription value. + */ + public String getSubscription() { + return this.subscription; + } + + /** + * Optional. The subscription ID. + * @param subscriptionValue The Subscription value. + */ + public void setSubscription(final String subscriptionValue) { + this.subscription = subscriptionValue; + } + + private WebSpaceWorkerSize workerSize; + + /** + * Optional. The worker size. Possible values are Small, Medium, and + * Large. For JSON, the equivalents are 0 = Small, 1 = Medium, and 2 = + * Large. + * @return The WorkerSize value. + */ + public WebSpaceWorkerSize getWorkerSize() { + return this.workerSize; + } + + /** + * Optional. The worker size. Possible values are Small, Medium, and + * Large. For JSON, the equivalents are 0 = Small, 1 = Medium, and 2 = + * Large. + * @param workerSizeValue The WorkerSize value. + */ + public void setWorkerSize(final WebSpaceWorkerSize workerSizeValue) { + this.workerSize = workerSizeValue; + } + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListWebSitesResponse.java b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListWebSitesResponse.java new file mode 100644 index 0000000000000..420423937f944 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSpacesListWebSitesResponse.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.websites.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Web Sites operation response. +*/ +public class WebSpacesListWebSitesResponse extends OperationResponse implements Iterable { + private ArrayList webSites; + + /** + * Optional. The web sites associated with the specified web space. + * @return The WebSites value. + */ + public ArrayList getWebSites() { + return this.webSites; + } + + /** + * Optional. The web sites associated with the specified web space. + * @param webSitesValue The WebSites value. + */ + public void setWebSites(final ArrayList webSitesValue) { + this.webSites = webSitesValue; + } + + /** + * Initializes a new instance of the WebSpacesListWebSitesResponse class. + * + */ + public WebSpacesListWebSitesResponse() { + super(); + this.webSites = new ArrayList(); + } + + /** + * Gets the sequence of WebSites. + * + */ + public Iterator iterator() { + return this.getWebSites().iterator(); + } +} diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/package.html b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/package.html new file mode 100644 index 0000000000000..365788dce2e62 --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/package.html @@ -0,0 +1,4 @@ + + +This package contains the models for the websites management service. + diff --git a/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/package.html b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/package.html new file mode 100644 index 0000000000000..e49ec4d99a8cd --- /dev/null +++ b/management-websites/src/main/java/com/microsoft/windowsazure/management/websites/package.html @@ -0,0 +1,6 @@ + + +This package contains the websites management class, + interface, and associated configuration and utility classes. + + diff --git a/management-websites/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/management-websites/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..9d6f8fe4cf4d2 --- /dev/null +++ b/management-websites/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1 @@ +com.microsoft.windowsazure.management.websites.Exports diff --git a/management-websites/src/test/java/com/microsoft/windowsazure/management/website/ServerFarmOperationsTests.java b/management-websites/src/test/java/com/microsoft/windowsazure/management/website/ServerFarmOperationsTests.java new file mode 100644 index 0000000000000..10a6ba445a9d7 --- /dev/null +++ b/management-websites/src/test/java/com/microsoft/windowsazure/management/website/ServerFarmOperationsTests.java @@ -0,0 +1,164 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.website; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.ArrayList; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.xml.sax.SAXException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.websites.models.ServerFarmCreateParameters; +import com.microsoft.windowsazure.management.websites.models.ServerFarmCreateResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmGetResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmListResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmStatus; +import com.microsoft.windowsazure.management.websites.models.ServerFarmUpdateParameters; +import com.microsoft.windowsazure.management.websites.models.ServerFarmUpdateResponse; +import com.microsoft.windowsazure.management.websites.models.ServerFarmWorkerSize; + +public class ServerFarmOperationsTests extends WebSiteManagementIntegrationTestBase { + + @BeforeClass + public static void setup() throws Exception { + createService(); + cleanup(); + } + + @AfterClass + public static void cleanup() throws Exception { + deleteServerFarm("northcentraluswebspace"); + deleteServerFarm("eastuswebspace"); + } + + private static void deleteServerFarm(String webSpaceName) throws IOException, ParserConfigurationException, SAXException { + try { + webSiteManagementClient.getServerFarmsOperations().delete(webSpaceName); + } + catch (ServiceException e) { + e.printStackTrace(); + } + } + + private void createServerFarm(String webSpaceName) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { + int currentNumberOfWorkersValue = 2; + int numberOfWorkersValue = 2; + ServerFarmCreateParameters createParameters = new ServerFarmCreateParameters(); + createParameters.setCurrentNumberOfWorkers(currentNumberOfWorkersValue); + createParameters.setCurrentWorkerSize(ServerFarmWorkerSize.Small); + createParameters.setNumberOfWorkers(numberOfWorkersValue); + createParameters.setStatus(ServerFarmStatus.Pending); + createParameters.setWorkerSize(ServerFarmWorkerSize.Small); + webSiteManagementClient.getServerFarmsOperations().create(webSpaceName, createParameters); + } + + @Test + public void createServerFarmSuccess() throws Exception { + String webSpaceName = "northcentraluswebspace"; + int currentNumberOfWorkersValue = 2; + int numberOfWorkersValue = 2; + + // Arrange + ServerFarmCreateParameters createParameters = new ServerFarmCreateParameters(); + createParameters.setCurrentNumberOfWorkers(currentNumberOfWorkersValue); + createParameters.setCurrentWorkerSize(ServerFarmWorkerSize.Small); + createParameters.setNumberOfWorkers(numberOfWorkersValue); + createParameters.setStatus(ServerFarmStatus.Pending); + createParameters.setWorkerSize(ServerFarmWorkerSize.Small); + + // Act + ServerFarmCreateResponse serverFarmCreateResponse = webSiteManagementClient.getServerFarmsOperations().create(webSpaceName, createParameters); + + // Assert + Assert.assertEquals(200, serverFarmCreateResponse.getStatusCode()); + Assert.assertNotNull(serverFarmCreateResponse.getRequestId()); + Assert.assertEquals(currentNumberOfWorkersValue, serverFarmCreateResponse.getCurrentNumberOfWorkers()); + Assert.assertEquals(ServerFarmWorkerSize.Small, serverFarmCreateResponse.getCurrentWorkerSize()); + } + + @Test + public void getServerFarmSuccess() throws Exception { + String webSpaceName = "eastuswebspace"; + String serverFarmName = ""; + + // Act + ServerFarmGetResponse serverFarmGetResponse = webSiteManagementClient.getServerFarmsOperations().get(webSpaceName, serverFarmName); + + // Assert + Assert.assertEquals(200, serverFarmGetResponse.getStatusCode()); + Assert.assertNotNull(serverFarmGetResponse.getRequestId()); + } + + @Test + public void listServerFarmSuccess() throws Exception { + String webSpaceName = "eastuswebspace"; + + // Act + ServerFarmListResponse serverFarmListResponse = webSiteManagementClient.getServerFarmsOperations().list(webSpaceName); + + // Assert + Assert.assertEquals(200, serverFarmListResponse.getStatusCode()); + Assert.assertNotNull(serverFarmListResponse.getRequestId()); + + ArrayList serverFarmslist = serverFarmListResponse.getServerFarms(); + for (ServerFarmListResponse.ServerFarm serverFarm : serverFarmslist) { + // Assert + Assert.assertNotNull(serverFarm.getCurrentWorkerSize()); + Assert.assertEquals("Default1", serverFarm.getName()); + Assert.assertNotNull(serverFarm.getStatus()); + Assert.assertNotNull(serverFarm.getWorkerSize()); + } + } + + @Test + public void updateServerFarmSuccess() throws Exception { + String webSpaceName = "eastuswebspace"; + + int currentNumberOfWorkersValue = 3; + int numberOfWorkersValue = 3; + + // Arrange + createServerFarm(webSpaceName); + + // Act + ServerFarmUpdateParameters updateParameters = new ServerFarmUpdateParameters(); + updateParameters.setCurrentNumberOfWorkers(currentNumberOfWorkersValue); + updateParameters.setCurrentWorkerSize(ServerFarmWorkerSize.Medium); + updateParameters.setNumberOfWorkers(numberOfWorkersValue); + updateParameters.setStatus(ServerFarmStatus.Ready); + updateParameters.setWorkerSize(ServerFarmWorkerSize.Medium); + ServerFarmUpdateResponse updateOperationResponse = webSiteManagementClient.getServerFarmsOperations().update(webSpaceName, updateParameters); + + // Assert + Assert.assertEquals(200, updateOperationResponse.getStatusCode()); + Assert.assertNotNull(updateOperationResponse.getRequestId()); + + Assert.assertEquals(3, updateOperationResponse.getCurrentNumberOfWorkers()); + Assert.assertEquals(3, updateOperationResponse.getNumberOfWorkers()); + Assert.assertEquals(ServerFarmWorkerSize.Medium, updateOperationResponse.getCurrentWorkerSize()); + Assert.assertEquals("DefaultServerFarm", updateOperationResponse.getName()); + Assert.assertEquals(ServerFarmStatus.Ready, updateOperationResponse.getStatus()); + Assert.assertEquals(ServerFarmWorkerSize.Medium, updateOperationResponse.getWorkerSize()); + } +} \ No newline at end of file diff --git a/management-websites/src/test/java/com/microsoft/windowsazure/management/website/WebSiteManagementIntegrationTestBase.java b/management-websites/src/test/java/com/microsoft/windowsazure/management/website/WebSiteManagementIntegrationTestBase.java new file mode 100644 index 0000000000000..cfcd5ccafa113 --- /dev/null +++ b/management-websites/src/test/java/com/microsoft/windowsazure/management/website/WebSiteManagementIntegrationTestBase.java @@ -0,0 +1,66 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management.website; + +import java.net.URI; +import java.util.Map; + +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Alteration; +import com.microsoft.windowsazure.core.Builder.Registry; +import com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigurationProperties; +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.management.websites.WebSiteManagementClient; +import com.microsoft.windowsazure.management.websites.WebSiteManagementService; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.filter.LoggingFilter; + +public abstract class WebSiteManagementIntegrationTestBase { + protected static String testWebsitePrefix = "azuresdktestwebsite"; + protected static WebSiteManagementClient webSiteManagementClient; + + protected static void createService() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER, new DefaultHttpRequestRetryHandler()); + + // add LoggingFilter to any pipeline that is created + Registry builder = (Registry) config.getBuilder(); + builder.alter(WebSiteManagementClient.class, Client.class, new Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + webSiteManagementClient = WebSiteManagementService.create(config); + } + + protected static Configuration createConfiguration() throws Exception { + String baseUri = System.getenv(ManagementConfiguration.URI); + return ManagementConfiguration.configure( + baseUri != null ? new URI(baseUri) : null, + System.getenv(ManagementConfiguration.SUBSCRIPTION_ID), + System.getenv(ManagementConfiguration.KEYSTORE_PATH), + System.getenv(ManagementConfiguration.KEYSTORE_PASSWORD), + KeyStoreType.fromString(System.getenv(ManagementConfiguration.KEYSTORE_TYPE)) + ); + } +} \ No newline at end of file diff --git a/management-websites/src/test/java/com/microsoft/windowsazure/management/website/WebSiteOperationsTests.java b/management-websites/src/test/java/com/microsoft/windowsazure/management/website/WebSiteOperationsTests.java new file mode 100644 index 0000000000000..64fb23e58d03e --- /dev/null +++ b/management-websites/src/test/java/com/microsoft/windowsazure/management/website/WebSiteOperationsTests.java @@ -0,0 +1,278 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.website; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Random; +import java.util.TimeZone; + +import javax.xml.parsers.ParserConfigurationException; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.management.websites.models.*; +import com.microsoft.windowsazure.exception.ServiceException; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.xml.sax.SAXException; + +public class WebSiteOperationsTests extends WebSiteManagementIntegrationTestBase { + private static String websiteName = testWebsitePrefix + "01"; + private static String webSpaceName = WebSpaceNames.NORTHEUROPEWEBSPACE; + private static String hostName = ".azurewebsites.net"; + + @BeforeClass + public static void setup() throws Exception { + createService(); + cleanup(); + createWebSite(); + } + + @AfterClass + public static void cleanup() { + WebSiteListParameters webSiteListParameters = new WebSiteListParameters(); + ArrayList propertiesToInclude = new ArrayList(); + webSiteListParameters.setPropertiesToInclude(propertiesToInclude); + + WebSiteDeleteParameters webSiteDeleteParameters = new WebSiteDeleteParameters(); + webSiteDeleteParameters.setDeleteAllSlots(true); + webSiteDeleteParameters.setDeleteEmptyServerFarm(true); + webSiteDeleteParameters.setDeleteMetrics(true); + + WebSpacesListWebSitesResponse webSpacesListWebSitesResponse = null; + try { + webSpacesListWebSitesResponse = webSiteManagementClient.getWebSpacesOperations().listWebSites(webSpaceName, webSiteListParameters); + } catch (IOException e1) { + e1.printStackTrace(); + } catch (ServiceException e1) { + e1.printStackTrace(); + } catch (ParserConfigurationException e1) { + e1.printStackTrace(); + } catch (SAXException e1) { + e1.printStackTrace(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); + } + if (webSpacesListWebSitesResponse != null) { + ArrayList webSiteslist = webSpacesListWebSitesResponse.getWebSites(); + for (WebSite webSite : webSiteslist) + { + if (webSite.getName().startsWith(testWebsitePrefix )) + { + String websitename = webSite.getName().replaceFirst(hostName, ""); + try { + webSiteManagementClient.getWebSitesOperations().delete(webSpaceName, websitename, webSiteDeleteParameters); + } catch (IOException e) { + e.printStackTrace(); + } catch (ServiceException e) { + e.printStackTrace(); + } + } + } + } + } + + private static void createWebSite() throws Exception { + ArrayList hostNamesValue = new ArrayList(); + hostNamesValue.add(websiteName + hostName); + + WebSiteCreateParameters.WebSpaceDetails webSpaceDetails = new WebSiteCreateParameters.WebSpaceDetails(); + webSpaceDetails.setGeoRegion(GeoRegionNames.NORTHCENTRALUS); + webSpaceDetails.setPlan(WebSpacePlanNames.VIRTUALDEDICATEDPLAN); + webSpaceDetails.setName(webSpaceName); + + //Arrange + WebSiteCreateParameters createParameters = new WebSiteCreateParameters(); + createParameters.setName(websiteName); + createParameters.setWebSpaceName(webSpaceName); + createParameters.setWebSpace(webSpaceDetails); + createParameters.setSiteMode(WebSiteMode.Basic); + createParameters.setComputeMode(WebSiteComputeMode.Shared); + createParameters.setHostNames(hostNamesValue); + + //Act + WebSiteCreateResponse webSiteCreateResponse = webSiteManagementClient.getWebSitesOperations().create(webSpaceName, createParameters); + Assert.assertEquals(200, webSiteCreateResponse.getStatusCode()); + Assert.assertNotNull( webSiteCreateResponse.getRequestId()); + } + + @Test + public void createWebSiteSuccess() throws Exception { + String webSiteName = testWebsitePrefix + "02"; + ArrayList hostNamesValue = new ArrayList(); + hostNamesValue.add(webSiteName + hostName); + + WebSiteCreateParameters.WebSpaceDetails webSpaceDetails = new WebSiteCreateParameters.WebSpaceDetails(); + webSpaceDetails.setGeoRegion(GeoRegionNames.NORTHCENTRALUS); + webSpaceDetails.setPlan(WebSpacePlanNames.VIRTUALDEDICATEDPLAN); + webSpaceDetails.setName(webSpaceName); + + //Arrange + WebSiteCreateParameters createParameters = new WebSiteCreateParameters(); + createParameters.setName(webSiteName); + createParameters.setWebSpaceName(webSpaceName); + createParameters.setWebSpace(webSpaceDetails); + createParameters.setSiteMode(WebSiteMode.Basic); + createParameters.setComputeMode(WebSiteComputeMode.Shared); + createParameters.setHostNames(hostNamesValue); + + //Act + WebSiteCreateResponse webSiteCreateResponse = webSiteManagementClient.getWebSitesOperations().create(webSpaceName, createParameters); + + //Assert + Assert.assertEquals(200, webSiteCreateResponse.getStatusCode()); + Assert.assertNotNull( webSiteCreateResponse.getRequestId()); + Assert.assertEquals(webSiteName, webSiteCreateResponse.getWebSite().getName()); + } + + @Test + public void getWebSiteSuccess() throws Exception { + //Act + WebSiteGetParameters webSiteGetParameters = new WebSiteGetParameters(); + WebSiteGetResponse webSiteGetResponse = webSiteManagementClient.getWebSitesOperations().get(webSpaceName, websiteName, webSiteGetParameters); + + //Assert + Assert.assertEquals(200, webSiteGetResponse.getStatusCode()); + Assert.assertNotNull(webSiteGetResponse.getRequestId()); + Assert.assertEquals(websiteName, webSiteGetResponse.getWebSite().getName()); + } + + @Test + public void updateWebSiteSuccess() throws Exception { + //Arrange + WebSiteGetParameters webSiteGetParameters = new WebSiteGetParameters(); + + //Act + WebSiteGetResponse webSiteGetResponse = webSiteManagementClient.getWebSitesOperations().get(webSpaceName, websiteName, webSiteGetParameters); + Assert.assertEquals(200, webSiteGetResponse.getStatusCode()); + + WebSiteUpdateParameters updateParameters = new WebSiteUpdateParameters(); + updateParameters.setAvailabilityState(WebSpaceAvailabilityState.Limited); + updateParameters.setSiteMode(WebSiteMode.Limited); + + OperationResponse updateoperationResponse = webSiteManagementClient.getWebSitesOperations().update(webSpaceName, websiteName, updateParameters); + //Assert + Assert.assertEquals(200, updateoperationResponse.getStatusCode()); + Assert.assertNotNull(updateoperationResponse.getRequestId()); + } + + @Test + public void repositoryoperationSuccess() throws Exception { + //Act + OperationResponse createResponse = webSiteManagementClient.getWebSitesOperations().createRepository(webSpaceName, websiteName); + Assert.assertEquals(200, createResponse.getStatusCode()); + Assert.assertNotNull(createResponse.getRequestId()); + + WebSiteGetRepositoryResponse getResponse = webSiteManagementClient.getWebSitesOperations().getRepository(webSpaceName, websiteName); + + //Assert + Assert.assertEquals(200, getResponse.getStatusCode()); + Assert.assertNotNull(getResponse.getRequestId()); + Assert.assertNotNull(getResponse.getUri()); + } + + @Test + public void isHostnameAvailableSuccess() throws Exception { + String webSiteNameInValid = websiteName; + String webSiteNameValid =testWebsitePrefix + "invalidsite"; + + //Act + WebSiteIsHostnameAvailableResponse webSiteIsHostnameAvailableResponseInvalid = webSiteManagementClient.getWebSitesOperations().isHostnameAvailable(webSiteNameInValid); + + //Assert + Assert.assertEquals(200, webSiteIsHostnameAvailableResponseInvalid.getStatusCode()); + Assert.assertNotNull(webSiteIsHostnameAvailableResponseInvalid.getRequestId()); + Assert.assertEquals(false, webSiteIsHostnameAvailableResponseInvalid.isAvailable()); + + WebSiteIsHostnameAvailableResponse webSiteIsHostnameAvailableResponseValid = webSiteManagementClient.getWebSitesOperations().isHostnameAvailable(webSiteNameValid); + Assert.assertEquals(200, webSiteIsHostnameAvailableResponseValid.getStatusCode()); + Assert.assertNotNull(webSiteIsHostnameAvailableResponseValid.getRequestId()); + Assert.assertEquals(true, webSiteIsHostnameAvailableResponseValid.isAvailable()); + } + + @Test + public void restartWebSiteSuccess() throws Exception { + OperationResponse operationResponse = webSiteManagementClient.getWebSitesOperations().restart(webSpaceName, websiteName); + + //Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void generatePasswordSuccess() throws Exception { + OperationResponse operationResponse = webSiteManagementClient.getWebSitesOperations().generatePassword(webSpaceName, websiteName); + + //Assert + Assert.assertEquals(200, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @SuppressWarnings("static-access") + @Test + public void getConfigurationSuccess() throws Exception { + //Act + WebSiteGetConfigurationResponse webSiteGetConfigurationResponse = webSiteManagementClient.getWebSitesOperations().getConfiguration(webSpaceName, websiteName); + + //Assert + Assert.assertEquals(200, webSiteGetConfigurationResponse.getStatusCode()); + Assert.assertNotNull(webSiteGetConfigurationResponse.getRequestId()); + Assert.assertEquals(false, webSiteGetConfigurationResponse.isWebSocketsEnabled()); + Assert.assertEquals("", webSiteGetConfigurationResponse.getDocumentRoot()); + Assert.assertEquals(35, webSiteGetConfigurationResponse.getLogsDirectorySizeLimit().intValue()); + + Assert.assertEquals(Calendar.YEAR, webSiteGetConfigurationResponse.getRequestTracingExpirationTime().YEAR); + Assert.assertEquals(null, webSiteGetConfigurationResponse.getRemoteDebuggingVersion()); + Assert.assertEquals(0, webSiteGetConfigurationResponse.getConnectionStrings().size()); + } + + @Test + public void getHistoricalUsageMetricsSuccess() throws Exception { + WebSiteGetHistoricalUsageMetricsParameters parameters = new WebSiteGetHistoricalUsageMetricsParameters(); + ArrayList list = new ArrayList(); + list.add("test"); + parameters.setMetricNames(list); + + Calendar now = Calendar.getInstance(); + Calendar startTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + startTime.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH) , now.get(Calendar.DATE - 5)); + Calendar endTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + endTime.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH) , now.get(Calendar.DATE - 1)); + parameters.setStartTime(startTime); + parameters.setEndTime(endTime); + + //Act + WebSiteGetHistoricalUsageMetricsResponse webSiteGetHistoricalUsageMetricsResponse = webSiteManagementClient.getWebSitesOperations().getHistoricalUsageMetrics(webSpaceName, websiteName, parameters); + + //Assert + Assert.assertEquals(200, webSiteGetHistoricalUsageMetricsResponse.getStatusCode()); + Assert.assertNotNull(webSiteGetHistoricalUsageMetricsResponse.getRequestId()); + } + + protected static String randomString(int length) { + Random random = new Random(); + StringBuilder stringBuilder = new StringBuilder(length); + for (int i=0; i userlist = webSpacesListPublishingUsersResponse.getUsers(); + for (WebSpacesListPublishingUsersResponse.User user : userlist) { + Assert.assertNotNull(user.getName()); + } + } + + @Test + public void listGeoRegionsSuccess() throws Exception { + // Act + WebSpacesListGeoRegionsResponse webSpacesListGeoRegionsResponse = webSiteManagementClient.getWebSpacesOperations().listGeoRegions(); + // Assert + Assert.assertEquals(200, webSpacesListGeoRegionsResponse.getStatusCode()); + Assert.assertNotNull(webSpacesListGeoRegionsResponse.getRequestId()); + + ArrayList geoRegionslist = webSpacesListGeoRegionsResponse.getGeoRegions(); + for (WebSpacesListGeoRegionsResponse.GeoRegion geoRegion : geoRegionslist) { + Assert.assertNotNull(geoRegion.getName()); + } + } + + @Test + public void listWebSpaceSuccess() throws Exception { + // Act + WebSpacesListResponse webSpacesListResponse = webSiteManagementClient.getWebSpacesOperations().list(); + // Assert + Assert.assertEquals(200, webSpacesListResponse.getStatusCode()); + Assert.assertNotNull( webSpacesListResponse.getRequestId()); + + ArrayList webSpacelist = webSpacesListResponse.getWebSpaces(); + for (WebSpacesListResponse.WebSpace webspace : webSpacelist) { + Assert.assertNotNull(webspace.getAvailabilityState()); + Assert.assertNotNull(webspace.getName()); + } + } + + @Test + public void listWebSitesSuccess() throws Exception { + String webSpaceName = "eastuswebspace"; + WebSiteListParameters webSiteListParameters = new WebSiteListParameters(); + ArrayList propertiesToInclude = new ArrayList(); + webSiteListParameters.setPropertiesToInclude(propertiesToInclude); + + // Act + WebSpacesListWebSitesResponse webSpacesListWebSitesResponse = webSiteManagementClient.getWebSpacesOperations().listWebSites(webSpaceName, webSiteListParameters); + + // Assert + Assert.assertEquals(200, webSpacesListWebSitesResponse.getStatusCode()); + Assert.assertNotNull(webSpacesListWebSitesResponse.getRequestId()); + + ArrayList webSiteslist = webSpacesListWebSitesResponse.getWebSites(); + for (WebSite webSite : webSiteslist) { + //Assert + Assert.assertEquals(WebSpaceAvailabilityState.Normal, webSite.getAvailabilityState()); + Assert.assertNotNull(webSite.getName()); + } + } +} \ No newline at end of file diff --git a/management/pom.xml b/management/pom.xml new file mode 100644 index 0000000000000..85c2048dc64c6 --- /dev/null +++ b/management/pom.xml @@ -0,0 +1,161 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-management + jar + + Microsoft Azure Management Client API + Microsoft Azure Management SDK Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + 2.1.1 + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + org.apache.httpcomponents + httpclient + + + javax.inject + javax.inject + + + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk16 + test + + + + info.cukes + cucumber-java + test + + + info.cukes + cucumber-junit + test + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+
+
diff --git a/management/src/main/java/com/microsoft/windowsazure/management/AffinityGroupOperations.java b/management/src/main/java/com/microsoft/windowsazure/management/AffinityGroupOperations.java new file mode 100644 index 0000000000000..cc5b240116986 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/AffinityGroupOperations.java @@ -0,0 +1,208 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.AffinityGroupCreateParameters; +import com.microsoft.windowsazure.management.models.AffinityGroupGetResponse; +import com.microsoft.windowsazure.management.models.AffinityGroupListResponse; +import com.microsoft.windowsazure.management.models.AffinityGroupUpdateParameters; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* Operations for managing affinity groups in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx for more +* information) +*/ +public interface AffinityGroupOperations { + /** + * The Create Affinity Group operation creates a new affinity group for the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Affinity + * Group operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse create(AffinityGroupCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Create Affinity Group operation creates a new affinity group for the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Affinity + * Group operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future createAsync(AffinityGroupCreateParameters parameters); + + /** + * The Delete Affinity Group operation deletes an affinity group in the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String affinityGroupName) throws IOException, ServiceException; + + /** + * The Delete Affinity Group operation deletes an affinity group in the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String affinityGroupName); + + /** + * The Get Affinity Group Properties operation returns the system properties + * associated with the specified affinity group. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the desired affinity group + * as returned by the name element of the List Affinity Groups operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Affinity Group operation response. + */ + AffinityGroupGetResponse get(String affinityGroupName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Affinity Group Properties operation returns the system properties + * associated with the specified affinity group. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the desired affinity group + * as returned by the name element of the List Affinity Groups operation. + * @return The Get Affinity Group operation response. + */ + Future getAsync(String affinityGroupName); + + /** + * The List Affinity Groups operation lists the affinity groups associated + * with the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Affinity Groups operation response. + */ + AffinityGroupListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Affinity Groups operation lists the affinity groups associated + * with the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for + * more information) + * + * @return The List Affinity Groups operation response. + */ + Future listAsync(); + + /** + * The Update Affinity Group operation updates the label and/or the + * description for an affinity group for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @param parameters Required. Parameters supplied to the Update Affinity + * Group operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse update(String affinityGroupName, AffinityGroupUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Update Affinity Group operation updates the label and/or the + * description for an affinity group for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @param parameters Required. Parameters supplied to the Update Affinity + * Group operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future updateAsync(String affinityGroupName, AffinityGroupUpdateParameters parameters); +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/AffinityGroupOperationsImpl.java b/management/src/main/java/com/microsoft/windowsazure/management/AffinityGroupOperationsImpl.java new file mode 100644 index 0000000000000..b86a2b3f37f47 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/AffinityGroupOperationsImpl.java @@ -0,0 +1,886 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.AffinityGroupCreateParameters; +import com.microsoft.windowsazure.management.models.AffinityGroupGetResponse; +import com.microsoft.windowsazure.management.models.AffinityGroupListResponse; +import com.microsoft.windowsazure.management.models.AffinityGroupUpdateParameters; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Operations for managing affinity groups in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx for more +* information) +*/ +public class AffinityGroupOperationsImpl implements ServiceOperations, AffinityGroupOperations { + /** + * Initializes a new instance of the AffinityGroupOperationsImpl class. + * + * @param client Reference to the service client. + */ + AffinityGroupOperationsImpl(ManagementClientImpl client) { + this.client = client; + } + + private ManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.ManagementClientImpl. + * @return The Client value. + */ + public ManagementClientImpl getClient() { + return this.client; + } + + /** + * The Create Affinity Group operation creates a new affinity group for the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Affinity + * Group operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future createAsync(final AffinityGroupCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return create(parameters); + } + }); + } + + /** + * The Create Affinity Group operation creates a new affinity group for the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Affinity + * Group operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse create(AffinityGroupCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { + throw new IllegalArgumentException("parameters.Description"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getLabel().length() > 100) { + throw new IllegalArgumentException("parameters.Label"); + } + if (parameters.getLocation() == null) { + throw new NullPointerException("parameters.Location"); + } + if (parameters.getName() == null) { + throw new NullPointerException("parameters.Name"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/affinitygroups"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element createAffinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CreateAffinityGroup"); + requestDoc.appendChild(createAffinityGroupElement); + + Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); + nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); + createAffinityGroupElement.appendChild(nameElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + createAffinityGroupElement.appendChild(labelElement); + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + createAffinityGroupElement.appendChild(descriptionElement); + } + + Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Location"); + locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation())); + createAffinityGroupElement.appendChild(locationElement); + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_CREATED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Affinity Group operation deletes an affinity group in the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String affinityGroupName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(affinityGroupName); + } + }); + } + + /** + * The Delete Affinity Group operation deletes an affinity group in the + * specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String affinityGroupName) throws IOException, ServiceException { + // Validate + if (affinityGroupName == null) { + throw new NullPointerException("affinityGroupName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("affinityGroupName", affinityGroupName); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/affinitygroups/" + affinityGroupName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Affinity Group Properties operation returns the system properties + * associated with the specified affinity group. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the desired affinity group + * as returned by the name element of the List Affinity Groups operation. + * @return The Get Affinity Group operation response. + */ + @Override + public Future getAsync(final String affinityGroupName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public AffinityGroupGetResponse call() throws Exception { + return get(affinityGroupName); + } + }); + } + + /** + * The Get Affinity Group Properties operation returns the system properties + * associated with the specified affinity group. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the desired affinity group + * as returned by the name element of the List Affinity Groups operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Affinity Group operation response. + */ + @Override + public AffinityGroupGetResponse get(String affinityGroupName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (affinityGroupName == null) { + throw new NullPointerException("affinityGroupName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("affinityGroupName", affinityGroupName); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/affinitygroups/" + affinityGroupName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + AffinityGroupGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new AffinityGroupGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element affinityGroupElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); + if (affinityGroupElement != null) { + Element nameElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + result.setName(nameInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + result.setLabel(labelInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + result.setDescription(descriptionInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + result.setLocation(locationInstance); + } + + Element hostedServicesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "HostedServices"); + if (hostedServicesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostedServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "HostedService").size(); i1 = i1 + 1) { + org.w3c.dom.Element hostedServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(hostedServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "HostedService").get(i1)); + AffinityGroupGetResponse.HostedServiceReference hostedServiceInstance = new AffinityGroupGetResponse.HostedServiceReference(); + result.getHostedServices().add(hostedServiceInstance); + + Element urlElement = XmlUtility.getElementByTagNameNS(hostedServicesElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement != null) { + URI urlInstance; + urlInstance = new URI(urlElement.getTextContent()); + hostedServiceInstance.setUri(urlInstance); + } + + Element serviceNameElement = XmlUtility.getElementByTagNameNS(hostedServicesElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement != null) { + String serviceNameInstance; + serviceNameInstance = serviceNameElement.getTextContent(); + hostedServiceInstance.setServiceName(serviceNameInstance); + } + } + } + + Element storageServicesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "StorageServices"); + if (storageServicesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storageServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "StorageService").size(); i2 = i2 + 1) { + org.w3c.dom.Element storageServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(storageServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "StorageService").get(i2)); + AffinityGroupGetResponse.StorageServiceReference storageServiceInstance = new AffinityGroupGetResponse.StorageServiceReference(); + result.getStorageServices().add(storageServiceInstance); + + Element urlElement2 = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "Url"); + if (urlElement2 != null) { + URI urlInstance2; + urlInstance2 = new URI(urlElement2.getTextContent()); + storageServiceInstance.setUri(urlInstance2); + } + + Element serviceNameElement2 = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); + if (serviceNameElement2 != null) { + String serviceNameInstance2; + serviceNameInstance2 = serviceNameElement2.getTextContent(); + storageServiceInstance.setServiceName(serviceNameInstance2); + } + } + } + + Element capabilitiesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Capabilities"); + if (capabilitiesSequenceElement != null) { + for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(capabilitiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Capability").size(); i3 = i3 + 1) { + org.w3c.dom.Element capabilitiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(capabilitiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Capability").get(i3)); + result.getCapabilities().add(capabilitiesElement.getTextContent()); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Affinity Groups operation lists the affinity groups associated + * with the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for + * more information) + * + * @return The List Affinity Groups operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public AffinityGroupListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Affinity Groups operation lists the affinity groups associated + * with the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Affinity Groups operation response. + */ + @Override + public AffinityGroupListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/affinitygroups"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + AffinityGroupListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new AffinityGroupListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element affinityGroupsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "AffinityGroups"); + if (affinityGroupsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(affinityGroupsSequenceElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup").size(); i1 = i1 + 1) { + org.w3c.dom.Element affinityGroupsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(affinityGroupsSequenceElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup").get(i1)); + AffinityGroupListResponse.AffinityGroup affinityGroupInstance = new AffinityGroupListResponse.AffinityGroup(); + result.getAffinityGroups().add(affinityGroupInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + affinityGroupInstance.setName(nameInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; + affinityGroupInstance.setLabel(labelInstance); + } + + Element descriptionElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Description"); + if (descriptionElement != null) { + String descriptionInstance; + descriptionInstance = descriptionElement.getTextContent(); + affinityGroupInstance.setDescription(descriptionInstance); + } + + Element locationElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Location"); + if (locationElement != null) { + String locationInstance; + locationInstance = locationElement.getTextContent(); + affinityGroupInstance.setLocation(locationInstance); + } + + Element capabilitiesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Capabilities"); + if (capabilitiesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(capabilitiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Capability").size(); i2 = i2 + 1) { + org.w3c.dom.Element capabilitiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(capabilitiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Capability").get(i2)); + affinityGroupInstance.getCapabilities().add(capabilitiesElement.getTextContent()); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Update Affinity Group operation updates the label and/or the + * description for an affinity group for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @param parameters Required. Parameters supplied to the Update Affinity + * Group operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future updateAsync(final String affinityGroupName, final AffinityGroupUpdateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return update(affinityGroupName, parameters); + } + }); + } + + /** + * The Update Affinity Group operation updates the label and/or the + * description for an affinity group for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for + * more information) + * + * @param affinityGroupName Required. The name of the affinity group. + * @param parameters Required. Parameters supplied to the Update Affinity + * Group operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse update(String affinityGroupName, AffinityGroupUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (affinityGroupName == null) { + throw new NullPointerException("affinityGroupName"); + } + if (parameters == null) { + throw new NullPointerException("parameters"); + } + if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { + throw new IllegalArgumentException("parameters.Description"); + } + if (parameters.getLabel() == null) { + throw new NullPointerException("parameters.Label"); + } + if (parameters.getLabel().length() > 100) { + throw new IllegalArgumentException("parameters.Label"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("affinityGroupName", affinityGroupName); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/affinitygroups/" + affinityGroupName.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element updateAffinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateAffinityGroup"); + requestDoc.appendChild(updateAffinityGroupElement); + + Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); + labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); + updateAffinityGroupElement.appendChild(labelElement); + + if (parameters.getDescription() != null) { + Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); + descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); + updateAffinityGroupElement.appendChild(descriptionElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/Exports.java b/management/src/main/java/com/microsoft/windowsazure/management/Exports.java new file mode 100644 index 0000000000000..f72b98388ba50 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/Exports.java @@ -0,0 +1,31 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.Builder; + +/** + * The Class Exports. + */ +public class Exports implements Builder.Exports { + /* (non-Javadoc) + * @see com.microsoft.windowsazure.services.core.Builder.Exports#register(com.microsoft.windowsazure.services.core.Builder.Registry) + */ + @Override + public void register(Builder.Registry registry) { + // provide contract implementation + registry.add(ManagementClient.class, ManagementClientImpl.class); + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/LocationOperations.java b/management/src/main/java/com/microsoft/windowsazure/management/LocationOperations.java new file mode 100644 index 0000000000000..15354c4a9466a --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/LocationOperations.java @@ -0,0 +1,67 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.LocationsListResponse; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for listing the available data +* center locations for a hosted service in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx for more +* information) +*/ +public interface LocationOperations { + /** + * The List Locations operation lists all of the data center locations that + * are valid for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441293.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Locations operation response. + */ + LocationsListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Locations operation lists all of the data center locations that + * are valid for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441293.aspx for + * more information) + * + * @return The List Locations operation response. + */ + Future listAsync(); +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/LocationOperationsImpl.java b/management/src/main/java/com/microsoft/windowsazure/management/LocationOperationsImpl.java new file mode 100644 index 0000000000000..41241e709885e --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/LocationOperationsImpl.java @@ -0,0 +1,214 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.LocationsListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for listing the available data +* center locations for a hosted service in your subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx for more +* information) +*/ +public class LocationOperationsImpl implements ServiceOperations, LocationOperations { + /** + * Initializes a new instance of the LocationOperationsImpl class. + * + * @param client Reference to the service client. + */ + LocationOperationsImpl(ManagementClientImpl client) { + this.client = client; + } + + private ManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.ManagementClientImpl. + * @return The Client value. + */ + public ManagementClientImpl getClient() { + return this.client; + } + + /** + * The List Locations operation lists all of the data center locations that + * are valid for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441293.aspx for + * more information) + * + * @return The List Locations operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public LocationsListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Locations operation lists all of the data center locations that + * are valid for your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441293.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Locations operation response. + */ + @Override + public LocationsListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/locations"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + LocationsListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new LocationsListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element locationsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Locations"); + if (locationsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(locationsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Location").size(); i1 = i1 + 1) { + org.w3c.dom.Element locationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(locationsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Location").get(i1)); + LocationsListResponse.Location locationInstance = new LocationsListResponse.Location(); + result.getLocations().add(locationInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(locationsElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + locationInstance.setName(nameInstance); + } + + Element displayNameElement = XmlUtility.getElementByTagNameNS(locationsElement, "http://schemas.microsoft.com/windowsazure", "DisplayName"); + if (displayNameElement != null) { + String displayNameInstance; + displayNameInstance = displayNameElement.getTextContent(); + locationInstance.setDisplayName(displayNameInstance); + } + + Element availableServicesSequenceElement = XmlUtility.getElementByTagNameNS(locationsElement, "http://schemas.microsoft.com/windowsazure", "AvailableServices"); + if (availableServicesSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(availableServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "AvailableService").size(); i2 = i2 + 1) { + org.w3c.dom.Element availableServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(availableServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "AvailableService").get(i2)); + locationInstance.getAvailableServices().add(availableServicesElement.getTextContent()); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/ManagementCertificateOperations.java b/management/src/main/java/com/microsoft/windowsazure/management/ManagementCertificateOperations.java new file mode 100644 index 0000000000000..4d413167011d2 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/ManagementCertificateOperations.java @@ -0,0 +1,193 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.ManagementCertificateCreateParameters; +import com.microsoft.windowsazure.management.models.ManagementCertificateGetResponse; +import com.microsoft.windowsazure.management.models.ManagementCertificateListResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import org.xml.sax.SAXException; + +/** +* You can use management certificates, which are also known as subscription +* certificates, to authenticate clients attempting to connect to resources +* associated with your Azure subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for more +* information) +*/ +public interface ManagementCertificateOperations { + /** + * The Create Management Certificate operation adds a certificate to the + * list of management certificates. Management certificates, which are also + * known as subscription certificates, authenticate clients attempting to + * connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Management + * Certificate operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse create(ManagementCertificateCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException; + + /** + * The Create Management Certificate operation adds a certificate to the + * list of management certificates. Management certificates, which are also + * known as subscription certificates, authenticate clients attempting to + * connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Management + * Certificate operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future createAsync(ManagementCertificateCreateParameters parameters); + + /** + * The Delete Management Certificate operation deletes a certificate from + * the list of management certificates. Management certificates, which are + * also known as subscription certificates, authenticate clients attempting + * to connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * delete. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse delete(String thumbprint) throws IOException, ServiceException; + + /** + * The Delete Management Certificate operation deletes a certificate from + * the list of management certificates. Management certificates, which are + * also known as subscription certificates, authenticate clients attempting + * to connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * delete. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future deleteAsync(String thumbprint); + + /** + * The Get Management Certificate operation retrieves information about the + * management certificate with the specified thumbprint. Management + * certificates, which are also known as subscription certificates, + * authenticate clients attempting to connect to resources associated with + * your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * retrieve information about. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Management Certificate operation response. + */ + ManagementCertificateGetResponse get(String thumbprint) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Management Certificate operation retrieves information about the + * management certificate with the specified thumbprint. Management + * certificates, which are also known as subscription certificates, + * authenticate clients attempting to connect to resources associated with + * your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * retrieve information about. + * @return The Get Management Certificate operation response. + */ + Future getAsync(String thumbprint); + + /** + * The List Management Certificates operation lists and returns basic + * information about all of the management certificates associated with the + * specified subscription. Management certificates, which are also known as + * subscription certificates, authenticate clients attempting to connect to + * resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Management Certificates operation response. + */ + ManagementCertificateListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Management Certificates operation lists and returns basic + * information about all of the management certificates associated with the + * specified subscription. Management certificates, which are also known as + * subscription certificates, authenticate clients attempting to connect to + * resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @return The List Management Certificates operation response. + */ + Future listAsync(); +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/ManagementCertificateOperationsImpl.java b/management/src/main/java/com/microsoft/windowsazure/management/ManagementCertificateOperationsImpl.java new file mode 100644 index 0000000000000..0d80e5b0150b2 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/ManagementCertificateOperationsImpl.java @@ -0,0 +1,672 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.ManagementCertificateCreateParameters; +import com.microsoft.windowsazure.management.models.ManagementCertificateGetResponse; +import com.microsoft.windowsazure.management.models.ManagementCertificateListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URISyntaxException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* You can use management certificates, which are also known as subscription +* certificates, to authenticate clients attempting to connect to resources +* associated with your Azure subscription. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for more +* information) +*/ +public class ManagementCertificateOperationsImpl implements ServiceOperations, ManagementCertificateOperations { + /** + * Initializes a new instance of the ManagementCertificateOperationsImpl + * class. + * + * @param client Reference to the service client. + */ + ManagementCertificateOperationsImpl(ManagementClientImpl client) { + this.client = client; + } + + private ManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.ManagementClientImpl. + * @return The Client value. + */ + public ManagementClientImpl getClient() { + return this.client; + } + + /** + * The Create Management Certificate operation adds a certificate to the + * list of management certificates. Management certificates, which are also + * known as subscription certificates, authenticate clients attempting to + * connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Management + * Certificate operation. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future createAsync(final ManagementCertificateCreateParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return create(parameters); + } + }); + } + + /** + * The Create Management Certificate operation adds a certificate to the + * list of management certificates. Management certificates, which are also + * known as subscription certificates, authenticate clients attempting to + * connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the Create Management + * Certificate operation. + * @throws ParserConfigurationException Thrown if there was an error + * configuring the parser for the response body. + * @throws SAXException Thrown if there was an error parsing the response + * body. + * @throws TransformerException Thrown if there was an error creating the + * DOM transformer. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse create(ManagementCertificateCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/certificates"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPost httpRequest = new HttpPost(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Serialize Request + String requestContent = null; + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document requestDoc = documentBuilder.newDocument(); + + Element subscriptionCertificateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate"); + requestDoc.appendChild(subscriptionCertificateElement); + + if (parameters.getPublicKey() != null) { + Element subscriptionCertificatePublicKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey"); + subscriptionCertificatePublicKeyElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getPublicKey()))); + subscriptionCertificateElement.appendChild(subscriptionCertificatePublicKeyElement); + } + + if (parameters.getThumbprint() != null) { + Element subscriptionCertificateThumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint"); + subscriptionCertificateThumbprintElement.appendChild(requestDoc.createTextNode(parameters.getThumbprint())); + subscriptionCertificateElement.appendChild(subscriptionCertificateThumbprintElement); + } + + if (parameters.getData() != null) { + Element subscriptionCertificateDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData"); + subscriptionCertificateDataElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData()))); + subscriptionCertificateElement.appendChild(subscriptionCertificateDataElement); + } + + DOMSource domSource = new DOMSource(requestDoc); + StringWriter stringWriter = new StringWriter(); + StreamResult streamResult = new StreamResult(stringWriter); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.transform(domSource, streamResult); + requestContent = stringWriter.toString(); + StringEntity entity = new StringEntity(requestContent); + httpRequest.setEntity(entity); + httpRequest.setHeader("Content-Type", "application/xml"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Delete Management Certificate operation deletes a certificate from + * the list of management certificates. Management certificates, which are + * also known as subscription certificates, authenticate clients attempting + * to connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * delete. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future deleteAsync(final String thumbprint) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return delete(thumbprint); + } + }); + } + + /** + * The Delete Management Certificate operation deletes a certificate from + * the list of management certificates. Management certificates, which are + * also known as subscription certificates, authenticate clients attempting + * to connect to resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * delete. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse delete(String thumbprint) throws IOException, ServiceException { + // Validate + if (thumbprint == null) { + throw new NullPointerException("thumbprint"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("thumbprint", thumbprint); + CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/certificates/" + thumbprint.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + CustomHttpDelete httpRequest = new CustomHttpDelete(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NOT_FOUND) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The Get Management Certificate operation retrieves information about the + * management certificate with the specified thumbprint. Management + * certificates, which are also known as subscription certificates, + * authenticate clients attempting to connect to resources associated with + * your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * retrieve information about. + * @return The Get Management Certificate operation response. + */ + @Override + public Future getAsync(final String thumbprint) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ManagementCertificateGetResponse call() throws Exception { + return get(thumbprint); + } + }); + } + + /** + * The Get Management Certificate operation retrieves information about the + * management certificate with the specified thumbprint. Management + * certificates, which are also known as subscription certificates, + * authenticate clients attempting to connect to resources associated with + * your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx for + * more information) + * + * @param thumbprint Required. The thumbprint value of the certificate to + * retrieve information about. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Management Certificate operation response. + */ + @Override + public ManagementCertificateGetResponse get(String thumbprint) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + if (thumbprint == null) { + throw new NullPointerException("thumbprint"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("thumbprint", thumbprint); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/certificates/" + thumbprint.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ManagementCertificateGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ManagementCertificateGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element subscriptionCertificateElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate"); + if (subscriptionCertificateElement != null) { + Element subscriptionCertificatePublicKeyElement = XmlUtility.getElementByTagNameNS(subscriptionCertificateElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey"); + if (subscriptionCertificatePublicKeyElement != null) { + byte[] subscriptionCertificatePublicKeyInstance; + subscriptionCertificatePublicKeyInstance = subscriptionCertificatePublicKeyElement.getTextContent() != null ? Base64.decode(subscriptionCertificatePublicKeyElement.getTextContent()) : null; + result.setPublicKey(subscriptionCertificatePublicKeyInstance); + } + + Element subscriptionCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(subscriptionCertificateElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint"); + if (subscriptionCertificateThumbprintElement != null) { + String subscriptionCertificateThumbprintInstance; + subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.getTextContent(); + result.setThumbprint(subscriptionCertificateThumbprintInstance); + } + + Element subscriptionCertificateDataElement = XmlUtility.getElementByTagNameNS(subscriptionCertificateElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData"); + if (subscriptionCertificateDataElement != null) { + byte[] subscriptionCertificateDataInstance; + subscriptionCertificateDataInstance = subscriptionCertificateDataElement.getTextContent() != null ? Base64.decode(subscriptionCertificateDataElement.getTextContent()) : null; + result.setData(subscriptionCertificateDataInstance); + } + + Element createdElement = XmlUtility.getElementByTagNameNS(subscriptionCertificateElement, "http://schemas.microsoft.com/windowsazure", "Created"); + if (createdElement != null) { + Calendar createdInstance; + createdInstance = DatatypeConverter.parseDateTime(createdElement.getTextContent()); + result.setCreated(createdInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Management Certificates operation lists and returns basic + * information about all of the management certificates associated with the + * specified subscription. Management certificates, which are also known as + * subscription certificates, authenticate clients attempting to connect to + * resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @return The List Management Certificates operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public ManagementCertificateListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Management Certificates operation lists and returns basic + * information about all of the management certificates associated with the + * specified subscription. Management certificates, which are also known as + * subscription certificates, authenticate clients attempting to connect to + * resources associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Management Certificates operation response. + */ + @Override + public ManagementCertificateListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/certificates"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + ManagementCertificateListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new ManagementCertificateListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element subscriptionCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificates"); + if (subscriptionCertificatesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subscriptionCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate").size(); i1 = i1 + 1) { + org.w3c.dom.Element subscriptionCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subscriptionCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate").get(i1)); + ManagementCertificateListResponse.SubscriptionCertificate subscriptionCertificateInstance = new ManagementCertificateListResponse.SubscriptionCertificate(); + result.getSubscriptionCertificates().add(subscriptionCertificateInstance); + + Element subscriptionCertificatePublicKeyElement = XmlUtility.getElementByTagNameNS(subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey"); + if (subscriptionCertificatePublicKeyElement != null) { + byte[] subscriptionCertificatePublicKeyInstance; + subscriptionCertificatePublicKeyInstance = subscriptionCertificatePublicKeyElement.getTextContent() != null ? Base64.decode(subscriptionCertificatePublicKeyElement.getTextContent()) : null; + subscriptionCertificateInstance.setPublicKey(subscriptionCertificatePublicKeyInstance); + } + + Element subscriptionCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint"); + if (subscriptionCertificateThumbprintElement != null) { + String subscriptionCertificateThumbprintInstance; + subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.getTextContent(); + subscriptionCertificateInstance.setThumbprint(subscriptionCertificateThumbprintInstance); + } + + Element subscriptionCertificateDataElement = XmlUtility.getElementByTagNameNS(subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData"); + if (subscriptionCertificateDataElement != null) { + byte[] subscriptionCertificateDataInstance; + subscriptionCertificateDataInstance = subscriptionCertificateDataElement.getTextContent() != null ? Base64.decode(subscriptionCertificateDataElement.getTextContent()) : null; + subscriptionCertificateInstance.setData(subscriptionCertificateDataInstance); + } + + Element createdElement = XmlUtility.getElementByTagNameNS(subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Created"); + if (createdElement != null) { + Calendar createdInstance; + createdInstance = DatatypeConverter.parseDateTime(createdElement.getTextContent()); + subscriptionCertificateInstance.setCreated(createdInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/ManagementClient.java b/management/src/main/java/com/microsoft/windowsazure/management/ManagementClient.java new file mode 100644 index 0000000000000..584025c74a399 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/ManagementClient.java @@ -0,0 +1,158 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.FilterableService; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import java.io.Closeable; +import java.io.IOException; +import java.net.URI; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API provides programmatic access to much of the +* functionality available through the Management Portal. The Service +* Management API is a REST API. All API operations are performed over SSL and +* are mutually authenticated using X.509 v3 certificates. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for more +* information) +*/ +public interface ManagementClient extends Closeable, FilterableService { + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + URI getBaseUri(); + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + SubscriptionCloudCredentials getCredentials(); + + /** + * Operations for managing affinity groups in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx for + * more information) + * @return The AffinityGroupsOperations value. + */ + AffinityGroupOperations getAffinityGroupsOperations(); + + /** + * The Service Management API includes operations for listing the available + * data center locations for a hosted service in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx for + * more information) + * @return The LocationsOperations value. + */ + LocationOperations getLocationsOperations(); + + /** + * You can use management certificates, which are also known as subscription + * certificates, to authenticate clients attempting to connect to resources + * associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for + * more information) + * @return The ManagementCertificatesOperations value. + */ + ManagementCertificateOperations getManagementCertificatesOperations(); + + /** + * The Service Management API includes operations for listing the available + * role sizes for VMs in your subscription. + * @return The RoleSizesOperations value. + */ + RoleSizeOperations getRoleSizesOperations(); + + /** + * Operations for listing subscription details. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715315.aspx for + * more information) + * @return The SubscriptionsOperations value. + */ + SubscriptionOperations getSubscriptionsOperations(); + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + Future getOperationStatusAsync(String requestId); +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/ManagementClientImpl.java b/management/src/main/java/com/microsoft/windowsazure/management/ManagementClientImpl.java new file mode 100644 index 0000000000000..d7bfdc3135d3b --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/ManagementClientImpl.java @@ -0,0 +1,416 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.OperationStatus; +import com.microsoft.windowsazure.core.OperationStatusResponse; +import com.microsoft.windowsazure.core.ServiceClient; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import javax.inject.Inject; +import javax.inject.Named; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API provides programmatic access to much of the +* functionality available through the Management Portal. The Service +* Management API is a REST API. All API operations are performed over SSL and +* are mutually authenticated using X.509 v3 certificates. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for more +* information) +*/ +public class ManagementClientImpl extends ServiceClient implements ManagementClient { + private URI baseUri; + + /** + * The URI used as the base for all Service Management requests. + * @return The BaseUri value. + */ + public URI getBaseUri() { + return this.baseUri; + } + + private SubscriptionCloudCredentials credentials; + + /** + * When you create an Azure subscription, it is uniquely identified by a + * subscription ID. The subscription ID forms part of the URI for every + * call that you make to the Service Management API. The Azure Service + * Management API uses mutual authentication of management certificates + * over SSL to ensure that a request made to the service is secure. No + * anonymous requests are allowed. + * @return The Credentials value. + */ + public SubscriptionCloudCredentials getCredentials() { + return this.credentials; + } + + private AffinityGroupOperations affinityGroups; + + /** + * Operations for managing affinity groups in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx for + * more information) + * @return The AffinityGroupsOperations value. + */ + public AffinityGroupOperations getAffinityGroupsOperations() { + return this.affinityGroups; + } + + private LocationOperations locations; + + /** + * The Service Management API includes operations for listing the available + * data center locations for a hosted service in your subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg441299.aspx for + * more information) + * @return The LocationsOperations value. + */ + public LocationOperations getLocationsOperations() { + return this.locations; + } + + private ManagementCertificateOperations managementCertificates; + + /** + * You can use management certificates, which are also known as subscription + * certificates, to authenticate clients attempting to connect to resources + * associated with your Azure subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for + * more information) + * @return The ManagementCertificatesOperations value. + */ + public ManagementCertificateOperations getManagementCertificatesOperations() { + return this.managementCertificates; + } + + private RoleSizeOperations roleSizes; + + /** + * The Service Management API includes operations for listing the available + * role sizes for VMs in your subscription. + * @return The RoleSizesOperations value. + */ + public RoleSizeOperations getRoleSizesOperations() { + return this.roleSizes; + } + + private SubscriptionOperations subscriptions; + + /** + * Operations for listing subscription details. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715315.aspx for + * more information) + * @return The SubscriptionsOperations value. + */ + public SubscriptionOperations getSubscriptionsOperations() { + return this.subscriptions; + } + + /** + * Initializes a new instance of the ManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + private ManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) { + super(httpBuilder, executorService); + this.affinityGroups = new AffinityGroupOperationsImpl(this); + this.locations = new LocationOperationsImpl(this); + this.managementCertificates = new ManagementCertificateOperationsImpl(this); + this.roleSizes = new RoleSizeOperationsImpl(this); + this.subscriptions = new SubscriptionOperationsImpl(this); + } + + /** + * Initializes a new instance of the ManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @param baseUri Required. The URI used as the base for all Service + * Management requests. + */ + @Inject + public ManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } else { + this.credentials = credentials; + } + if (baseUri == null) { + try { + this.baseUri = new URI("https://management.core.windows.net"); + } + catch (URISyntaxException ex) { + } + } else { + this.baseUri = baseUri; + } + } + + /** + * Initializes a new instance of the ManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + * @param credentials Required. When you create an Azure subscription, it is + * uniquely identified by a subscription ID. The subscription ID forms part + * of the URI for every call that you make to the Service Management API. + * The Azure Service Management API uses mutual authentication of + * management certificates over SSL to ensure that a request made to the + * service is secure. No anonymous requests are allowed. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + */ + public ManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException { + this(httpBuilder, executorService); + if (credentials == null) { + throw new NullPointerException("credentials"); + } + this.credentials = credentials; + this.baseUri = new URI("https://management.core.windows.net"); + } + + /** + * Initializes a new instance of the ManagementClientImpl class. + * + * @param httpBuilder The HTTP client builder. + * @param executorService The executor service. + */ + protected ManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) { + return new ManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri()); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public Future getOperationStatusAsync(final String requestId) { + return this.getExecutorService().submit(new Callable() { + @Override + public OperationStatusResponse call() throws Exception { + return getOperationStatus(requestId); + } + }); + } + + /** + * The Get Operation Status operation returns the status of the specified + * operation. After calling an asynchronous operation, you can call Get + * Operation Status to determine whether the operation has succeeded, + * failed, or is still in progress. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for + * more information) + * + * @param requestId Required. The request ID for the request you wish to + * track. The request ID is returned in the x-ms-request-id response header + * for every request. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The response body contains the status of the specified + * asynchronous operation, indicating whether it has succeeded, is + * inprogress, or has failed. Note that this status is distinct from the + * HTTP status code returned for the Get Operation Status operation itself. + * If the asynchronous operation succeeded, the response body includes the + * HTTP status code for the successful request. If the asynchronous + * operation failed, the response body includes the HTTP status code for + * the failed request, and also includes error information regarding the + * failure. + */ + @Override + public OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (requestId == null) { + throw new NullPointerException("requestId"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("requestId", requestId); + CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getBaseUri().toString(); + String url = "/" + this.getCredentials().getSubscriptionId().trim() + "/operations/" + requestId.trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationStatusResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new OperationStatusResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); + if (operationElement != null) { + Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ID"); + if (idElement != null) { + String idInstance; + idInstance = idElement.getTextContent(); + result.setId(idInstance); + } + + Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); + if (statusElement != null) { + OperationStatus statusInstance; + statusInstance = OperationStatus.valueOf(statusElement.getTextContent()); + result.setStatus(statusInstance); + } + + Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "HttpStatusCode"); + if (httpStatusCodeElement != null) { + Integer httpStatusCodeInstance; + httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent()); + result.setHttpStatusCode(httpStatusCodeInstance); + } + + Element errorElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Error"); + if (errorElement != null) { + OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); + result.setError(errorInstance); + + Element codeElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Code"); + if (codeElement != null) { + String codeInstance; + codeInstance = codeElement.getTextContent(); + errorInstance.setCode(codeInstance); + } + + Element messageElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Message"); + if (messageElement != null) { + String messageInstance; + messageInstance = messageElement.getTextContent(); + errorInstance.setMessage(messageInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/ManagementService.java b/management/src/main/java/com/microsoft/windowsazure/management/ManagementService.java new file mode 100644 index 0000000000000..986622583ddb2 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/ManagementService.java @@ -0,0 +1,74 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.Configuration; + +/** + * + * Access service management functionality. + * + */ +public final class ManagementService { + private ManagementService() { + // class is not instantiated + } + + /** + * Creates an instance of the ManagementClient API. + * @return An instance of the ManagementClient API. + */ + public static ManagementClient create() { + return Configuration.getInstance().create(ManagementClient.class); + } + + /** + * Creates an instance of the ManagementClient API using the + * specified configuration. + * + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the ManagementClient API. + */ + public static ManagementClient create(final Configuration config) { + return config.create(ManagementClient.class); + } + + /** + * Creates an instance of the ManagementClient API. + * + * @param profile A String object that representing the profile + * of the service management service. + * @return An instance of the ManagementClient API. + */ + public static ManagementClient create(final String profile) { + return Configuration.getInstance().create(profile, + ManagementClient.class); + } + + /** + * Creates an instance of the ManagementClient API using the + * specified configuration. + * + * @param profile The profile. + * @param config A Configuration object that represents the + * configuration for the service management. + * @return An instance of the ManagementClient API. + */ + public static ManagementClient create(final String profile, + final Configuration config) { + return config.create(profile, ManagementClient.class); + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/RoleSizeOperations.java b/management/src/main/java/com/microsoft/windowsazure/management/RoleSizeOperations.java new file mode 100644 index 0000000000000..813dbf1a239fa --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/RoleSizeOperations.java @@ -0,0 +1,61 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.RoleSizeListResponse; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for listing the available role +* sizes for VMs in your subscription. +*/ +public interface RoleSizeOperations { + /** + * The List Role Sizes operation lists all of the role sizes that are valid + * for your subscription. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Role Sizes operation response. + */ + RoleSizeListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Role Sizes operation lists all of the role sizes that are valid + * for your subscription. + * + * @return The List Role Sizes operation response. + */ + Future listAsync(); +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/RoleSizeOperationsImpl.java b/management/src/main/java/com/microsoft/windowsazure/management/RoleSizeOperationsImpl.java new file mode 100644 index 0000000000000..f057ed9289d58 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/RoleSizeOperationsImpl.java @@ -0,0 +1,229 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.RoleSizeListResponse; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* The Service Management API includes operations for listing the available role +* sizes for VMs in your subscription. +*/ +public class RoleSizeOperationsImpl implements ServiceOperations, RoleSizeOperations { + /** + * Initializes a new instance of the RoleSizeOperationsImpl class. + * + * @param client Reference to the service client. + */ + RoleSizeOperationsImpl(ManagementClientImpl client) { + this.client = client; + } + + private ManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.ManagementClientImpl. + * @return The Client value. + */ + public ManagementClientImpl getClient() { + return this.client; + } + + /** + * The List Role Sizes operation lists all of the role sizes that are valid + * for your subscription. + * + * @return The List Role Sizes operation response. + */ + @Override + public Future listAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public RoleSizeListResponse call() throws Exception { + return list(); + } + }); + } + + /** + * The List Role Sizes operation lists all of the role sizes that are valid + * for your subscription. + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Role Sizes operation response. + */ + @Override + public RoleSizeListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/rolesizes"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + RoleSizeListResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new RoleSizeListResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element roleSizesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "RoleSizes"); + if (roleSizesSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize").size(); i1 = i1 + 1) { + org.w3c.dom.Element roleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(roleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize").get(i1)); + RoleSizeListResponse.RoleSize roleSizeInstance = new RoleSizeListResponse.RoleSize(); + result.getRoleSizes().add(roleSizeInstance); + + Element nameElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "Name"); + if (nameElement != null) { + String nameInstance; + nameInstance = nameElement.getTextContent(); + roleSizeInstance.setName(nameInstance); + } + + Element labelElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "Label"); + if (labelElement != null) { + String labelInstance; + labelInstance = labelElement.getTextContent(); + roleSizeInstance.setLabel(labelInstance); + } + + Element coresElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "Cores"); + if (coresElement != null) { + int coresInstance; + coresInstance = DatatypeConverter.parseInt(coresElement.getTextContent()); + roleSizeInstance.setCores(coresInstance); + } + + Element memoryInMbElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "MemoryInMb"); + if (memoryInMbElement != null) { + int memoryInMbInstance; + memoryInMbInstance = DatatypeConverter.parseInt(memoryInMbElement.getTextContent()); + roleSizeInstance.setMemoryInMb(memoryInMbInstance); + } + + Element supportedByWebWorkerRolesElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "SupportedByWebWorkerRoles"); + if (supportedByWebWorkerRolesElement != null) { + boolean supportedByWebWorkerRolesInstance; + supportedByWebWorkerRolesInstance = DatatypeConverter.parseBoolean(supportedByWebWorkerRolesElement.getTextContent().toLowerCase()); + roleSizeInstance.setSupportedByWebWorkerRoles(supportedByWebWorkerRolesInstance); + } + + Element supportedByVirtualMachinesElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "SupportedByVirtualMachines"); + if (supportedByVirtualMachinesElement != null) { + boolean supportedByVirtualMachinesInstance; + supportedByVirtualMachinesInstance = DatatypeConverter.parseBoolean(supportedByVirtualMachinesElement.getTextContent().toLowerCase()); + roleSizeInstance.setSupportedByVirtualMachines(supportedByVirtualMachinesInstance); + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/SubscriptionOperations.java b/management/src/main/java/com/microsoft/windowsazure/management/SubscriptionOperations.java new file mode 100644 index 0000000000000..1d0347a9c446b --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/SubscriptionOperations.java @@ -0,0 +1,150 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.SubscriptionGetResponse; +import com.microsoft.windowsazure.management.models.SubscriptionListOperationsParameters; +import com.microsoft.windowsazure.management.models.SubscriptionListOperationsResponse; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.concurrent.Future; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; + +/** +* Operations for listing subscription details. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg715315.aspx for more +* information) +*/ +public interface SubscriptionOperations { + /** + * The Get Subscription operation returns account and resource allocation + * information for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Subscription operation response. + */ + SubscriptionGetResponse get() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException; + + /** + * The Get Subscription operation returns account and resource allocation + * information for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx for + * more information) + * + * @return The Get Subscription operation response. + */ + Future getAsync(); + + /** + * The List Subscription Operations operation returns a list of create, + * update, and delete operations that were performed on a subscription + * during the specified timeframe. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the List Subscription + * Operations operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Subscription Operations operation response. + */ + SubscriptionListOperationsResponse listOperations(SubscriptionListOperationsParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException; + + /** + * The List Subscription Operations operation returns a list of create, + * update, and delete operations that were performed on a subscription + * during the specified timeframe. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the List Subscription + * Operations operation. + * @return The List Subscription Operations operation response. + */ + Future listOperationsAsync(SubscriptionListOperationsParameters parameters); + + /** + * Register a resource with your subscription. + * + * @param resourceName Required. Name of the resource to register. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse registerResource(String resourceName) throws IOException, ServiceException; + + /** + * Register a resource with your subscription. + * + * @param resourceName Required. Name of the resource to register. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future registerResourceAsync(String resourceName); + + /** + * Unregister a resource with your subscription. + * + * @param resourceName Required. Name of the resource to unregister. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + OperationResponse unregisterResource(String resourceName) throws IOException, ServiceException; + + /** + * Unregister a resource with your subscription. + * + * @param resourceName Required. Name of the resource to unregister. + * @return A standard service response including an HTTP status code and + * request ID. + */ + Future unregisterResourceAsync(String resourceName); +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/SubscriptionOperationsImpl.java b/management/src/main/java/com/microsoft/windowsazure/management/SubscriptionOperationsImpl.java new file mode 100644 index 0000000000000..c75339a6461a6 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/SubscriptionOperationsImpl.java @@ -0,0 +1,766 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.core.ServiceOperations; +import com.microsoft.windowsazure.core.utils.BOMInputStream; +import com.microsoft.windowsazure.core.utils.XmlUtility; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.SubscriptionGetResponse; +import com.microsoft.windowsazure.management.models.SubscriptionListOperationsParameters; +import com.microsoft.windowsazure.management.models.SubscriptionListOperationsResponse; +import com.microsoft.windowsazure.management.models.SubscriptionStatus; +import com.microsoft.windowsazure.tracing.CloudTracing; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.TimeZone; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** +* Operations for listing subscription details. (see +* http://msdn.microsoft.com/en-us/library/windowsazure/gg715315.aspx for more +* information) +*/ +public class SubscriptionOperationsImpl implements ServiceOperations, SubscriptionOperations { + /** + * Initializes a new instance of the SubscriptionOperationsImpl class. + * + * @param client Reference to the service client. + */ + SubscriptionOperationsImpl(ManagementClientImpl client) { + this.client = client; + } + + private ManagementClientImpl client; + + /** + * Gets a reference to the + * microsoft.windowsazure.management.ManagementClientImpl. + * @return The Client value. + */ + public ManagementClientImpl getClient() { + return this.client; + } + + /** + * The Get Subscription operation returns account and resource allocation + * information for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx for + * more information) + * + * @return The Get Subscription operation response. + */ + @Override + public Future getAsync() { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public SubscriptionGetResponse call() throws Exception { + return get(); + } + }); + } + + /** + * The Get Subscription operation returns account and resource allocation + * information for the specified subscription. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx for + * more information) + * + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @throws URISyntaxException Thrown if there was an error parsing a URI in + * the response. + * @return The Get Subscription operation response. + */ + @Override + public SubscriptionGetResponse get() throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { + // Validate + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim(); + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + SubscriptionGetResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new SubscriptionGetResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element subscriptionElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Subscription"); + if (subscriptionElement != null) { + Element subscriptionIDElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionID"); + if (subscriptionIDElement != null) { + String subscriptionIDInstance; + subscriptionIDInstance = subscriptionIDElement.getTextContent(); + result.setSubscriptionID(subscriptionIDInstance); + } + + Element subscriptionNameElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionName"); + if (subscriptionNameElement != null) { + String subscriptionNameInstance; + subscriptionNameInstance = subscriptionNameElement.getTextContent(); + result.setSubscriptionName(subscriptionNameInstance); + } + + Element subscriptionStatusElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionStatus"); + if (subscriptionStatusElement != null) { + SubscriptionStatus subscriptionStatusInstance; + subscriptionStatusInstance = SubscriptionStatus.valueOf(subscriptionStatusElement.getTextContent()); + result.setSubscriptionStatus(subscriptionStatusInstance); + } + + Element accountAdminLiveEmailIdElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "AccountAdminLiveEmailId"); + if (accountAdminLiveEmailIdElement != null) { + String accountAdminLiveEmailIdInstance; + accountAdminLiveEmailIdInstance = accountAdminLiveEmailIdElement.getTextContent(); + result.setAccountAdminLiveEmailId(accountAdminLiveEmailIdInstance); + } + + Element serviceAdminLiveEmailIdElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "ServiceAdminLiveEmailId"); + if (serviceAdminLiveEmailIdElement != null) { + String serviceAdminLiveEmailIdInstance; + serviceAdminLiveEmailIdInstance = serviceAdminLiveEmailIdElement.getTextContent(); + result.setServiceAdminLiveEmailId(serviceAdminLiveEmailIdInstance); + } + + Element maxCoreCountElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "MaxCoreCount"); + if (maxCoreCountElement != null) { + int maxCoreCountInstance; + maxCoreCountInstance = DatatypeConverter.parseInt(maxCoreCountElement.getTextContent()); + result.setMaximumCoreCount(maxCoreCountInstance); + } + + Element maxStorageAccountsElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "MaxStorageAccounts"); + if (maxStorageAccountsElement != null) { + int maxStorageAccountsInstance; + maxStorageAccountsInstance = DatatypeConverter.parseInt(maxStorageAccountsElement.getTextContent()); + result.setMaximumStorageAccounts(maxStorageAccountsInstance); + } + + Element maxHostedServicesElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "MaxHostedServices"); + if (maxHostedServicesElement != null) { + int maxHostedServicesInstance; + maxHostedServicesInstance = DatatypeConverter.parseInt(maxHostedServicesElement.getTextContent()); + result.setMaximumHostedServices(maxHostedServicesInstance); + } + + Element currentCoreCountElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "CurrentCoreCount"); + if (currentCoreCountElement != null) { + int currentCoreCountInstance; + currentCoreCountInstance = DatatypeConverter.parseInt(currentCoreCountElement.getTextContent()); + result.setCurrentCoreCount(currentCoreCountInstance); + } + + Element currentStorageAccountsElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "CurrentStorageAccounts"); + if (currentStorageAccountsElement != null) { + int currentStorageAccountsInstance; + currentStorageAccountsInstance = DatatypeConverter.parseInt(currentStorageAccountsElement.getTextContent()); + result.setCurrentStorageAccounts(currentStorageAccountsInstance); + } + + Element currentHostedServicesElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "CurrentHostedServices"); + if (currentHostedServicesElement != null) { + int currentHostedServicesInstance; + currentHostedServicesInstance = DatatypeConverter.parseInt(currentHostedServicesElement.getTextContent()); + result.setCurrentHostedServices(currentHostedServicesInstance); + } + + Element maxVirtualNetworkSitesElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "MaxVirtualNetworkSites"); + if (maxVirtualNetworkSitesElement != null) { + int maxVirtualNetworkSitesInstance; + maxVirtualNetworkSitesInstance = DatatypeConverter.parseInt(maxVirtualNetworkSitesElement.getTextContent()); + result.setMaximumVirtualNetworkSites(maxVirtualNetworkSitesInstance); + } + + Element currentVirtualNetworkSitesElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "CurrentVirtualNetworkSites"); + if (currentVirtualNetworkSitesElement != null) { + int currentVirtualNetworkSitesInstance; + currentVirtualNetworkSitesInstance = DatatypeConverter.parseInt(currentVirtualNetworkSitesElement.getTextContent()); + result.setCurrentVirtualNetworkSites(currentVirtualNetworkSitesInstance); + } + + Element maxLocalNetworkSitesElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "MaxLocalNetworkSites"); + if (maxLocalNetworkSitesElement != null) { + int maxLocalNetworkSitesInstance; + maxLocalNetworkSitesInstance = DatatypeConverter.parseInt(maxLocalNetworkSitesElement.getTextContent()); + result.setMaximumLocalNetworkSites(maxLocalNetworkSitesInstance); + } + + Element maxDnsServersElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "MaxDnsServers"); + if (maxDnsServersElement != null) { + int maxDnsServersInstance; + maxDnsServersInstance = DatatypeConverter.parseInt(maxDnsServersElement.getTextContent()); + result.setMaximumDnsServers(maxDnsServersInstance); + } + + Element currentLocalNetworkSitesElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "CurrentLocalNetworkSites"); + if (currentLocalNetworkSitesElement != null) { + int currentLocalNetworkSitesInstance; + currentLocalNetworkSitesInstance = DatatypeConverter.parseInt(currentLocalNetworkSitesElement.getTextContent()); + result.setCurrentLocalNetworkSites(currentLocalNetworkSitesInstance); + } + + Element currentDnsServersElement = XmlUtility.getElementByTagNameNS(subscriptionElement, "http://schemas.microsoft.com/windowsazure", "CurrentDnsServers"); + if (currentDnsServersElement != null) { + int currentDnsServersInstance; + currentDnsServersInstance = DatatypeConverter.parseInt(currentDnsServersElement.getTextContent()); + result.setCurrentDnsServers(currentDnsServersInstance); + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * The List Subscription Operations operation returns a list of create, + * update, and delete operations that were performed on a subscription + * during the specified timeframe. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the List Subscription + * Operations operation. + * @return The List Subscription Operations operation response. + */ + @Override + public Future listOperationsAsync(final SubscriptionListOperationsParameters parameters) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public SubscriptionListOperationsResponse call() throws Exception { + return listOperations(parameters); + } + }); + } + + /** + * The List Subscription Operations operation returns a list of create, + * update, and delete operations that were performed on a subscription + * during the specified timeframe. (see + * http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx for + * more information) + * + * @param parameters Required. Parameters supplied to the List Subscription + * Operations operation. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @throws ParserConfigurationException Thrown if there was a serious + * configuration error with the document parser. + * @throws SAXException Thrown if there was an error parsing the XML + * response. + * @return The List Subscription Operations operation response. + */ + @Override + public SubscriptionListOperationsResponse listOperations(SubscriptionListOperationsParameters parameters) throws IOException, ServiceException, ParserConfigurationException, SAXException { + // Validate + if (parameters == null) { + throw new NullPointerException("parameters"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("parameters", parameters); + CloudTracing.enter(invocationId, this, "listOperationsAsync", tracingParameters); + } + + // Construct URL + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); + simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/operations" + "?"; + url = url + "&" + "StartTime=" + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"); + url = url + "&" + "EndTime=" + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"); + if (parameters.getObjectIdFilter() != null) { + url = url + "&" + "ObjectIdFilter=" + URLEncoder.encode(parameters.getObjectIdFilter().trim(), "UTF-8"); + } + if (parameters.getOperationStatus() != null) { + url = url + "&" + "OperationResultFilter=" + URLEncoder.encode(parameters.getOperationStatus().toString(), "UTF-8"); + } + if (parameters.getContinuationToken() != null) { + url = url + "&" + "ContinuationToken=" + URLEncoder.encode(parameters.getContinuationToken().trim(), "UTF-8"); + } + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpGet httpRequest = new HttpGet(url); + + // Set Headers + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + SubscriptionListOperationsResponse result = null; + // Deserialize Response + InputStream responseContent = httpResponse.getEntity().getContent(); + result = new SubscriptionListOperationsResponse(); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); + + Element subscriptionOperationCollectionElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "SubscriptionOperationCollection"); + if (subscriptionOperationCollectionElement != null) { + Element continuationTokenElement = XmlUtility.getElementByTagNameNS(subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure", "ContinuationToken"); + if (continuationTokenElement != null) { + String continuationTokenInstance; + continuationTokenInstance = continuationTokenElement.getTextContent(); + result.setContinuationToken(continuationTokenInstance); + } + + Element subscriptionOperationsSequenceElement = XmlUtility.getElementByTagNameNS(subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionOperations"); + if (subscriptionOperationsSequenceElement != null) { + for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subscriptionOperationsSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation").size(); i1 = i1 + 1) { + org.w3c.dom.Element subscriptionOperationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(subscriptionOperationsSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation").get(i1)); + SubscriptionListOperationsResponse.SubscriptionOperation subscriptionOperationInstance = new SubscriptionListOperationsResponse.SubscriptionOperation(); + result.getSubscriptionOperations().add(subscriptionOperationInstance); + + Element operationIdElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationId"); + if (operationIdElement != null) { + String operationIdInstance; + operationIdInstance = operationIdElement.getTextContent(); + subscriptionOperationInstance.setOperationId(operationIdInstance); + } + + Element operationObjectIdElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationObjectId"); + if (operationObjectIdElement != null) { + String operationObjectIdInstance; + operationObjectIdInstance = operationObjectIdElement.getTextContent(); + subscriptionOperationInstance.setOperationObjectId(operationObjectIdInstance); + } + + Element operationNameElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationName"); + if (operationNameElement != null) { + String operationNameInstance; + operationNameInstance = operationNameElement.getTextContent(); + subscriptionOperationInstance.setOperationName(operationNameInstance); + } + + Element operationParametersSequenceElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationParameters"); + if (operationParametersSequenceElement != null) { + for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operationParametersSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperationParameter").size(); i2 = i2 + 1) { + org.w3c.dom.Element operationParametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility.getElementsByTagNameNS(operationParametersSequenceElement, "http://schemas.microsoft.com/windowsazure", "OperationParameter").get(i2)); + String operationParametersKey = XmlUtility.getElementByTagNameNS(operationParametersElement, "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement", "Name").getTextContent(); + String operationParametersValue = XmlUtility.getElementByTagNameNS(operationParametersElement, "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement", "Value").getTextContent(); + subscriptionOperationInstance.getOperationParameters().put(operationParametersKey, operationParametersValue); + } + } + + Element operationCallerElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationCaller"); + if (operationCallerElement != null) { + SubscriptionListOperationsResponse.OperationCallerDetails operationCallerInstance = new SubscriptionListOperationsResponse.OperationCallerDetails(); + subscriptionOperationInstance.setOperationCaller(operationCallerInstance); + + Element usedServiceManagementApiElement = XmlUtility.getElementByTagNameNS(operationCallerElement, "http://schemas.microsoft.com/windowsazure", "UsedServiceManagementApi"); + if (usedServiceManagementApiElement != null) { + boolean usedServiceManagementApiInstance; + usedServiceManagementApiInstance = DatatypeConverter.parseBoolean(usedServiceManagementApiElement.getTextContent().toLowerCase()); + operationCallerInstance.setUsedServiceManagementApi(usedServiceManagementApiInstance); + } + + Element userEmailAddressElement = XmlUtility.getElementByTagNameNS(operationCallerElement, "http://schemas.microsoft.com/windowsazure", "UserEmailAddress"); + if (userEmailAddressElement != null) { + String userEmailAddressInstance; + userEmailAddressInstance = userEmailAddressElement.getTextContent(); + operationCallerInstance.setUserEmailAddress(userEmailAddressInstance); + } + + Element subscriptionCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(operationCallerElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint"); + if (subscriptionCertificateThumbprintElement != null) { + String subscriptionCertificateThumbprintInstance; + subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.getTextContent(); + operationCallerInstance.setSubscriptionCertificateThumbprint(subscriptionCertificateThumbprintInstance); + } + + Element clientIPElement = XmlUtility.getElementByTagNameNS(operationCallerElement, "http://schemas.microsoft.com/windowsazure", "ClientIP"); + if (clientIPElement != null) { + InetAddress clientIPInstance; + clientIPInstance = InetAddress.getByName(clientIPElement.getTextContent()); + operationCallerInstance.setClientIPAddress(clientIPInstance); + } + } + + Element operationStatusElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationStatus"); + if (operationStatusElement != null) { + String operationStatusInstance; + operationStatusInstance = operationStatusElement.getTextContent(); + subscriptionOperationInstance.setOperationStatus(operationStatusInstance); + } + + Element operationStartedTimeElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationStartedTime"); + if (operationStartedTimeElement != null) { + Calendar operationStartedTimeInstance; + operationStartedTimeInstance = DatatypeConverter.parseDateTime(operationStartedTimeElement.getTextContent()); + subscriptionOperationInstance.setOperationStartedTime(operationStartedTimeInstance); + } + + Element operationCompletedTimeElement = XmlUtility.getElementByTagNameNS(subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure", "OperationCompletedTime"); + if (operationCompletedTimeElement != null) { + Calendar operationCompletedTimeInstance; + operationCompletedTimeInstance = DatatypeConverter.parseDateTime(operationCompletedTimeElement.getTextContent()); + subscriptionOperationInstance.setOperationCompletedTime(operationCompletedTimeInstance); + } + } + } + } + + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Register a resource with your subscription. + * + * @param resourceName Required. Name of the resource to register. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future registerResourceAsync(final String resourceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return registerResource(resourceName); + } + }); + } + + /** + * Register a resource with your subscription. + * + * @param resourceName Required. Name of the resource to register. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse registerResource(String resourceName) throws IOException, ServiceException { + // Validate + if (resourceName == null) { + throw new NullPointerException("resourceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("resourceName", resourceName); + CloudTracing.enter(invocationId, this, "registerResourceAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services" + "?"; + url = url + "service=" + URLEncoder.encode(resourceName.trim(), "UTF-8"); + url = url + "&" + "action=register"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } + + /** + * Unregister a resource with your subscription. + * + * @param resourceName Required. Name of the resource to unregister. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public Future unregisterResourceAsync(final String resourceName) { + return this.getClient().getExecutorService().submit(new Callable() { + @Override + public OperationResponse call() throws Exception { + return unregisterResource(resourceName); + } + }); + } + + /** + * Unregister a resource with your subscription. + * + * @param resourceName Required. Name of the resource to unregister. + * @throws IOException Signals that an I/O exception of some sort has + * occurred. This class is the general class of exceptions produced by + * failed or interrupted I/O operations. + * @throws ServiceException Thrown if an unexpected response is found. + * @return A standard service response including an HTTP status code and + * request ID. + */ + @Override + public OperationResponse unregisterResource(String resourceName) throws IOException, ServiceException { + // Validate + if (resourceName == null) { + throw new NullPointerException("resourceName"); + } + + // Tracing + boolean shouldTrace = CloudTracing.getIsEnabled(); + String invocationId = null; + if (shouldTrace) { + invocationId = Long.toString(CloudTracing.getNextInvocationId()); + HashMap tracingParameters = new HashMap(); + tracingParameters.put("resourceName", resourceName); + CloudTracing.enter(invocationId, this, "unregisterResourceAsync", tracingParameters); + } + + // Construct URL + String baseUrl = this.getClient().getBaseUri().toString(); + String url = "/" + this.getClient().getCredentials().getSubscriptionId().trim() + "/services" + "?"; + url = url + "service=" + URLEncoder.encode(resourceName.trim(), "UTF-8"); + url = url + "&" + "action=unregister"; + // Trim '/' character from the end of baseUrl and beginning of url. + if (baseUrl.charAt(baseUrl.length() - 1) == '/') { + baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); + } + if (url.charAt(0) == '/') { + url = url.substring(1); + } + url = baseUrl + "/" + url; + + // Create HTTP transport objects + HttpPut httpRequest = new HttpPut(url); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2013-03-01"); + + // Send Request + HttpResponse httpResponse = null; + try { + if (shouldTrace) { + CloudTracing.sendRequest(invocationId, httpRequest); + } + httpResponse = this.getClient().getHttpClient().execute(httpRequest); + if (shouldTrace) { + CloudTracing.receiveResponse(invocationId, httpResponse); + } + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { + ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); + if (shouldTrace) { + CloudTracing.error(invocationId, ex); + } + throw ex; + } + + // Create Result + OperationResponse result = null; + result = new OperationResponse(); + result.setStatusCode(statusCode); + if (httpResponse.getHeaders("x-ms-request-id").length > 0) { + result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); + } + + if (shouldTrace) { + CloudTracing.exit(invocationId, result); + } + return result; + } finally { + if (httpResponse != null && httpResponse.getEntity() != null) { + httpResponse.getEntity().getContent().close(); + } + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupCapabilities.java b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupCapabilities.java new file mode 100644 index 0000000000000..b8d12acb70eae --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupCapabilities.java @@ -0,0 +1,36 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* Describes the capabilities associated with an affinity group. +*/ +public abstract class AffinityGroupCapabilities { + /** + * Indicates if the virtual machine-related operations can be performed in + * this affinity group. If so, the string PersistentVMRole will be returned + * by this element. Otherwise, this element will not be present. + */ + public static final String PERSISTENTVMROLE = "PersistentVMRole"; +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupCreateParameters.java b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupCreateParameters.java new file mode 100644 index 0000000000000..abff9c1a6901a --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupCreateParameters.java @@ -0,0 +1,115 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* Parameters supplied to the Create Affinity Group operation. +*/ +public class AffinityGroupCreateParameters { + private String description; + + /** + * Optional. A description for the affinity group. The description can be up + * to 1024 characters in length. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. A description for the affinity group. The description can be up + * to 1024 characters in length. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String label; + + /** + * Required. A base-64-encoded name for the affinity group. The name can be + * up to 100 characters in length. Its value defaults to the Name of the + * affinity group if not provided. + * @return The Label value. + */ + public String getLabel() { + if (this.label == null) { + return this.getName(); + } else { + return this.label; + } + } + + /** + * Required. A base-64-encoded name for the affinity group. The name can be + * up to 100 characters in length. Its value defaults to the Name of the + * affinity group if not provided. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Required. The data center location where the affinity group will be + * created. To list available locations, see the List Locations operation. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Required. The data center location where the affinity group will be + * created. To list available locations, see the List Locations operation. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private String name; + + /** + * Required. A name for the affinity group that is unique to the + * subscription. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Required. A name for the affinity group that is unique to the + * subscription. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupGetResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupGetResponse.java new file mode 100644 index 0000000000000..177ffe0a3cf2c --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupGetResponse.java @@ -0,0 +1,266 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.URI; +import java.util.ArrayList; + +/** +* The Get Affinity Group operation response. +*/ +public class AffinityGroupGetResponse extends OperationResponse { + private ArrayList capabilities; + + /** + * Optional. Indicates if the virtual machine-related operations can be + * performed in this affinity group. If so, the string PersistentVMRole + * will be returned by this element. Otherwise, this element will not be + * present. + * @return The Capabilities value. + */ + public ArrayList getCapabilities() { + return this.capabilities; + } + + /** + * Optional. Indicates if the virtual machine-related operations can be + * performed in this affinity group. If so, the string PersistentVMRole + * will be returned by this element. Otherwise, this element will not be + * present. + * @param capabilitiesValue The Capabilities value. + */ + public void setCapabilities(final ArrayList capabilitiesValue) { + this.capabilities = capabilitiesValue; + } + + private String description; + + /** + * Optional. The user-supplied description for this affinity group. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. The user-supplied description for this affinity group. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private ArrayList hostedServices; + + /** + * Optional. The hosted services associated with this affinity group. + * @return The HostedServices value. + */ + public ArrayList getHostedServices() { + return this.hostedServices; + } + + /** + * Optional. The hosted services associated with this affinity group. + * @param hostedServicesValue The HostedServices value. + */ + public void setHostedServices(final ArrayList hostedServicesValue) { + this.hostedServices = hostedServicesValue; + } + + private String label; + + /** + * Optional. The user-supplied label for the affinity group, returned as a + * base-64-encoded string. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The user-supplied label for the affinity group, returned as a + * base-64-encoded string. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The location of the data center that the affinity group is + * associated with. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The location of the data center that the affinity group is + * associated with. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private String name; + + /** + * Optional. The user-supplied name for the affinity group. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The user-supplied name for the affinity group. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private ArrayList storageServices; + + /** + * Optional. The storage services associated with this affinity group. + * @return The StorageServices value. + */ + public ArrayList getStorageServices() { + return this.storageServices; + } + + /** + * Optional. The storage services associated with this affinity group. + * @param storageServicesValue The StorageServices value. + */ + public void setStorageServices(final ArrayList storageServicesValue) { + this.storageServices = storageServicesValue; + } + + /** + * Initializes a new instance of the AffinityGroupGetResponse class. + * + */ + public AffinityGroupGetResponse() { + super(); + this.capabilities = new ArrayList(); + this.hostedServices = new ArrayList(); + this.storageServices = new ArrayList(); + } + + /** + * Reference to a hosted service associated with an affinity group. + */ + public static class HostedServiceReference { + private String serviceName; + + /** + * Optional. The name of the hosted service. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The name of the hosted service. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private URI uri; + + /** + * Optional. The Service Management API request URI used to perform Get + * Hosted Service Properties requests against the hosted service. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The Service Management API request URI used to perform Get + * Hosted Service Properties requests against the hosted service. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + } + + /** + * Reference to a storage service associated with an affinity group. + */ + public static class StorageServiceReference { + private String serviceName; + + /** + * Optional. The user supplied name of the storage account. + * @return The ServiceName value. + */ + public String getServiceName() { + return this.serviceName; + } + + /** + * Optional. The user supplied name of the storage account. + * @param serviceNameValue The ServiceName value. + */ + public void setServiceName(final String serviceNameValue) { + this.serviceName = serviceNameValue; + } + + private URI uri; + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @return The Uri value. + */ + public URI getUri() { + return this.uri; + } + + /** + * Optional. The Service Management API request URI used to perform Get + * Storage Account Properties requests against the storage account. + * @param uriValue The Uri value. + */ + public void setUri(final URI uriValue) { + this.uri = uriValue; + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupListResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupListResponse.java new file mode 100644 index 0000000000000..8d2b5568ccd7e --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupListResponse.java @@ -0,0 +1,181 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Affinity Groups operation response. +*/ +public class AffinityGroupListResponse extends OperationResponse implements Iterable { + private ArrayList affinityGroups; + + /** + * Optional. The affinity groups associated with the specified subscription. + * @return The AffinityGroups value. + */ + public ArrayList getAffinityGroups() { + return this.affinityGroups; + } + + /** + * Optional. The affinity groups associated with the specified subscription. + * @param affinityGroupsValue The AffinityGroups value. + */ + public void setAffinityGroups(final ArrayList affinityGroupsValue) { + this.affinityGroups = affinityGroupsValue; + } + + /** + * Initializes a new instance of the AffinityGroupListResponse class. + * + */ + public AffinityGroupListResponse() { + super(); + this.affinityGroups = new ArrayList(); + } + + /** + * Gets the sequence of AffinityGroups. + * + */ + public Iterator iterator() { + return this.getAffinityGroups().iterator(); + } + + /** + * An affinity group associated with the specified subscription. + */ + public static class AffinityGroup { + private ArrayList capabilities; + + /** + * Optional. Indicates if the affinity group is able to perform virtual + * machine-related operations. If so, the string PersistentVMRole will + * be returned by this element. Otherwise, this element will not be + * present. + * @return The Capabilities value. + */ + public ArrayList getCapabilities() { + return this.capabilities; + } + + /** + * Optional. Indicates if the affinity group is able to perform virtual + * machine-related operations. If so, the string PersistentVMRole will + * be returned by this element. Otherwise, this element will not be + * present. + * @param capabilitiesValue The Capabilities value. + */ + public void setCapabilities(final ArrayList capabilitiesValue) { + this.capabilities = capabilitiesValue; + } + + private String description; + + /** + * Optional. The user-supplied description for this affinity group. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. The user-supplied description for this affinity group. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String label; + + /** + * Optional. The user-supplied label for the affinity group, returned as + * a base-64-encoded string. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. The user-supplied label for the affinity group, returned as + * a base-64-encoded string. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private String location; + + /** + * Optional. The user-specified data center that this affinity groups is + * located in. + * @return The Location value. + */ + public String getLocation() { + return this.location; + } + + /** + * Optional. The user-specified data center that this affinity groups is + * located in. + * @param locationValue The Location value. + */ + public void setLocation(final String locationValue) { + this.location = locationValue; + } + + private String name; + + /** + * Optional. The user-supplied name for the affinity group. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The user-supplied name for the affinity group. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + /** + * Initializes a new instance of the AffinityGroup class. + * + */ + public AffinityGroup() { + this.capabilities = new ArrayList(); + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupUpdateParameters.java b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupUpdateParameters.java new file mode 100644 index 0000000000000..52a3044e83e76 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/AffinityGroupUpdateParameters.java @@ -0,0 +1,69 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* Parameters supplied to the Update Affinity Group operation. +*/ +public class AffinityGroupUpdateParameters { + private String description; + + /** + * Optional. A description for the affinity group. The description can be up + * to 1024 characters in length. + * @return The Description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Optional. A description for the affinity group. The description can be up + * to 1024 characters in length. + * @param descriptionValue The Description value. + */ + public void setDescription(final String descriptionValue) { + this.description = descriptionValue; + } + + private String label; + + /** + * Required. A name for the affinity specified as a base-64-encoded string. + * The label can be up to 100 characters in length. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Required. A name for the affinity specified as a base-64-encoded string. + * The label can be up to 100 characters in length. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/LocationAvailableServiceNames.java b/management/src/main/java/com/microsoft/windowsazure/management/models/LocationAvailableServiceNames.java new file mode 100644 index 0000000000000..daf59874b44e8 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/LocationAvailableServiceNames.java @@ -0,0 +1,37 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* Indicates the services available at a location. +*/ +public abstract class LocationAvailableServiceNames { + public static final String COMPUTE = "Compute"; + + public static final String STORAGE = "Storage"; + + public static final String PERSISTENTVMROLE = "PersistentVMRole"; + + public static final String HIGHMEMORY = "HighMemory"; +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/LocationNames.java b/management/src/main/java/com/microsoft/windowsazure/management/models/LocationNames.java new file mode 100644 index 0000000000000..985384c714ef3 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/LocationNames.java @@ -0,0 +1,46 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* Known location names for Azure. You can obtain a complete list of the latest +* locations available to your subscription from the List Locations Operation. +*/ +public abstract class LocationNames { + public static final String WESTEUROPE = "West Europe"; + + public static final String SOUTHEASTASIA = "Southeast Asia"; + + public static final String EASTASIA = "East Asia"; + + public static final String NORTHCENTRALUS = "North Central US"; + + public static final String NORTHEUROPE = "North Europe"; + + public static final String SOUTHCENTRALUS = "South Central US"; + + public static final String WESTUS = "West US"; + + public static final String EASTUS = "East US"; +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/LocationsListResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/LocationsListResponse.java new file mode 100644 index 0000000000000..741560a521569 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/LocationsListResponse.java @@ -0,0 +1,137 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Locations operation response. +*/ +public class LocationsListResponse extends OperationResponse implements Iterable { + private ArrayList locations; + + /** + * Optional. The data center locations that are valid for your subscription. + * @return The Locations value. + */ + public ArrayList getLocations() { + return this.locations; + } + + /** + * Optional. The data center locations that are valid for your subscription. + * @param locationsValue The Locations value. + */ + public void setLocations(final ArrayList locationsValue) { + this.locations = locationsValue; + } + + /** + * Initializes a new instance of the LocationsListResponse class. + * + */ + public LocationsListResponse() { + super(); + this.locations = new ArrayList(); + } + + /** + * Gets the sequence of Locations. + * + */ + public Iterator iterator() { + return this.getLocations().iterator(); + } + + /** + * A data center location that is valid for your subscription. + */ + public static class Location { + private ArrayList availableServices; + + /** + * Optional. Indicates the services available at a location. + * @return The AvailableServices value. + */ + public ArrayList getAvailableServices() { + return this.availableServices; + } + + /** + * Optional. Indicates the services available at a location. + * @param availableServicesValue The AvailableServices value. + */ + public void setAvailableServices(final ArrayList availableServicesValue) { + this.availableServices = availableServicesValue; + } + + private String displayName; + + /** + * Optional. The localized name of data center location. + * @return The DisplayName value. + */ + public String getDisplayName() { + return this.displayName; + } + + /** + * Optional. The localized name of data center location. + * @param displayNameValue The DisplayName value. + */ + public void setDisplayName(final String displayNameValue) { + this.displayName = displayNameValue; + } + + private String name; + + /** + * Optional. The name of a data center location that is valid for your + * subscription. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of a data center location that is valid for your + * subscription. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + /** + * Initializes a new instance of the Location class. + * + */ + public Location() { + this.availableServices = new ArrayList(); + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateCreateParameters.java b/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateCreateParameters.java new file mode 100644 index 0000000000000..3acd0844e8008 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateCreateParameters.java @@ -0,0 +1,87 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* Parameters supplied to the Create Management Certificate operation. +*/ +public class ManagementCertificateCreateParameters { + private byte[] data; + + /** + * Optional. The certificate's raw data in base-64-encoded cer format. + * @return The Data value. + */ + public byte[] getData() { + return this.data; + } + + /** + * Optional. The certificate's raw data in base-64-encoded cer format. + * @param dataValue The Data value. + */ + public void setData(final byte[] dataValue) { + this.data = dataValue; + } + + private byte[] publicKey; + + /** + * Optional. A base-64-representation of the management certificate public + * key. + * @return The PublicKey value. + */ + public byte[] getPublicKey() { + return this.publicKey; + } + + /** + * Optional. A base-64-representation of the management certificate public + * key. + * @param publicKeyValue The PublicKey value. + */ + public void setPublicKey(final byte[] publicKeyValue) { + this.publicKey = publicKeyValue; + } + + private String thumbprint; + + /** + * Optional. The thumbprint that uniquely identifies the management + * certificate. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. The thumbprint that uniquely identifies the management + * certificate. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateGetResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateGetResponse.java new file mode 100644 index 0000000000000..13c807daea976 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateGetResponse.java @@ -0,0 +1,112 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.Calendar; + +/** +* The Get Management Certificate operation response. +*/ +public class ManagementCertificateGetResponse extends OperationResponse { + private Calendar created; + + /** + * Optional. The time that the management certificate was created, in UTC. + * @return The Created value. + */ + public Calendar getCreated() { + return this.created; + } + + /** + * Optional. The time that the management certificate was created, in UTC. + * @param createdValue The Created value. + */ + public void setCreated(final Calendar createdValue) { + this.created = createdValue; + } + + private byte[] data; + + /** + * Optional. A base-64 representation of the raw data contained in the + * management certificate, in cer format. + * @return The Data value. + */ + public byte[] getData() { + return this.data; + } + + /** + * Optional. A base-64 representation of the raw data contained in the + * management certificate, in cer format. + * @param dataValue The Data value. + */ + public void setData(final byte[] dataValue) { + this.data = dataValue; + } + + private byte[] publicKey; + + /** + * Optional. A base-64 representation of the management certificate public + * key. + * @return The PublicKey value. + */ + public byte[] getPublicKey() { + return this.publicKey; + } + + /** + * Optional. A base-64 representation of the management certificate public + * key. + * @param publicKeyValue The PublicKey value. + */ + public void setPublicKey(final byte[] publicKeyValue) { + this.publicKey = publicKeyValue; + } + + private String thumbprint; + + /** + * Optional. The thumbprint that uniquely identifies the management + * certificate. This thumbprint is the same value as the one specified by + * the request URI. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. The thumbprint that uniquely identifies the management + * certificate. This thumbprint is the same value as the one specified by + * the request URI. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateListResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateListResponse.java new file mode 100644 index 0000000000000..e50d357d2794c --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/ManagementCertificateListResponse.java @@ -0,0 +1,156 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; + +/** +* The List Management Certificates operation response. +*/ +public class ManagementCertificateListResponse extends OperationResponse implements Iterable { + private ArrayList subscriptionCertificates; + + /** + * Optional. The management certificates that are valid for your + * subscription. + * @return The SubscriptionCertificates value. + */ + public ArrayList getSubscriptionCertificates() { + return this.subscriptionCertificates; + } + + /** + * Optional. The management certificates that are valid for your + * subscription. + * @param subscriptionCertificatesValue The SubscriptionCertificates value. + */ + public void setSubscriptionCertificates(final ArrayList subscriptionCertificatesValue) { + this.subscriptionCertificates = subscriptionCertificatesValue; + } + + /** + * Initializes a new instance of the ManagementCertificateListResponse class. + * + */ + public ManagementCertificateListResponse() { + super(); + this.subscriptionCertificates = new ArrayList(); + } + + /** + * Gets the sequence of SubscriptionCertificates. + * + */ + public Iterator iterator() { + return this.getSubscriptionCertificates().iterator(); + } + + /** + * A management certificate that is valid for your subscription. + */ + public static class SubscriptionCertificate { + private Calendar created; + + /** + * Optional. The time that the management certificate was created, in + * UTC. + * @return The Created value. + */ + public Calendar getCreated() { + return this.created; + } + + /** + * Optional. The time that the management certificate was created, in + * UTC. + * @param createdValue The Created value. + */ + public void setCreated(final Calendar createdValue) { + this.created = createdValue; + } + + private byte[] data; + + /** + * Optional. A base-64 representation of the data contained in the + * management certificate, in cer format. + * @return The Data value. + */ + public byte[] getData() { + return this.data; + } + + /** + * Optional. A base-64 representation of the data contained in the + * management certificate, in cer format. + * @param dataValue The Data value. + */ + public void setData(final byte[] dataValue) { + this.data = dataValue; + } + + private byte[] publicKey; + + /** + * Optional. A base-64 representation of the management certificate + * public key. + * @return The PublicKey value. + */ + public byte[] getPublicKey() { + return this.publicKey; + } + + /** + * Optional. A base-64 representation of the management certificate + * public key. + * @param publicKeyValue The PublicKey value. + */ + public void setPublicKey(final byte[] publicKeyValue) { + this.publicKey = publicKeyValue; + } + + private String thumbprint; + + /** + * Optional. The X509 certificate thumbprint property of the management + * certificate. This thumbprint uniquely identifies the certificate. + * @return The Thumbprint value. + */ + public String getThumbprint() { + return this.thumbprint; + } + + /** + * Optional. The X509 certificate thumbprint property of the management + * certificate. This thumbprint uniquely identifies the certificate. + * @param thumbprintValue The Thumbprint value. + */ + public void setThumbprint(final String thumbprintValue) { + this.thumbprint = thumbprintValue; + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/RoleSizeListResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/RoleSizeListResponse.java new file mode 100644 index 0000000000000..06a7c4317958d --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/RoleSizeListResponse.java @@ -0,0 +1,185 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.util.ArrayList; +import java.util.Iterator; + +/** +* The List Role Sizes operation response. +*/ +public class RoleSizeListResponse extends OperationResponse implements Iterable { + private ArrayList roleSizes; + + /** + * Optional. The role sizes that are valid for your subscription. + * @return The RoleSizes value. + */ + public ArrayList getRoleSizes() { + return this.roleSizes; + } + + /** + * Optional. The role sizes that are valid for your subscription. + * @param roleSizesValue The RoleSizes value. + */ + public void setRoleSizes(final ArrayList roleSizesValue) { + this.roleSizes = roleSizesValue; + } + + /** + * Initializes a new instance of the RoleSizeListResponse class. + * + */ + public RoleSizeListResponse() { + super(); + this.roleSizes = new ArrayList(); + } + + /** + * Gets the sequence of RoleSizes. + * + */ + public Iterator iterator() { + return this.getRoleSizes().iterator(); + } + + /** + * A role size that is valid for your subscription. + */ + public static class RoleSize { + private int cores; + + /** + * Optional. Number of cores available for the role size. + * @return The Cores value. + */ + public int getCores() { + return this.cores; + } + + /** + * Optional. Number of cores available for the role size. + * @param coresValue The Cores value. + */ + public void setCores(final int coresValue) { + this.cores = coresValue; + } + + private String label; + + /** + * Optional. Localized label of the role size. + * @return The Label value. + */ + public String getLabel() { + return this.label; + } + + /** + * Optional. Localized label of the role size. + * @param labelValue The Label value. + */ + public void setLabel(final String labelValue) { + this.label = labelValue; + } + + private int memoryInMb; + + /** + * Optional. Memory available for the role size. + * @return The MemoryInMb value. + */ + public int getMemoryInMb() { + return this.memoryInMb; + } + + /** + * Optional. Memory available for the role size. + * @param memoryInMbValue The MemoryInMb value. + */ + public void setMemoryInMb(final int memoryInMbValue) { + this.memoryInMb = memoryInMbValue; + } + + private String name; + + /** + * Optional. The name of a role size that is valid for your subscription. + * @return The Name value. + */ + public String getName() { + return this.name; + } + + /** + * Optional. The name of a role size that is valid for your subscription. + * @param nameValue The Name value. + */ + public void setName(final String nameValue) { + this.name = nameValue; + } + + private boolean supportedByVirtualMachines; + + /** + * Optional. Indicating if the role size is supported by VMs. + * @return The SupportedByVirtualMachines value. + */ + public boolean isSupportedByVirtualMachines() { + return this.supportedByVirtualMachines; + } + + /** + * Optional. Indicating if the role size is supported by VMs. + * @param supportedByVirtualMachinesValue The SupportedByVirtualMachines + * value. + */ + public void setSupportedByVirtualMachines(final boolean supportedByVirtualMachinesValue) { + this.supportedByVirtualMachines = supportedByVirtualMachinesValue; + } + + private boolean supportedByWebWorkerRoles; + + /** + * Optional. Indicating if the role size is supported by web/worker + * roles. + * @return The SupportedByWebWorkerRoles value. + */ + public boolean isSupportedByWebWorkerRoles() { + return this.supportedByWebWorkerRoles; + } + + /** + * Optional. Indicating if the role size is supported by web/worker + * roles. + * @param supportedByWebWorkerRolesValue The SupportedByWebWorkerRoles + * value. + */ + public void setSupportedByWebWorkerRoles(final boolean supportedByWebWorkerRolesValue) { + this.supportedByWebWorkerRoles = supportedByWebWorkerRolesValue; + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionGetResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionGetResponse.java new file mode 100644 index 0000000000000..a153ca0900de5 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionGetResponse.java @@ -0,0 +1,355 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; + +/** +* The Get Subscription operation response. +*/ +public class SubscriptionGetResponse extends OperationResponse { + private String accountAdminLiveEmailId; + + /** + * Optional. The live ID of the account administrator. + * @return The AccountAdminLiveEmailId value. + */ + public String getAccountAdminLiveEmailId() { + return this.accountAdminLiveEmailId; + } + + /** + * Optional. The live ID of the account administrator. + * @param accountAdminLiveEmailIdValue The AccountAdminLiveEmailId value. + */ + public void setAccountAdminLiveEmailId(final String accountAdminLiveEmailIdValue) { + this.accountAdminLiveEmailId = accountAdminLiveEmailIdValue; + } + + private int currentCoreCount; + + /** + * Optional. The number of currently allocated cores. + * @return The CurrentCoreCount value. + */ + public int getCurrentCoreCount() { + return this.currentCoreCount; + } + + /** + * Optional. The number of currently allocated cores. + * @param currentCoreCountValue The CurrentCoreCount value. + */ + public void setCurrentCoreCount(final int currentCoreCountValue) { + this.currentCoreCount = currentCoreCountValue; + } + + private int currentDnsServers; + + /** + * Optional. The current number of DNS servers allocated on this + * subscription. + * @return The CurrentDnsServers value. + */ + public int getCurrentDnsServers() { + return this.currentDnsServers; + } + + /** + * Optional. The current number of DNS servers allocated on this + * subscription. + * @param currentDnsServersValue The CurrentDnsServers value. + */ + public void setCurrentDnsServers(final int currentDnsServersValue) { + this.currentDnsServers = currentDnsServersValue; + } + + private int currentHostedServices; + + /** + * Optional. The number of currently allocated cloud services. + * @return The CurrentHostedServices value. + */ + public int getCurrentHostedServices() { + return this.currentHostedServices; + } + + /** + * Optional. The number of currently allocated cloud services. + * @param currentHostedServicesValue The CurrentHostedServices value. + */ + public void setCurrentHostedServices(final int currentHostedServicesValue) { + this.currentHostedServices = currentHostedServicesValue; + } + + private int currentLocalNetworkSites; + + /** + * Optional. The current number of local virtual network sites that are + * allocated on this subscription. + * @return The CurrentLocalNetworkSites value. + */ + public int getCurrentLocalNetworkSites() { + return this.currentLocalNetworkSites; + } + + /** + * Optional. The current number of local virtual network sites that are + * allocated on this subscription. + * @param currentLocalNetworkSitesValue The CurrentLocalNetworkSites value. + */ + public void setCurrentLocalNetworkSites(final int currentLocalNetworkSitesValue) { + this.currentLocalNetworkSites = currentLocalNetworkSitesValue; + } + + private int currentStorageAccounts; + + /** + * Optional. The number of currently allocated storage accounts. + * @return The CurrentStorageAccounts value. + */ + public int getCurrentStorageAccounts() { + return this.currentStorageAccounts; + } + + /** + * Optional. The number of currently allocated storage accounts. + * @param currentStorageAccountsValue The CurrentStorageAccounts value. + */ + public void setCurrentStorageAccounts(final int currentStorageAccountsValue) { + this.currentStorageAccounts = currentStorageAccountsValue; + } + + private int currentVirtualNetworkSites; + + /** + * Optional. The number of currently allocated virtual network sites. + * @return The CurrentVirtualNetworkSites value. + */ + public int getCurrentVirtualNetworkSites() { + return this.currentVirtualNetworkSites; + } + + /** + * Optional. The number of currently allocated virtual network sites. + * @param currentVirtualNetworkSitesValue The CurrentVirtualNetworkSites + * value. + */ + public void setCurrentVirtualNetworkSites(final int currentVirtualNetworkSitesValue) { + this.currentVirtualNetworkSites = currentVirtualNetworkSitesValue; + } + + private int maximumCoreCount; + + /** + * Optional. The maximum number of cores that can be allocated on this + * subscription. + * @return The MaximumCoreCount value. + */ + public int getMaximumCoreCount() { + return this.maximumCoreCount; + } + + /** + * Optional. The maximum number of cores that can be allocated on this + * subscription. + * @param maximumCoreCountValue The MaximumCoreCount value. + */ + public void setMaximumCoreCount(final int maximumCoreCountValue) { + this.maximumCoreCount = maximumCoreCountValue; + } + + private int maximumDnsServers; + + /** + * Optional. The maximum number of DNS servers that can be allocated on this + * subscription. + * @return The MaximumDnsServers value. + */ + public int getMaximumDnsServers() { + return this.maximumDnsServers; + } + + /** + * Optional. The maximum number of DNS servers that can be allocated on this + * subscription. + * @param maximumDnsServersValue The MaximumDnsServers value. + */ + public void setMaximumDnsServers(final int maximumDnsServersValue) { + this.maximumDnsServers = maximumDnsServersValue; + } + + private int maximumHostedServices; + + /** + * Optional. The maximum number of cloud services that can be allocated on + * this subscription. + * @return The MaximumHostedServices value. + */ + public int getMaximumHostedServices() { + return this.maximumHostedServices; + } + + /** + * Optional. The maximum number of cloud services that can be allocated on + * this subscription. + * @param maximumHostedServicesValue The MaximumHostedServices value. + */ + public void setMaximumHostedServices(final int maximumHostedServicesValue) { + this.maximumHostedServices = maximumHostedServicesValue; + } + + private int maximumLocalNetworkSites; + + /** + * Optional. The maximum number of local virtual network sites that can be + * allocated on this subscription. + * @return The MaximumLocalNetworkSites value. + */ + public int getMaximumLocalNetworkSites() { + return this.maximumLocalNetworkSites; + } + + /** + * Optional. The maximum number of local virtual network sites that can be + * allocated on this subscription. + * @param maximumLocalNetworkSitesValue The MaximumLocalNetworkSites value. + */ + public void setMaximumLocalNetworkSites(final int maximumLocalNetworkSitesValue) { + this.maximumLocalNetworkSites = maximumLocalNetworkSitesValue; + } + + private int maximumStorageAccounts; + + /** + * Optional. The maximum number of storage accounts that can be allocated on + * this subscription. + * @return The MaximumStorageAccounts value. + */ + public int getMaximumStorageAccounts() { + return this.maximumStorageAccounts; + } + + /** + * Optional. The maximum number of storage accounts that can be allocated on + * this subscription. + * @param maximumStorageAccountsValue The MaximumStorageAccounts value. + */ + public void setMaximumStorageAccounts(final int maximumStorageAccountsValue) { + this.maximumStorageAccounts = maximumStorageAccountsValue; + } + + private int maximumVirtualNetworkSites; + + /** + * Optional. The maximum number of virtual network sites that can be + * allocated on this subscription. + * @return The MaximumVirtualNetworkSites value. + */ + public int getMaximumVirtualNetworkSites() { + return this.maximumVirtualNetworkSites; + } + + /** + * Optional. The maximum number of virtual network sites that can be + * allocated on this subscription. + * @param maximumVirtualNetworkSitesValue The MaximumVirtualNetworkSites + * value. + */ + public void setMaximumVirtualNetworkSites(final int maximumVirtualNetworkSitesValue) { + this.maximumVirtualNetworkSites = maximumVirtualNetworkSitesValue; + } + + private String serviceAdminLiveEmailId; + + /** + * Optional. The live ID of the subscription administrator. + * @return The ServiceAdminLiveEmailId value. + */ + public String getServiceAdminLiveEmailId() { + return this.serviceAdminLiveEmailId; + } + + /** + * Optional. The live ID of the subscription administrator. + * @param serviceAdminLiveEmailIdValue The ServiceAdminLiveEmailId value. + */ + public void setServiceAdminLiveEmailId(final String serviceAdminLiveEmailIdValue) { + this.serviceAdminLiveEmailId = serviceAdminLiveEmailIdValue; + } + + private String subscriptionID; + + /** + * Optional. The subscription ID that the operation was called on. + * @return The SubscriptionID value. + */ + public String getSubscriptionID() { + return this.subscriptionID; + } + + /** + * Optional. The subscription ID that the operation was called on. + * @param subscriptionIDValue The SubscriptionID value. + */ + public void setSubscriptionID(final String subscriptionIDValue) { + this.subscriptionID = subscriptionIDValue; + } + + private String subscriptionName; + + /** + * Optional. The user-supplied name for the subscription. + * @return The SubscriptionName value. + */ + public String getSubscriptionName() { + return this.subscriptionName; + } + + /** + * Optional. The user-supplied name for the subscription. + * @param subscriptionNameValue The SubscriptionName value. + */ + public void setSubscriptionName(final String subscriptionNameValue) { + this.subscriptionName = subscriptionNameValue; + } + + private SubscriptionStatus subscriptionStatus; + + /** + * Optional. The subscription status. + * @return The SubscriptionStatus value. + */ + public SubscriptionStatus getSubscriptionStatus() { + return this.subscriptionStatus; + } + + /** + * Optional. The subscription status. + * @param subscriptionStatusValue The SubscriptionStatus value. + */ + public void setSubscriptionStatus(final SubscriptionStatus subscriptionStatusValue) { + this.subscriptionStatus = subscriptionStatusValue; + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionListOperationsParameters.java b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionListOperationsParameters.java new file mode 100644 index 0000000000000..5dba85386a319 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionListOperationsParameters.java @@ -0,0 +1,158 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationStatus; +import java.util.Calendar; + +/** +* Parameters supplied to the List Subscription Operations operation. +*/ +public class SubscriptionListOperationsParameters { + private String continuationToken; + + /** + * Optional. When there are too many operations to list, such as when the + * requested timeframe is very large, the response includes an incomplete + * list and a token that can be used to return the rest of the list. + * Subsequent requests must include this parameter to continue listing + * operations from where the last response left off. If no token is + * specified, a filter is not applied and the response will begin at the + * specified StartTime. + * @return The ContinuationToken value. + */ + public String getContinuationToken() { + return this.continuationToken; + } + + /** + * Optional. When there are too many operations to list, such as when the + * requested timeframe is very large, the response includes an incomplete + * list and a token that can be used to return the rest of the list. + * Subsequent requests must include this parameter to continue listing + * operations from where the last response left off. If no token is + * specified, a filter is not applied and the response will begin at the + * specified StartTime. + * @param continuationTokenValue The ContinuationToken value. + */ + public void setContinuationToken(final String continuationTokenValue) { + this.continuationToken = continuationTokenValue; + } + + private Calendar endTime; + + /** + * Required. The end of the timeframe to begin listing subscription + * operations in UTC format. This parameter and the StartTime parameter + * indicate the timeframe to retrieve subscription operations. + * @return The EndTime value. + */ + public Calendar getEndTime() { + return this.endTime; + } + + /** + * Required. The end of the timeframe to begin listing subscription + * operations in UTC format. This parameter and the StartTime parameter + * indicate the timeframe to retrieve subscription operations. + * @param endTimeValue The EndTime value. + */ + public void setEndTime(final Calendar endTimeValue) { + this.endTime = endTimeValue; + } + + private String objectIdFilter; + + /** + * Optional. Returns subscription operations only for the specified object + * type and object ID. This parameter must be set equal to the URL value + * for performing an HTTP GET on the object. If no object is specified, a + * filter is not applied. + * @return The ObjectIdFilter value. + */ + public String getObjectIdFilter() { + return this.objectIdFilter; + } + + /** + * Optional. Returns subscription operations only for the specified object + * type and object ID. This parameter must be set equal to the URL value + * for performing an HTTP GET on the object. If no object is specified, a + * filter is not applied. + * @param objectIdFilterValue The ObjectIdFilter value. + */ + public void setObjectIdFilter(final String objectIdFilterValue) { + this.objectIdFilter = objectIdFilterValue; + } + + private OperationStatus operationStatus; + + /** + * Optional. Returns subscription operations only for the specified result + * status, either Succeeded, Failed, or InProgress. This filter can be + * combined with the ObjectIdFilter to select subscription operations for + * an object with a specific result status. If no result status is + * specified, a filter is not applied. + * @return The OperationStatus value. + */ + public OperationStatus getOperationStatus() { + return this.operationStatus; + } + + /** + * Optional. Returns subscription operations only for the specified result + * status, either Succeeded, Failed, or InProgress. This filter can be + * combined with the ObjectIdFilter to select subscription operations for + * an object with a specific result status. If no result status is + * specified, a filter is not applied. + * @param operationStatusValue The OperationStatus value. + */ + public void setOperationStatus(final OperationStatus operationStatusValue) { + this.operationStatus = operationStatusValue; + } + + private Calendar startTime; + + /** + * Required. The start of the timeframe to begin listing subscription + * operations in UTC format. This parameter and the EndTime parameter + * indicate the timeframe to retrieve subscription operations. This + * parameter cannot indicate a start date of more than 90 days in the past. + * @return The StartTime value. + */ + public Calendar getStartTime() { + return this.startTime; + } + + /** + * Required. The start of the timeframe to begin listing subscription + * operations in UTC format. This parameter and the EndTime parameter + * indicate the timeframe to retrieve subscription operations. This + * parameter cannot indicate a start date of more than 90 days in the past. + * @param startTimeValue The StartTime value. + */ + public void setStartTime(final Calendar startTimeValue) { + this.startTime = startTimeValue; + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionListOperationsResponse.java b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionListOperationsResponse.java new file mode 100644 index 0000000000000..4eab06b928f78 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionListOperationsResponse.java @@ -0,0 +1,358 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +import com.microsoft.windowsazure.core.OperationResponse; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; + +/** +* The List Subscription Operations operation response. +*/ +public class SubscriptionListOperationsResponse extends OperationResponse { + private String continuationToken; + + /** + * Optional. The string that can be used to return the rest of the list. + * Subsequent requests must include this parameter to continue listing + * operations from where the last response left off. This element exists + * only if the complete list of subscription operations was not returned. + * @return The ContinuationToken value. + */ + public String getContinuationToken() { + return this.continuationToken; + } + + /** + * Optional. The string that can be used to return the rest of the list. + * Subsequent requests must include this parameter to continue listing + * operations from where the last response left off. This element exists + * only if the complete list of subscription operations was not returned. + * @param continuationTokenValue The ContinuationToken value. + */ + public void setContinuationToken(final String continuationTokenValue) { + this.continuationToken = continuationTokenValue; + } + + private ArrayList subscriptionOperations; + + /** + * Optional. The list of operations that have been performed on the + * subscription during the specified timeframe. + * @return The SubscriptionOperations value. + */ + public ArrayList getSubscriptionOperations() { + return this.subscriptionOperations; + } + + /** + * Optional. The list of operations that have been performed on the + * subscription during the specified timeframe. + * @param subscriptionOperationsValue The SubscriptionOperations value. + */ + public void setSubscriptionOperations(final ArrayList subscriptionOperationsValue) { + this.subscriptionOperations = subscriptionOperationsValue; + } + + /** + * Initializes a new instance of the SubscriptionListOperationsResponse + * class. + * + */ + public SubscriptionListOperationsResponse() { + super(); + this.subscriptionOperations = new ArrayList(); + } + + /** + * A collection of attributes that identify the source of the operation. + */ + public static class OperationCallerDetails { + private InetAddress clientIPAddress; + + /** + * Optional. The IP address of the client computer that initiated the + * operation. This element is returned only if UsedServiceManagementApi + * is true. + * @return The ClientIPAddress value. + */ + public InetAddress getClientIPAddress() { + return this.clientIPAddress; + } + + /** + * Optional. The IP address of the client computer that initiated the + * operation. This element is returned only if UsedServiceManagementApi + * is true. + * @param clientIPAddressValue The ClientIPAddress value. + */ + public void setClientIPAddress(final InetAddress clientIPAddressValue) { + this.clientIPAddress = clientIPAddressValue; + } + + private String subscriptionCertificateThumbprint; + + /** + * Optional. The thumbprint of the subscription certificate used to + * initiate the operation. + * @return The SubscriptionCertificateThumbprint value. + */ + public String getSubscriptionCertificateThumbprint() { + return this.subscriptionCertificateThumbprint; + } + + /** + * Optional. The thumbprint of the subscription certificate used to + * initiate the operation. + * @param subscriptionCertificateThumbprintValue The + * SubscriptionCertificateThumbprint value. + */ + public void setSubscriptionCertificateThumbprint(final String subscriptionCertificateThumbprintValue) { + this.subscriptionCertificateThumbprint = subscriptionCertificateThumbprintValue; + } + + private boolean usedServiceManagementApi; + + /** + * Optional. Indicates whether the operation was initiated by using the + * Service Management API. This will be false if it was initiated by + * another source, such as the Management Portal. + * @return The UsedServiceManagementApi value. + */ + public boolean isUsedServiceManagementApi() { + return this.usedServiceManagementApi; + } + + /** + * Optional. Indicates whether the operation was initiated by using the + * Service Management API. This will be false if it was initiated by + * another source, such as the Management Portal. + * @param usedServiceManagementApiValue The UsedServiceManagementApi + * value. + */ + public void setUsedServiceManagementApi(final boolean usedServiceManagementApiValue) { + this.usedServiceManagementApi = usedServiceManagementApiValue; + } + + private String userEmailAddress; + + /** + * Optional. The email associated with the Windows Live ID of the user + * who initiated the operation from the Management Portal. This element + * is returned only if UsedServiceManagementApi is false. + * @return The UserEmailAddress value. + */ + public String getUserEmailAddress() { + return this.userEmailAddress; + } + + /** + * Optional. The email associated with the Windows Live ID of the user + * who initiated the operation from the Management Portal. This element + * is returned only if UsedServiceManagementApi is false. + * @param userEmailAddressValue The UserEmailAddress value. + */ + public void setUserEmailAddress(final String userEmailAddressValue) { + this.userEmailAddress = userEmailAddressValue; + } + } + + /** + * An operation that has been performed on the subscription during the + * specified timeframe. + */ + public static class SubscriptionOperation { + private SubscriptionListOperationsResponse.OperationCallerDetails operationCaller; + + /** + * Optional. A collection of attributes that identify the source of the + * operation. + * @return The OperationCaller value. + */ + public SubscriptionListOperationsResponse.OperationCallerDetails getOperationCaller() { + return this.operationCaller; + } + + /** + * Optional. A collection of attributes that identify the source of the + * operation. + * @param operationCallerValue The OperationCaller value. + */ + public void setOperationCaller(final SubscriptionListOperationsResponse.OperationCallerDetails operationCallerValue) { + this.operationCaller = operationCallerValue; + } + + private Calendar operationCompletedTime; + + /** + * Optional. The time that the operation finished executing. + * @return The OperationCompletedTime value. + */ + public Calendar getOperationCompletedTime() { + return this.operationCompletedTime; + } + + /** + * Optional. The time that the operation finished executing. + * @param operationCompletedTimeValue The OperationCompletedTime value. + */ + public void setOperationCompletedTime(final Calendar operationCompletedTimeValue) { + this.operationCompletedTime = operationCompletedTimeValue; + } + + private String operationId; + + /** + * Optional. The globally unique identifier (GUID) of the operation. + * @return The OperationId value. + */ + public String getOperationId() { + return this.operationId; + } + + /** + * Optional. The globally unique identifier (GUID) of the operation. + * @param operationIdValue The OperationId value. + */ + public void setOperationId(final String operationIdValue) { + this.operationId = operationIdValue; + } + + private String operationName; + + /** + * Optional. The name of the performed operation. + * @return The OperationName value. + */ + public String getOperationName() { + return this.operationName; + } + + /** + * Optional. The name of the performed operation. + * @param operationNameValue The OperationName value. + */ + public void setOperationName(final String operationNameValue) { + this.operationName = operationNameValue; + } + + private String operationObjectId; + + /** + * Optional. The target object for the operation. This value is equal to + * the URL for performing an HTTP GET on the object, and corresponds to + * the same values for the ObjectIdFilter in the request. + * @return The OperationObjectId value. + */ + public String getOperationObjectId() { + return this.operationObjectId; + } + + /** + * Optional. The target object for the operation. This value is equal to + * the URL for performing an HTTP GET on the object, and corresponds to + * the same values for the ObjectIdFilter in the request. + * @param operationObjectIdValue The OperationObjectId value. + */ + public void setOperationObjectId(final String operationObjectIdValue) { + this.operationObjectId = operationObjectIdValue; + } + + private HashMap operationParameters; + + /** + * Optional. The collection of parameters for the performed operation. + * @return The OperationParameters value. + */ + public HashMap getOperationParameters() { + return this.operationParameters; + } + + /** + * Optional. The collection of parameters for the performed operation. + * @param operationParametersValue The OperationParameters value. + */ + public void setOperationParameters(final HashMap operationParametersValue) { + this.operationParameters = operationParametersValue; + } + + private Calendar operationStartedTime; + + /** + * Optional. The time that the operation started to execute. + * @return The OperationStartedTime value. + */ + public Calendar getOperationStartedTime() { + return this.operationStartedTime; + } + + /** + * Optional. The time that the operation started to execute. + * @param operationStartedTimeValue The OperationStartedTime value. + */ + public void setOperationStartedTime(final Calendar operationStartedTimeValue) { + this.operationStartedTime = operationStartedTimeValue; + } + + private String operationStatus; + + /** + * Optional. An object that contains information on the current status + * of the operation. The object returned has the following XML format: + * 339c6c13-1f81-412f-9bc6-00e9c5876695 + * Succeeded 200 + * . Possible values of the Status element, + * whichholds the operation status, are: Succeeded, Failed, or + * InProgress. + * @return The OperationStatus value. + */ + public String getOperationStatus() { + return this.operationStatus; + } + + /** + * Optional. An object that contains information on the current status + * of the operation. The object returned has the following XML format: + * 339c6c13-1f81-412f-9bc6-00e9c5876695 + * Succeeded 200 + * . Possible values of the Status element, + * whichholds the operation status, are: Succeeded, Failed, or + * InProgress. + * @param operationStatusValue The OperationStatus value. + */ + public void setOperationStatus(final String operationStatusValue) { + this.operationStatus = operationStatusValue; + } + + /** + * Initializes a new instance of the SubscriptionOperation class. + * + */ + public SubscriptionOperation() { + this.operationParameters = new HashMap(); + } + } +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionOperationNames.java b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionOperationNames.java new file mode 100644 index 0000000000000..9d30bb3928cd7 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionOperationNames.java @@ -0,0 +1,107 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* The name of a subscription operation. +*/ +public abstract class SubscriptionOperationNames { + public static final String ACTIVATEDOMAINNAME = "ActivateDomainName"; + + public static final String ADDCERTIFICATES = "AddCertificates"; + + public static final String ADDSUBSCRIPTIONCERTIFICATE = "AddSubscriptionCertificate"; + + public static final String CHANGEDEPLOYMENTCONFIGURATION = "ChangeDeploymentConfiguration"; + + public static final String CHANGEDEPLOYMENTCONFIGURATIONBYSLOT = "ChangeDeploymentConfigurationBySlot"; + + public static final String COMMITIMAGEUPLOAD = "CommitImageUpload"; + + public static final String CREATEAFFINITYGROUP = "CreateAffinityGroup"; + + public static final String CREATEDEPLOYMENT = "CreateDeployment"; + + public static final String CREATEDEPLOYMENTBYSLOT = "CreateDeploymentBySlot"; + + public static final String CREATEHOSTEDSERVICE = "CreateHostedService"; + + public static final String CREATESTORAGESERVICE = "CreateStorageService"; + + public static final String DELETEAFFINITYGROUP = "DeleteAffinityGroup"; + + public static final String DELETECERTIFICATE = "DeleteCertificate"; + + public static final String DELETEDEPLOYMENT = "DeleteDeployment"; + + public static final String DELETEHOSTEDSERVICE = "DeleteHostedService"; + + public static final String DELETEIMAGE = "DeleteImage"; + + public static final String DELETESTORAGESERVICE = "DeleteStorageService"; + + public static final String PREPAREIMAGEUPLOAD = "PrepareImageUpload"; + + public static final String REBOOTDEPLOYMENTROLEINSTANCE = "RebootDeploymentRoleInstance"; + + public static final String REBOOTDEPLOYMENTROLEINSTANCEBYSLOT = "RebootDeploymentRoleInstanceBySlot"; + + public static final String REIMAGEDEPLOYMENTROLEINSTANCE = "ReimageDeploymentRoleInstance"; + + public static final String REIMAGEDEPLOYMENTROLEINSTANCEBYSLOT = "ReimageDeploymentRoleInstanceBySlot"; + + public static final String REGENERATESTORAGESERVICEKEYS = "RegenerateStorageServiceKeys"; + + public static final String REGISTERDOMAINNAME = "RegisterDomainName"; + + public static final String REMOVESUBSCRIPTIONCERTIFICATE = "RemoveSubscriptionCertificate"; + + public static final String ROLLBACKDEPLOYMENTUPDATEORUPGRADE = "RollbackDeploymentUpdateOrUpgrade"; + + public static final String SETIMAGEPROPERTIES = "SetImageProperties"; + + public static final String SETPARENTIMAGE = "SetParentImage"; + + public static final String SWAPDEPLOYMENT = "SwapDeployment"; + + public static final String UNREGISTERDOMAINNAME = "UnregisterDomainName"; + + public static final String UPDATEAFFINITYGROUP = "UpdateAffinityGroup"; + + public static final String UPDATEDEPLOYMENTSTATUS = "UpdateDeploymentStatus"; + + public static final String UPDATEDEPLOYMENTSTATUSBYSLOT = "UpdateDeploymentStatusBySlot"; + + public static final String UPDATEHOSTEDSERVICE = "UpdateHostedService"; + + public static final String UPDATESTORAGESERVICE = "UpdateStorageService"; + + public static final String UPGRADEDEPLOYMENT = "UpgradeDeployment"; + + public static final String UPGRADEDEPLOYMENTBYSLOT = "UpgradeDeploymentBySlot"; + + public static final String WALKUPGRADEDOMAIN = "WalkUpgradeDomain"; + + public static final String WALKUPGRADEDOMAINBYSLOT = "WalkUpgradeDomainBySlot"; +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionStatus.java b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionStatus.java new file mode 100644 index 0000000000000..2707a899b0386 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/SubscriptionStatus.java @@ -0,0 +1,33 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Warning: This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if the +// code is regenerated. + +package com.microsoft.windowsazure.management.models; + +/** +* The subscription status. +*/ +public enum SubscriptionStatus { + Active, + + Disabled, +} diff --git a/management/src/main/java/com/microsoft/windowsazure/management/models/package.html b/management/src/main/java/com/microsoft/windowsazure/management/models/package.html new file mode 100644 index 0000000000000..59ca7af26eb47 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/models/package.html @@ -0,0 +1,4 @@ + + +This package contains the models for the management service. + diff --git a/management/src/main/java/com/microsoft/windowsazure/management/package.html b/management/src/main/java/com/microsoft/windowsazure/management/package.html new file mode 100644 index 0000000000000..fa2e6d6428998 --- /dev/null +++ b/management/src/main/java/com/microsoft/windowsazure/management/package.html @@ -0,0 +1,6 @@ + + +This package contains the management class, + interface, and associated configuration and utility classes. + + diff --git a/management/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/management/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..fe120b2ad20ea --- /dev/null +++ b/management/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1 @@ +com.microsoft.windowsazure.management.Exports \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/AffinityGroupOperationsTests.java b/management/src/test/java/com/microsoft/windowsazure/management/AffinityGroupOperationsTests.java new file mode 100644 index 0000000000000..5347e96734c72 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/AffinityGroupOperationsTests.java @@ -0,0 +1,143 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management; + +import java.util.ArrayList; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.core.OperationResponse; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.management.models.AffinityGroupCreateParameters; +import com.microsoft.windowsazure.management.models.AffinityGroupGetResponse; +import com.microsoft.windowsazure.management.models.AffinityGroupListResponse; +import com.microsoft.windowsazure.management.models.AffinityGroupUpdateParameters; + +public class AffinityGroupOperationsTests extends ManagementIntegrationTestBase { + private static final String affinityGroupName1 = "testAffinityGroup1"; + private static final String affinityGroupName2 = "testAffinityGroup2"; + private static final String affinityGroupLocation1 = "West US"; + private static final String affinityGroupLocation2 = "East US"; + private static final String affinityGrouplabel1 = "testAffinityGroup1 Label"; + private static final String affinityGroupLabel2 = "testAffinityGroup2 Label"; + private static final String affinityGroupDescription1 = "testAffinityGroupDescription1"; + private static final String affinityGroupDescription2 = "testAffinityGroupDescription2"; + + @BeforeClass + public static void setup() throws Exception { + createService(); + cleanup(); + + AffinityGroupCreateParameters createParameters = new AffinityGroupCreateParameters(); + createParameters.setName(affinityGroupName1); + createParameters.setLocation(affinityGroupLocation1); + createParameters.setLabel(affinityGrouplabel1); + createParameters.setDescription(affinityGroupDescription1); + + managementClient.getAffinityGroupsOperations().create(createParameters); + } + + @AfterClass + public static void cleanup() throws Exception { + try { + AffinityGroupListResponse affinityGroupListResponse = managementClient.getAffinityGroupsOperations().list(); + ArrayList affinityGrouplist = affinityGroupListResponse.getAffinityGroups(); + for (AffinityGroupListResponse.AffinityGroup affinitygroup : affinityGrouplist) { + if (affinitygroup.getName().contains("testAffinityGroup")) { + managementClient.getAffinityGroupsOperations().delete(affinitygroup.getName()); + } + } + } + catch (ServiceException e) { + e.printStackTrace(); + } + } + + @Test + public void createAffinityGroup() throws Exception { + // Arrange + AffinityGroupCreateParameters createParameters = new AffinityGroupCreateParameters(); + createParameters.setName(affinityGroupName2); + createParameters.setLocation(affinityGroupLocation2); + createParameters.setLabel(affinityGroupLabel2); + createParameters.setDescription(affinityGroupDescription2); + + // Act + OperationResponse operationResponse = managementClient + .getAffinityGroupsOperations().create(createParameters); + + // Assert + Assert.assertEquals(201, operationResponse.getStatusCode()); + Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void getAffinityGroups() throws Exception { + // Act + AffinityGroupGetResponse affinityGroupResponse = managementClient + .getAffinityGroupsOperations().get(affinityGroupName1); + + // Assert + Assert.assertEquals(200, affinityGroupResponse.getStatusCode()); + Assert.assertNotNull(affinityGroupResponse.getRequestId()); + Assert.assertNotNull(affinityGroupResponse.getCapabilities()); + Assert.assertEquals(affinityGroupName1, affinityGroupResponse.getName()); + Assert.assertEquals(affinityGroupLocation1, affinityGroupResponse.getLocation()); + Assert.assertEquals(affinityGrouplabel1, affinityGroupResponse.getLabel()); + Assert.assertEquals(affinityGroupDescription1, affinityGroupResponse.getDescription()); + Assert.assertNotNull(affinityGroupResponse.getHostedServices()); + Assert.assertNotNull(affinityGroupResponse.getStorageServices()); + } + + @Test + public void listAffinityGroupsSuccess() throws Exception { + // Arrange + AffinityGroupListResponse affinityGroupListResponse = managementClient.getAffinityGroupsOperations().list(); + ArrayList affinityGrouplist = affinityGroupListResponse.getAffinityGroups(); + Assert.assertNotNull(affinityGrouplist); + } + + @Test + public void updateAffinityGroupSuccess() throws Exception { + // Arrange + String expectedAffinityGroupName = "testAffinityGroupUpdateSuccess"; + String expectedAffinityGroupLabel = "testAffinityGroupUpdateSuccessLabel"; + String expectedUpdatedAffinityGroupLabel = "testAffinityGroupUpdatedSuccessLabel"; + String expectedLocation = "West US"; + String expectedDescription = "updateAffinityGroupSuccess"; + + AffinityGroupCreateParameters createParameters = new AffinityGroupCreateParameters(); + createParameters.setName(expectedAffinityGroupName); + createParameters.setLocation(expectedLocation); + createParameters.setLabel(expectedAffinityGroupLabel ); + + // Act + OperationResponse operationResponse = managementClient.getAffinityGroupsOperations().create(createParameters); + Assert.assertEquals(201, operationResponse.getStatusCode()); + + AffinityGroupUpdateParameters updateParameters = new AffinityGroupUpdateParameters(); + updateParameters.setLabel(expectedUpdatedAffinityGroupLabel); + updateParameters.setDescription(expectedDescription); + OperationResponse updateoperationResponse = managementClient.getAffinityGroupsOperations().update(expectedAffinityGroupName, updateParameters); + + // Assert + Assert.assertEquals(200, updateoperationResponse.getStatusCode()); + Assert.assertNotNull(updateoperationResponse.getRequestId()); + } +} \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/LocationOperationsTest.java b/management/src/test/java/com/microsoft/windowsazure/management/LocationOperationsTest.java new file mode 100644 index 0000000000000..030cf5c916e5e --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/LocationOperationsTest.java @@ -0,0 +1,37 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.management.models.LocationsListResponse; + +public class LocationOperationsTest extends ManagementIntegrationTestBase { + @BeforeClass + public static void setup() throws Exception { + createService(); + } + + @Test + public void listLocationSuccess() throws Exception { + LocationsListResponse locationsListResponse = managementClient.getLocationsOperations().list(); + Assert.assertEquals(200, locationsListResponse.getStatusCode()); + Assert.assertNotNull(locationsListResponse.getRequestId()); + Assert.assertTrue(locationsListResponse.getLocations().size() > 0); + } +} \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/ManagementCertificateOperationsTests.java b/management/src/test/java/com/microsoft/windowsazure/management/ManagementCertificateOperationsTests.java new file mode 100644 index 0000000000000..68423b72da637 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/ManagementCertificateOperationsTests.java @@ -0,0 +1,77 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management; + +import java.util.ArrayList; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.management.models.ManagementCertificateGetResponse; +import com.microsoft.windowsazure.management.models.ManagementCertificateListResponse; + +public class ManagementCertificateOperationsTests extends ManagementIntegrationTestBase { + @BeforeClass + public static void setup() throws Exception { + createService(); + } + + @Test + public void createManagementCertificate() throws Exception { + // Arrange + +// ManagementCertificateCreateParameters createParameters = new ManagementCertificateCreateParameters(); +//// createParameters.setData(dataValue); +//// createParameters.setPublicKey(publicKeyValue); +//// createParameters.setThumbprint(thumbprintValue); +// +// // Act +// OperationResponse operationResponse = managementClient.getManagementCertificatesOperations().create(createParameters); +// +// // Assert +// Assert.assertEquals(201, operationResponse.getStatusCode()); +// Assert.assertNotNull(operationResponse.getRequestId()); + } + + @Test + public void getManagementCertificateSuccess() throws Exception { + + // arrange + ManagementCertificateListResponse managementCertificateListResponse = managementClient.getManagementCertificatesOperations().list(); + ArrayList managementCertificatelist = managementCertificateListResponse.getSubscriptionCertificates(); + + if (managementCertificatelist.size() > 0) { + String thumbprint = managementCertificatelist.get(0).getThumbprint(); + + ManagementCertificateGetResponse managementCertificateResponse = managementClient.getManagementCertificatesOperations().get(thumbprint); + + // Assert + Assert.assertEquals(200, managementCertificateResponse.getStatusCode()); + Assert.assertNotNull(managementCertificateResponse.getRequestId()); + Assert.assertEquals(thumbprint, managementCertificateResponse.getThumbprint()); + } + } + + @Test + public void listManagementCertificateSuccess() throws Exception { + // Arrange + ManagementCertificateListResponse managementCertificateListResponse = managementClient.getManagementCertificatesOperations().list(); + ArrayList managementCertificatelist = managementCertificateListResponse.getSubscriptionCertificates(); + + Assert.assertNotNull(managementCertificatelist);; + } +} diff --git a/management/src/test/java/com/microsoft/windowsazure/management/ManagementClientTests.java b/management/src/test/java/com/microsoft/windowsazure/management/ManagementClientTests.java new file mode 100644 index 0000000000000..88016848e50d5 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/ManagementClientTests.java @@ -0,0 +1,251 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package com.microsoft.windowsazure.management; + +import java.net.URI; +import java.util.Map; + +import junit.framework.Assert; + +import org.junit.Test; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; +import com.microsoft.windowsazure.management.models.AffinityGroupListResponse; +import com.microsoft.windowsazure.management.util.TestRequestFilter; +import com.microsoft.windowsazure.management.util.TestResponseFilter; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.filter.LoggingFilter; + +public class ManagementClientTests extends ManagementIntegrationTestBase { + @Test + public void createWithRequestFilterLast() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + managementClient = ManagementService.create(config); + + TestRequestFilter testFilter = new TestRequestFilter("filter1a"); + ManagementClient filteredService = managementClient.withRequestFilterLast(testFilter); + + // Executing operation on the filtered service should execute the filter + AffinityGroupListResponse response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(1, testFilter.getCalled()); + + // Make sure the filter executes twice + response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(2, testFilter.getCalled()); + } + + @Test + public void createWithRequestLastRespectsOrder() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Builder.Registry builder = (Builder.Registry) config.getBuilder(); + builder.alter(ManagementClient.class, Client.class, new Builder.Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + managementClient = ManagementService.create(config); + + TestRequestFilter testFilter1 = new TestRequestFilter("filter1b"); + TestRequestFilter testFilter2 = new TestRequestFilter("filter2b"); + ManagementClient filteredService = managementClient.withRequestFilterLast(testFilter1); + filteredService = filteredService.withRequestFilterLast(testFilter2); + + // Executing operation on the filtered service should execute the filter + AffinityGroupListResponse response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(0, testFilter1.getCalled()); + Assert.assertEquals(1, testFilter2.getCalled()); + + // Make sure the filter executes twice + response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(0, testFilter1.getCalled()); + Assert.assertEquals(2, testFilter2.getCalled()); + } + + @Test + public void createWithRequestFirstRespectsOrder() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Builder.Registry builder = (Builder.Registry) config.getBuilder(); + builder.alter(ManagementClient.class, Client.class, new Builder.Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + managementClient = ManagementService.create(config); + + TestRequestFilter testFilter1 = new TestRequestFilter("filter1c"); + TestRequestFilter testFilter2 = new TestRequestFilter("filter2c"); + ManagementClient filteredService = managementClient.withRequestFilterFirst(testFilter1); + filteredService = filteredService.withRequestFilterFirst(testFilter2); + + // Executing operation on the filtered service should execute the filter + AffinityGroupListResponse response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(1, testFilter1.getCalled()); + Assert.assertEquals(0, testFilter2.getCalled()); + + // Make sure the filter executes twice + response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(2, testFilter1.getCalled()); + Assert.assertEquals(0, testFilter2.getCalled()); + } + + @Test + public void createWithResponseLastRespectsOrder() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Builder.Registry builder = (Builder.Registry) config.getBuilder(); + builder.alter(ManagementClient.class, Client.class, new Builder.Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + managementClient = ManagementService.create(config); + + TestResponseFilter testFilter1 = new TestResponseFilter("filter1b"); + TestResponseFilter testFilter2 = new TestResponseFilter("filter2b"); + ManagementClient filteredService = managementClient.withResponseFilterLast(testFilter1); + filteredService = filteredService.withResponseFilterLast(testFilter2); + + // Executing operation on the filtered service should execute the filter + AffinityGroupListResponse response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(0, testFilter1.getCalled()); + Assert.assertEquals(1, testFilter2.getCalled()); + + // Make sure the filter executes twice + response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(0, testFilter1.getCalled()); + Assert.assertEquals(2, testFilter2.getCalled()); + } + + @Test + public void createWithResponseFirstRespectsOrder() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Builder.Registry builder = (Builder.Registry) config.getBuilder(); + builder.alter(ManagementClient.class, Client.class, new Builder.Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + managementClient = ManagementService.create(config); + + TestResponseFilter testFilter1 = new TestResponseFilter("filter1c"); + TestResponseFilter testFilter2 = new TestResponseFilter("filter2c"); + ManagementClient filteredService = managementClient.withResponseFilterFirst(testFilter1); + filteredService = filteredService.withResponseFilterFirst(testFilter2); + + // Executing operation on the filtered service should execute the filter + AffinityGroupListResponse response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(1, testFilter1.getCalled()); + Assert.assertEquals(0, testFilter2.getCalled()); + + // Make sure the filter executes twice + response = filteredService.getAffinityGroupsOperations().list(); + + Assert.assertEquals(200, response.getStatusCode()); + Assert.assertEquals(2, testFilter1.getCalled()); + Assert.assertEquals(0, testFilter2.getCalled()); + } + + @Test + public void getCredential() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Builder.Registry builder = (Builder.Registry) config.getBuilder(); + builder.alter(ManagementClient.class, Client.class, new Builder.Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + managementClient = ManagementService.create(config); + + SubscriptionCloudCredentials subscriptionCloudCredentials = managementClient.getCredentials(); + + Assert.assertNotNull(subscriptionCloudCredentials.getSubscriptionId()); + } + + @Test + public void getUri() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Builder.Registry builder = (Builder.Registry) config.getBuilder(); + builder.alter(ManagementClient.class, Client.class, new Builder.Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + managementClient = ManagementService.create(config); + + URI uri = managementClient.getBaseUri(); + URI expectUri = new URI("https://management.core.windows.net"); + + Assert.assertEquals(expectUri.getHost(), uri.getHost()); + } +} \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/ManagementIntegrationTestBase.java b/management/src/test/java/com/microsoft/windowsazure/management/ManagementIntegrationTestBase.java new file mode 100644 index 0000000000000..d05b503f48232 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/ManagementIntegrationTestBase.java @@ -0,0 +1,64 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.management; + +import java.net.URI; +import java.util.Map; + +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; + +import com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigurationProperties; +import com.microsoft.windowsazure.core.utils.KeyStoreType; +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Alteration; +import com.microsoft.windowsazure.core.Builder.Registry; +import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.filter.LoggingFilter; + +public abstract class ManagementIntegrationTestBase { + + protected static ManagementClient managementClient; + + protected static void createService() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER, new DefaultHttpRequestRetryHandler()); + + // add LoggingFilter to any pipeline that is created + Registry builder = (Registry) config.getBuilder(); + builder.alter(ManagementClient.class, Client.class, new Alteration() { + @Override + public Client alter(String profile, Client client, Builder builder, Map properties) { + client.addFilter(new LoggingFilter()); + return client; + } + }); + + managementClient = ManagementService.create(config); + } + + protected static Configuration createConfiguration() throws Exception { + String baseUri = System.getenv(ManagementConfiguration.URI); + return ManagementConfiguration.configure( + baseUri != null ? new URI(baseUri) : null, + System.getenv(ManagementConfiguration.SUBSCRIPTION_ID), + System.getenv(ManagementConfiguration.KEYSTORE_PATH), + System.getenv(ManagementConfiguration.KEYSTORE_PASSWORD), + KeyStoreType.fromString(System.getenv(ManagementConfiguration.KEYSTORE_TYPE)) + ); + } +} \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/RoleSizeOperationsTest.java b/management/src/test/java/com/microsoft/windowsazure/management/RoleSizeOperationsTest.java new file mode 100644 index 0000000000000..9219d0c618142 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/RoleSizeOperationsTest.java @@ -0,0 +1,38 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.management.models.RoleSizeListResponse; + +public class RoleSizeOperationsTest extends ManagementIntegrationTestBase { + @BeforeClass + public static void setup() throws Exception { + createService(); + } + + @Test + public void listRoleSizeSuccess() throws Exception { + RoleSizeListResponse roleSizeListResponse = managementClient.getRoleSizesOperations().list(); + + Assert.assertEquals(200, roleSizeListResponse.getStatusCode()); + Assert.assertNotNull(roleSizeListResponse.getRequestId()); + Assert.assertTrue(roleSizeListResponse.getRoleSizes().size() > 0); + } +} \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/SubscriptionOperationsTest.java b/management/src/test/java/com/microsoft/windowsazure/management/SubscriptionOperationsTest.java new file mode 100644 index 0000000000000..79e86043e6ee2 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/SubscriptionOperationsTest.java @@ -0,0 +1,73 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management; + +import java.util.Calendar; +import java.util.TimeZone; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.management.models.SubscriptionGetResponse; +import com.microsoft.windowsazure.management.models.SubscriptionListOperationsParameters; +import com.microsoft.windowsazure.management.models.SubscriptionListOperationsResponse; + +public class SubscriptionOperationsTest extends ManagementIntegrationTestBase { + + @BeforeClass + public static void setup() throws Exception { + createService(); + } + + @Test + public void getSubscriptionSuccess() throws Exception { + // Act + SubscriptionGetResponse subscriptionGetResponse = managementClient.getSubscriptionsOperations().get(); + // Assert + Assert.assertEquals(200, subscriptionGetResponse.getStatusCode()); + Assert.assertNotNull(subscriptionGetResponse.getRequestId()); + Assert.assertNotNull(subscriptionGetResponse.getAccountAdminLiveEmailId()); + Assert.assertNotNull(subscriptionGetResponse.getSubscriptionID()); + + Assert.assertEquals("Azure SDK sandbox", subscriptionGetResponse.getSubscriptionName()); + Assert.assertEquals(10, subscriptionGetResponse.getMaximumVirtualNetworkSites()); + Assert.assertEquals(10, subscriptionGetResponse.getMaximumLocalNetworkSites()); + Assert.assertEquals(9, subscriptionGetResponse.getMaximumDnsServers()); + Assert.assertEquals(20, subscriptionGetResponse.getMaximumStorageAccounts()); + } + + @Test + public void listSubscriptionsSuccess() throws Exception { + // Arrange + SubscriptionListOperationsParameters parameters = new SubscriptionListOperationsParameters(); + + Calendar now = Calendar.getInstance(); + Calendar startTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + startTime.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH) , now.get(Calendar.DATE - 5)); + Calendar endTime = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + endTime.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH) , now.get(Calendar.DATE - 1)); + parameters.setStartTime(startTime); + parameters.setEndTime(endTime); + + SubscriptionListOperationsResponse subscriptionListOperationsResponse = managementClient.getSubscriptionsOperations().listOperations(parameters); + + Assert.assertEquals(200, subscriptionListOperationsResponse.getStatusCode()); + Assert.assertNotNull(subscriptionListOperationsResponse.getRequestId()); + Assert.assertEquals(50, subscriptionListOperationsResponse.getSubscriptionOperations().size()); + } +} + \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/util/TestRequestFilter.java b/management/src/test/java/com/microsoft/windowsazure/management/util/TestRequestFilter.java new file mode 100644 index 0000000000000..220cbe83aefd9 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/util/TestRequestFilter.java @@ -0,0 +1,51 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.util; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; + +public class TestRequestFilter implements ServiceRequestFilter +{ + private int called; + private String identifier; + + public int getCalled() { return this.called; } + + public String getIdentifier() { return this.identifier; } + + public TestRequestFilter(String identifier) + { + this.called = 0; + this.identifier = identifier; + } + + public TestRequestFilter() + { + this.called = 0; + } + + @Override + public void filter (ServiceRequestContext request) + { + if (request.getProperty("executed") == null) + { + request.setProperty("executed", true); + + called++; + } + } +} \ No newline at end of file diff --git a/management/src/test/java/com/microsoft/windowsazure/management/util/TestResponseFilter.java b/management/src/test/java/com/microsoft/windowsazure/management/util/TestResponseFilter.java new file mode 100644 index 0000000000000..019c40d5d3713 --- /dev/null +++ b/management/src/test/java/com/microsoft/windowsazure/management/util/TestResponseFilter.java @@ -0,0 +1,52 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.management.util; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; + +public class TestResponseFilter implements ServiceResponseFilter +{ + private int called; + private String identifier; + + public int getCalled() { return this.called; } + + public String getIdentifier() { return this.identifier; } + + public TestResponseFilter(String identifier) + { + this.called = 0; + this.identifier = identifier; + } + + public TestResponseFilter() + { + this.called = 0; + } + + @Override + public void filter (ServiceRequestContext request, ServiceResponseContext response) + { + if (response.getProperty("executed") == null) + { + response.setProperty("executed", true); + + called++; + } + } +} \ No newline at end of file diff --git a/management/src/test/resources/META-INF/com.microsoft.windowsazure.properties b/management/src/test/resources/META-INF/com.microsoft.windowsazure.properties new file mode 100644 index 0000000000000..c3a7631fc3948 --- /dev/null +++ b/management/src/test/resources/META-INF/com.microsoft.windowsazure.properties @@ -0,0 +1,7 @@ +management.keystore.path= +management.keystore.password= +management.keystore.type= +management.subscription.id= +management.uri= +testprefix.com.microsoft.windowsazure.services.core.Configuration.connectTimeout=3 +testprefix.com.microsoft.windowsazure.services.core.Configuration.readTimeout=7 \ No newline at end of file diff --git a/media/pom.xml b/media/pom.xml new file mode 100644 index 0000000000000..f986dd1f09355 --- /dev/null +++ b/media/pom.xml @@ -0,0 +1,233 @@ + + + 4.0.0 + + com.microsoft.windowsazure + microsoft-azure-api-parent + 0.5.0 + ../parent/pom.xml + + + microsoft-azure-api-media + jar + + Microsoft Azure Media Client API + Microsoft Azure Media SDK Clients + https://github.com/Azure/azure-sdk-for-java + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + + + + + microsoft + Microsoft + + + + + + ${project.groupId} + microsoft-azure-api-core + 0.5.0 + + + org.apache.httpcomponents + httpclient + + + javax.xml.bind + jaxb-api + provided + + + javax.mail + mail + + + javax.inject + javax.inject + + + com.sun.jersey + jersey-client + + + com.sun.jersey + jersey-json + + + commons-logging + commons-logging + + + + + org.hamcrest + hamcrest-all + test + + + org.mockito + mockito-all + test + + + junit + junit + test + + + org.bouncycastle + bcprov-jdk16 + test + + + + + + + org.apache.maven.plugins + maven-help-plugin + 2.1.1 + + + validate + + evaluate + + + legal + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage + /** +
* Copyright Microsoft Corporation +
* +
* Licensed under the Apache License, Version 2.0 (the "License"); +
* you may not use this file except in compliance with the License. +
* You may obtain a copy of the License at +
* http://www.apache.org/licenses/LICENSE-2.0 +
* +
* Unless required by applicable law or agreed to in writing, software +
* distributed under the License is distributed on an "AS IS" BASIS, +
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +
* See the License for the specific language governing permissions and +
* limitations under the License. +
*/]]>
+
+
+ +
+ + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.apache.maven.plugins + maven-help-plugin + [2.1.1,) + + evaluate + + + + + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.4.3 + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + **/Test*.java + **/*Test.java + **/*Tests.java + **/*TestCase.java + + + + + +
+ + + + org.codehaus.mojo + emma-maven-plugin + 1.0-alpha-3 + true + + + org.codehaus.mojo + surefire-report-maven-plugin + 2.0-beta-1 + true + + + +
diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobConfiguration.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobConfiguration.java new file mode 100644 index 0000000000000..59e9653e5bd07 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobConfiguration.java @@ -0,0 +1,44 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob; + +/** + * This class contains static strings used to identify parts of a service + * configuration instance associated with the Windows Azure Blob service. + *

+ * These values must not be altered. + */ +public abstract class BlobConfiguration { + /** + * The Blob configuration account name constant. This String + * value is used as a key in the configuration file, to identify the value + * for the DNS prefix name for the storage account. + */ + public static final String ACCOUNT_NAME = "blob.accountName"; + + /** + * The Blob configuration account key constant. This String + * value is used as a key in the configuration file, to identify the value + * for the storage service account key. + */ + public static final String ACCOUNT_KEY = "blob.accountKey"; + + /** + * The Blob configuration URI constant. This String value is + * used as a key in the configuration file, to identify the URI value for + * the Blob storage service REST API address for the storage account. + */ + public static final String URI = "blob.uri"; +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobContract.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobContract.java new file mode 100644 index 0000000000000..2c71143accc52 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobContract.java @@ -0,0 +1,563 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob; + +import java.io.InputStream; + +import com.microsoft.windowsazure.core.pipeline.jersey.JerseyFilterableService; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.blob.models.BlockList; +import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; +import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; +import com.microsoft.windowsazure.services.blob.models.DeleteBlobOptions; +import com.microsoft.windowsazure.services.blob.models.DeleteContainerOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; +import com.microsoft.windowsazure.services.blob.models.GetBlobResult; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; +import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; +import com.microsoft.windowsazure.services.blob.models.ListContainersResult; + +/** + * Defines the methods available on the Windows Azure blob storage service. + * Construct an object instance implementing BlobContract with one + * of the static create methods on {@link BlobService}. These methods + * associate a Configuration with the implementation, so the + * methods on the instance of BlobContract all work with a + * particular storage account. + */ +public interface BlobContract extends JerseyFilterableService { + + /** + * Marks a blob for deletion. + *

+ * This method marks the properties, metadata, and content of the blob + * specified by the blob and container parameters for + * deletion. + *

+ * When a blob is successfully deleted, it is immediately removed from the + * storage account's index and is no longer accessible to clients. The + * blob's data is later removed from the service during garbage collection. + *

+ * Note that in order to delete a blob, you must delete all of its + * snapshots. You can delete an individual snapshot, only the snapshots, or + * both the blob and its snapshots with the + * {@link #deleteBlob(String, String, DeleteBlobOptions)} method. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to delete. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void deleteBlob(String container, String blob) throws ServiceException; + + /** + * Marks a blob or snapshot for deletion, using the specified options. + *

+ * This method marks the properties, metadata, and content of the blob or + * snapshot specified by the blob and container parameters + * for deletion. Use the {@link DeleteBlobOptions options} parameter to set + * an optional server timeout for the operation, a snapshot timestamp to + * specify an individual snapshot to delete, a blob lease ID to delete a + * blob with an active lease, a flag indicating whether to delete all + * snapshots but not the blob, or both the blob and all snapshots, and any + * access conditions to satisfy. + *

+ * When a blob is successfully deleted, it is immediately removed from the + * storage account's index and is no longer accessible to clients. The + * blob's data is later removed from the service during garbage collection. + *

+ * If the blob has an active lease, the client must specify a valid lease ID + * in the options parameter in order to delete it. + *

+ * If a blob has a large number of snapshots, it's possible that the delete + * blob operation will time out. If this happens, the client should retry + * the request. + * + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to delete. + * @param options + * A {@link DeleteBlobOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void deleteBlob(String container, String blob, DeleteBlobOptions options) + throws ServiceException; + + /** + * Gets a list of the containers in the blob storage account. + * + * @return A {@link ListContainersResult} reference to the result of the + * list containers operation. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + ListContainersResult listContainers() throws ServiceException; + + /** + * Gets a list of the containers in the blob storage account using the + * specified options. + *

+ * Use the {@link ListContainersOptions options} parameter to specify + * options, including a server response timeout for the request, a container + * name prefix filter, a marker for continuing requests, the maximum number + * of results to return in a request, and whether to include container + * metadata in the results. + * + * @param options + * A {@link ListContainersOptions} instance containing options + * for the request. + * @return A {@link ListContainersResult} reference to the result of the + * list containers operation. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + ListContainersResult listContainers(ListContainersOptions options) + throws ServiceException; + + /** + * Creates a container with the specified name. + *

+ * Container names must be unique within a storage account, and must follow + * the naming rules specified in Naming and Referencing Containers, Blobs, and Metadata. + * + * @param container + * A {@link String} containing the name of the container to + * create. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void createContainer(String container) throws ServiceException; + + /** + * Creates a container with the specified name, using the specified options. + *

+ * Use the {@link CreateContainerOptions options} parameter to specify + * options, including a server response timeout for the request, metadata to + * set on the container, and the public access level for container and blob + * data. Container names must be unique within a storage account, and must + * follow the naming rules specified in Naming and Referencing Containers, Blobs, and Metadata. + * + * @param container + * A {@link String} containing the name of the container to + * create. + * @param options + * A {@link CreateContainerOptions} instance containing options + * for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void createContainer(String container, CreateContainerOptions options) + throws ServiceException; + + /** + * Marks a container for deletion. The container and any blobs contained + * within it are later deleted during garbage collection. + *

+ * When a container is deleted, a container with the same name cannot be + * created for at least 30 seconds; the container may not be available for + * more than 30 seconds if the service is still processing the request. + * + * @param container + * A {@link String} containing the name of the container to + * delete. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void deleteContainer(String container) throws ServiceException; + + /** + * Marks a container for deletion, using the specified options. The + * container and any blobs contained within it are later deleted during + * garbage collection. + *

+ * Use the {@link DeleteContainerOptions options} parameter to specify the + * server response timeout and any access conditions for the container + * deletion operation. Access conditions can be used to make the operation + * conditional on the value of the Etag or last modified time of the + * container. + *

+ * When a container is deleted, a container with the same name cannot be + * created for at least 30 seconds; the container may not be available for + * more than 30 seconds if the service is still processing the request. + * + * @param container + * A {@link String} containing the name of the container to + * delete. + * @param options + * A {@link DeleteContainerOptions} instance containing options + * for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void deleteContainer(String container, DeleteContainerOptions options) + throws ServiceException; + + /** + * Creates a block blob from a content stream. + * + * @param container + * A {@link String} containing the name of the container to + * create the blob in. + * @param blob + * A {@link String} containing the name of the blob to create. A + * blob name can contain any combination of characters, but + * reserved URL characters must be properly escaped. A blob name + * must be at least one character long and cannot be more than + * 1,024 characters long, and must be unique within the + * container. + * @param contentStream + * An {@link InputStream} reference to the content stream to + * upload to the new blob. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + CreateBlobResult createBlockBlob(String container, String blob, + InputStream contentStream) throws ServiceException; + + /** + * Creates a block blob from a content stream, using the specified options. + *

+ * Use the {@link CreateBlobOptions options} parameter to optionally specify + * the server timeout for the operation, the MIME content type and content + * encoding for the blob, the content language, the MD5 hash, a cache + * control value, and blob metadata. + * + * @param container + * A {@link String} containing the name of the container to + * create the blob in. + * @param blob + * A {@link String} containing the name of the blob to create. A + * blob name can contain any combination of characters, but + * reserved URL characters must be properly escaped. A blob name + * must be at least one character long and cannot be more than + * 1,024 characters long, and must be unique within the + * container. + * @param contentStream + * An {@link InputStream} reference to the content to upload to + * the new blob. + * @param options + * A {@link CreateBlobOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + CreateBlobResult createBlockBlob(String container, String blob, + InputStream contentStream, CreateBlobOptions options) + throws ServiceException; + + /** + * Creates a new uncommited block from a content stream. + *

+ * This method creates an uncommitted block for a block blob specified by + * the blob and container parameters. The blockId + * parameter is a client-specified ID for the block, which must be less than + * or equal to 64 bytes in size. For a given blob, the length of the value + * specified for the blockId parameter must be the same size for + * each block. The contentStream parameter specifies the content to + * be copied to the block. The content for the block must be less than or + * equal to 4 MB in size. + *

+ * To create or update a block blob, the blocks that have been successfully + * written to the server with this method must be committed using a call to + * {@link com.microsoft.windowsazure.services.blob.BlobContract#commitBlobBlocks(String, String, BlockList)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions)}. + * + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to create the + * block for. + * @param blockId + * A {@link String} containing a client-specified ID for the + * block. + * @param contentStream + * An {@link InputStream} reference to the content to copy to the + * block. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void createBlobBlock(String container, String blob, String blockId, + InputStream contentStream) throws ServiceException; + + /** + * Creates a new uncommitted block from a content stream, using the + * specified options. + *

+ * This method creates an uncommitted block for a block blob specified by + * the blob and container parameters. The blockId + * parameter is a client-specified ID for the block, which must be less than + * or equal to 64 bytes in size. For a given blob, the length of the value + * specified for the blockId parameter must be the same size for + * each block. The contentStream parameter specifies the content to + * be copied to the block. The content for the block must be less than or + * equal to 4 MB in size. Use the {@link CreateBlobBlockOptions options} + * parameter to optionally specify the server timeout for the operation, the + * lease ID if the blob has an active lease, and the MD5 hash value for the + * block content. + *

+ * To create or update a block blob, the blocks that have been successfully + * written to the server with this method must be committed using a call to + * {@link com.microsoft.windowsazure.services.blob.BlobContract#commitBlobBlocks(String, String, BlockList)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions)}. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to create the + * block for. + * @param blockId + * A {@link String} containing a client-specified ID for the + * block. + * @param contentStream + * An {@link InputStream} reference to the content to copy to the + * block. + * @param options + * A {@link CreateBlobBlockOptions} instance containing options + * for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void createBlobBlock(String container, String blob, String blockId, + InputStream contentStream, CreateBlobBlockOptions options) + throws ServiceException; + + /** + * Commits a list of blocks to a block blob. + *

+ * This method creates or updates the block blob specified by the + * blob and container parameters. You can call this method + * to update a blob by uploading only those blocks that have changed, then + * committing the new and existing blocks together. You can do this with the + * blockList parameter by specifying whether to commit a block from + * the committed block list or from the uncommitted block list, or to commit + * the most recently uploaded version of the block, whichever list it may + * belong to. + *

+ * In order to be written as part of a blob, each block in the list must + * have been successfully written to the server with a call to + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobBlock(String, String, String, InputStream)} + * or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobBlock(String, String, String, InputStream, CreateBlobBlockOptions)}. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the block blob to + * create or update. + * @param blockList + * A {@link BlockList} containing the list of blocks to commit to + * the block blob. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void commitBlobBlocks(String container, String blob, BlockList blockList) + throws ServiceException; + + /** + * Commits a block list to a block blob, using the specified options. + *

+ * This method creates or updates the block blob specified by the + * blob and container parameters. You can call this method + * to update a blob by uploading only those blocks that have changed, then + * committing the new and existing blocks together. You can do this with the + * blockList parameter by specifying whether to commit a block from + * the committed block list or from the uncommitted block list, or to commit + * the most recently uploaded version of the block, whichever list it may + * belong to. Use the {@link CommitBlobBlocksOptions options} parameter to + * optionally specify the server timeout for the operation, the MIME content + * type and content encoding for the blob, the content language, the MD5 + * hash, a cache control value, blob metadata, the lease ID if the blob has + * an active lease, and any access conditions for the operation. + *

+ * In order to be written as part of a blob, each block in the list must + * have been successfully written to the server with a call to + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobBlock(String, String, String, InputStream)} + * or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobBlock(String, String, String, InputStream, CreateBlobBlockOptions)}. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the block blob to + * create or update. + * @param blockList + * A {@link BlockList} containing the list of blocks to commit to + * the block blob. + * @param options + * A {@link CommitBlobBlocksOptions} instance containing options + * for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void commitBlobBlocks(String container, String blob, BlockList blockList, + CommitBlobBlocksOptions options) throws ServiceException; + + /** + * Lists the blocks of a blob. + *

+ * This method lists the committed blocks of the block blob specified by the + * blob and container parameters. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the block blob to + * list. + * @return A {@link ListBlobBlocksResult} instance containing the list of + * blocks returned for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + ListBlobBlocksResult listBlobBlocks(String container, String blob) + throws ServiceException; + + /** + * Lists the blocks of a blob, using the specified options. + *

+ * This method lists the committed blocks, uncommitted blocks, or both, of + * the block blob specified by the blob and container + * parameters. Use the {@link ListBlobBlocksOptions options} parameter to + * specify an optional server timeout for the operation, the lease ID if the + * blob has an active lease, the snapshot timestamp to get the committed + * blocks of a snapshot, whether to return the committed block list, and + * whether to return the uncommitted block list. By default, only the + * committed blocks of the blob are returned. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the block blob to + * list. + * @param options + * A {@link ListBlobBlocksOptions} instance containing options + * for the request. + * @return A {@link ListBlobBlocksResult} instance containing the list of + * blocks returned for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + ListBlobBlocksResult listBlobBlocks(String container, String blob, + ListBlobBlocksOptions options) throws ServiceException; + + /** + * Gets the properties of a blob. + *

+ * This method lists the properties of the blob specified by the + * blob and container parameters. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to get + * properties for. + * @return A {@link GetBlobPropertiesResult} instance containing the blob + * properties returned for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + GetBlobPropertiesResult getBlobProperties(String container, String blob) + throws ServiceException; + + /** + * Gets the properties of a blob, using the specified options. + *

+ * This method lists the properties of the blob specified by the + * blob and container parameters. Use the + * {@link GetBlobPropertiesOptions options} parameter to set an optional + * server timeout for the operation, the lease ID if the blob has an active + * lease, the snapshot timestamp to get the properties of a snapshot, and + * any access conditions for the request. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to get + * properties for. + * @param options + * A {@link GetBlobPropertiesOptions} instance containing options + * for the request. + * @return A {@link GetBlobPropertiesResult} instance containing the blob + * properties returned for the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + GetBlobPropertiesResult getBlobProperties(String container, String blob, + GetBlobPropertiesOptions options) throws ServiceException; + + /** + * Gets the properties, metadata, and content of a blob. + *

+ * This method gets the properties, metadata, and content of the blob + * specified by the blob and container parameters. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to get. + * @return A {@link GetBlobResult} instance containing the properties, + * metadata, and content of the blob from the server response to the + * request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + GetBlobResult getBlob(String container, String blob) + throws ServiceException; + + /** + * Gets the properties, metadata, and content of a blob or blob snapshot, + * using the specified options. + *

+ * This method gets the properties, metadata, and content of the blob + * specified by the blob and container parameters. Use the + * {@link GetBlobOptions options} parameter to set an optional server + * timeout for the operation, a snapshot timestamp to specify a snapshot, a + * blob lease ID to get a blob with an active lease, an optional start and + * end range for blob content to return, and any access conditions to + * satisfy. + * + * @param container + * A {@link String} containing the name of the blob's container. + * @param blob + * A {@link String} containing the name of the blob to get. + * @param options + * A {@link GetBlobOptions} instance containing options for the + * request. + * @return A {@link GetBlobResult} instance containing the properties, + * metadata, and content of the blob from the server response to the + * request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + GetBlobResult getBlob(String container, String blob, GetBlobOptions options) + throws ServiceException; + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobService.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobService.java new file mode 100644 index 0000000000000..2d0ccf5c5bd90 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/BlobService.java @@ -0,0 +1,99 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob; + +import com.microsoft.windowsazure.Configuration; + +/** + * A class for static factory methods that return instances implementing + * {@link com.microsoft.windowsazure.services.blob.BlobContract}. + */ +public final class BlobService { + private BlobService() { + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.blob.BlobContract} using default values for initializing a + * {@link Configuration} instance. Note that the returned interface will not + * work unless storage account credentials have been added to the + * "META-INF/com.microsoft.windowsazure.properties" resource file. + * + * @return An instance implementing {@link com.microsoft.windowsazure.services.blob.BlobContract} for interacting + * with the blob service. + */ + public static BlobContract create() { + return create(null, Configuration.getInstance()); + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.blob.BlobContract} using the specified {@link Configuration} instance. + * The {@link Configuration} instance must have storage account information + * and credentials set before this method is called for the returned + * interface to work. + * + * @param config + * A {@link Configuration} instance configured with storage + * account information and credentials. + * + * @return An instance implementing {@link com.microsoft.windowsazure.services.blob.BlobContract} for interacting + * with the blob service. + */ + public static BlobContract create(Configuration config) { + return create(null, config); + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.blob.BlobContract} using default values for initializing a + * {@link Configuration} instance, and using the specified profile prefix + * for service settings. Note that the returned interface will not work + * unless storage account settings and credentials have been added to the + * "META-INF/com.microsoft.windowsazure.properties" resource file with the + * specified profile prefix. + * + * @param profile + * A string prefix for the account name and credentials settings + * in the {@link Configuration} instance. + * @return An instance implementing {@link com.microsoft.windowsazure.services.blob.BlobContract} for interacting + * with the blob service. + */ + public static BlobContract create(String profile) { + return create(profile, Configuration.getInstance()); + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.blob.BlobContract} using the specified {@link Configuration} instance + * and profile prefix for service settings. The {@link Configuration} + * instance must have storage account information and credentials set with + * the specified profile prefix before this method is called for the + * returned interface to work. + * + * @param profile + * A string prefix for the account name and credentials settings + * in the {@link Configuration} instance. + * @param config + * A {@link Configuration} instance configured with storage + * account information and credentials. + * + * @return An instance implementing {@link com.microsoft.windowsazure.services.blob.BlobContract} for interacting + * with the blob service. + */ + public static BlobContract create(String profile, Configuration config) { + return config.create(profile, BlobContract.class); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/Exports.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/Exports.java new file mode 100644 index 0000000000000..7b43f1b3b1080 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/Exports.java @@ -0,0 +1,36 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.ISO8601DateConverter; +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.services.blob.implementation.BlobExceptionProcessor; +import com.microsoft.windowsazure.services.blob.implementation.BlobRestProxy; +import com.microsoft.windowsazure.services.blob.implementation.SharedKeyFilter; +import com.microsoft.windowsazure.services.blob.implementation.SharedKeyLiteFilter; + +public class Exports implements Builder.Exports { + @Override + public void register(Builder.Registry registry) { + registry.add(BlobContract.class, BlobExceptionProcessor.class); + registry.add(BlobExceptionProcessor.class); + registry.add(BlobRestProxy.class); + registry.add(SharedKeyLiteFilter.class); + registry.add(SharedKeyFilter.class); + registry.add(ISO8601DateConverter.class); + registry.add(UserAgentFilter.class); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobExceptionProcessor.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobExceptionProcessor.java new file mode 100644 index 0000000000000..66a82fbc9fcee --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobExceptionProcessor.java @@ -0,0 +1,343 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.implementation; + +import java.io.InputStream; + +import javax.inject.Inject; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import com.microsoft.windowsazure.services.blob.BlobContract; +import com.microsoft.windowsazure.services.blob.models.BlockList; +import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; +import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; +import com.microsoft.windowsazure.services.blob.models.DeleteBlobOptions; +import com.microsoft.windowsazure.services.blob.models.DeleteContainerOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; +import com.microsoft.windowsazure.services.blob.models.GetBlobResult; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; +import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; +import com.microsoft.windowsazure.services.blob.models.ListContainersResult; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class BlobExceptionProcessor implements BlobContract { + private static Log log = LogFactory.getLog(BlobExceptionProcessor.class); + private final BlobContract service; + + @Inject + public BlobExceptionProcessor(BlobRestProxy service) { + this.service = service; + } + + public BlobExceptionProcessor(BlobContract service) { + this.service = service; + } + + @Override + public BlobContract withFilter(ServiceFilter filter) { + return new BlobExceptionProcessor(service.withFilter(filter)); + } + + @Override + public BlobContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + return new BlobExceptionProcessor( + service.withRequestFilterFirst(serviceRequestFilter)); + } + + @Override + public BlobContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + return new BlobExceptionProcessor( + service.withRequestFilterLast(serviceRequestFilter)); + } + + @Override + public BlobContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + return new BlobExceptionProcessor( + service.withResponseFilterFirst(serviceResponseFilter)); + } + + @Override + public BlobContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + return new BlobExceptionProcessor( + service.withResponseFilterLast(serviceResponseFilter)); + } + + private ServiceException processCatch(ServiceException e) { + log.warn(e.getMessage(), e.getCause()); + return ServiceExceptionFactory.process("blob", e); + } + + @Override + public CreateBlobResult createBlockBlob(String container, String blob, + InputStream contentStream) throws ServiceException { + try { + return service.createBlockBlob(container, blob, contentStream); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public CreateBlobResult createBlockBlob(String container, String blob, + InputStream contentStream, CreateBlobOptions options) + throws ServiceException { + try { + return service.createBlockBlob(container, blob, contentStream, + options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void createBlobBlock(String container, String blob, String blockId, + InputStream contentStream) throws ServiceException { + try { + service.createBlobBlock(container, blob, blockId, contentStream); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void createBlobBlock(String container, String blob, String blockId, + InputStream contentStream, CreateBlobBlockOptions options) + throws ServiceException { + try { + service.createBlobBlock(container, blob, blockId, contentStream, + options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void commitBlobBlocks(String container, String blob, + BlockList blockList) throws ServiceException { + try { + service.commitBlobBlocks(container, blob, blockList); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void commitBlobBlocks(String container, String blob, + BlockList blockList, CommitBlobBlocksOptions options) + throws ServiceException { + try { + service.commitBlobBlocks(container, blob, blockList, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteBlob(String container, String blob) + throws ServiceException { + try { + service.deleteBlob(container, blob); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteBlob(String container, String blob, + DeleteBlobOptions options) throws ServiceException { + try { + service.deleteBlob(container, blob, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListContainersResult listContainers() throws ServiceException { + try { + return service.listContainers(); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListContainersResult listContainers(ListContainersOptions options) + throws ServiceException { + try { + return service.listContainers(options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void createContainer(String container) throws ServiceException { + try { + service.createContainer(container); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void createContainer(String container, CreateContainerOptions options) + throws ServiceException { + try { + service.createContainer(container, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteContainer(String container) throws ServiceException { + try { + service.deleteContainer(container); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteContainer(String container, DeleteContainerOptions options) + throws ServiceException { + try { + service.deleteContainer(container, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListBlobBlocksResult listBlobBlocks(String container, String blob) + throws ServiceException { + try { + return service.listBlobBlocks(container, blob); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListBlobBlocksResult listBlobBlocks(String container, String blob, + ListBlobBlocksOptions options) throws ServiceException { + try { + return service.listBlobBlocks(container, blob, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetBlobPropertiesResult getBlobProperties(String container, + String blob) throws ServiceException { + try { + return service.getBlobProperties(container, blob); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetBlobPropertiesResult getBlobProperties(String container, + String blob, GetBlobPropertiesOptions options) + throws ServiceException { + try { + return service.getBlobProperties(container, blob, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetBlobResult getBlob(String container, String blob) + throws ServiceException { + try { + return service.getBlob(container, blob); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetBlobResult getBlob(String container, String blob, + GetBlobOptions options) throws ServiceException { + try { + return service.getBlob(container, blob, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobOperationRestProxy.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobOperationRestProxy.java new file mode 100644 index 0000000000000..5061c62ad5975 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobOperationRestProxy.java @@ -0,0 +1,578 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.blob.implementation; + +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import com.microsoft.windowsazure.core.RFC1123DateConverter; +import com.microsoft.windowsazure.core.pipeline.PipelineHelpers; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; +import com.microsoft.windowsazure.core.utils.CommaStringBuilder; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.blob.BlobContract; +import com.microsoft.windowsazure.services.blob.models.BlobProperties; +import com.microsoft.windowsazure.services.blob.models.BlobServiceOptions; +import com.microsoft.windowsazure.services.blob.models.BlockList; +import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; +import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; +import com.microsoft.windowsazure.services.blob.models.DeleteBlobOptions; +import com.microsoft.windowsazure.services.blob.models.DeleteContainerOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; +import com.microsoft.windowsazure.services.blob.models.GetBlobResult; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; +import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; +import com.microsoft.windowsazure.services.blob.models.ListContainersResult; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; +import com.sun.jersey.api.client.filter.ClientFilter; +import com.sun.jersey.core.util.Base64; + +public abstract class BlobOperationRestProxy implements BlobContract { + + private static final String API_VERSION = "2011-08-18"; + private final Client channel; + private final String accountName; + private final String url; + private final RFC1123DateConverter dateMapper; + private final ClientFilter[] filters; + + protected BlobOperationRestProxy(Client channel, String accountName, + String url) { + this(channel, new ClientFilter[0], accountName, url, + new RFC1123DateConverter()); + } + + protected BlobOperationRestProxy(Client channel, ClientFilter[] filters, + String accountName, String url, RFC1123DateConverter dateMapper) { + this.channel = channel; + this.accountName = accountName; + this.url = url; + this.filters = filters; + this.dateMapper = dateMapper; + } + + @Override + public abstract BlobContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter); + + @Override + public abstract BlobContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter); + + @Override + public abstract BlobContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter); + + @Override + public abstract BlobContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter); + + protected Client getChannel() { + return channel; + } + + protected String getAccountName() { + return accountName; + } + + protected String getUrl() { + return url; + } + + protected RFC1123DateConverter getDateMapper() { + return dateMapper; + } + + protected ClientFilter[] getFilters() { + return filters; + } + + private void throwIfError(ClientResponse r) { + PipelineHelpers.throwIfError(r); + } + + private void throwIfNotSuccess(ClientResponse clientResponse) { + PipelineHelpers.throwIfNotSuccess(clientResponse); + } + + private WebResource addOptionalQueryParam(WebResource webResource, + String key, Object value) { + return PipelineHelpers.addOptionalQueryParam(webResource, key, value); + } + + private Builder addOptionalRangeHeader(Builder builder, Long rangeStart, + Long rangeEnd) { + return PipelineHelpers.addOptionalRangeHeader(builder, rangeStart, + rangeEnd); + } + + private WebResource addOptionalQueryParam(WebResource webResource, + String key, int value, int defaultValue) { + return PipelineHelpers.addOptionalQueryParam(webResource, key, value, + defaultValue); + } + + private WebResource addOptionalContainerIncludeQueryParam( + ListContainersOptions options, WebResource webResource) { + CommaStringBuilder sb = new CommaStringBuilder(); + sb.addValue(options.isIncludeMetadata(), "metadata"); + webResource = addOptionalQueryParam(webResource, "include", + sb.toString()); + return webResource; + } + + private Builder addOptionalHeader(Builder builder, String name, Object value) { + return PipelineHelpers.addOptionalHeader(builder, name, value); + } + + private Builder addOptionalMetadataHeader(Builder builder, + Map metadata) { + return PipelineHelpers.addOptionalMetadataHeader(builder, metadata); + } + + private Builder addOptionalAccessConditionHeader(Builder builder, + AccessConditionHeader accessCondition) { + return PipelineHelpers.addOptionalAccessConditionHeader(builder, + accessCondition); + } + + private Builder addPutBlobHeaders(CreateBlobOptions options, Builder builder) { + builder = addOptionalHeader(builder, "Content-Type", + options.getContentType()); + if (options.getContentType() == null) { + // Note: Add content type here to enable proper HMAC signing + builder = builder.type("application/octet-stream"); + } + builder = addOptionalHeader(builder, "Content-Encoding", + options.getContentEncoding()); + builder = addOptionalHeader(builder, "Content-Language", + options.getContentLanguage()); + builder = addOptionalHeader(builder, "Content-MD5", + options.getContentMD5()); + builder = addOptionalHeader(builder, "Cache-Control", + options.getCacheControl()); + builder = addOptionalHeader(builder, "x-ms-blob-content-type", + options.getBlobContentType()); + builder = addOptionalHeader(builder, "x-ms-blob-content-encoding", + options.getBlobContentEncoding()); + builder = addOptionalHeader(builder, "x-ms-blob-content-language", + options.getBlobContentLanguage()); + builder = addOptionalHeader(builder, "x-ms-blob-content-md5", + options.getBlobContentMD5()); + builder = addOptionalHeader(builder, "x-ms-blob-cache-control", + options.getBlobCacheControl()); + builder = addOptionalHeader(builder, "x-ms-lease-id", + options.getLeaseId()); + builder = addOptionalMetadataHeader(builder, options.getMetadata()); + builder = addOptionalAccessConditionHeader(builder, + options.getAccessCondition()); + + return builder; + } + + private WebResource getResource(BlobServiceOptions options) { + WebResource webResource = channel.resource(url).path("/"); + webResource = addOptionalQueryParam(webResource, "timeout", + options.getTimeout()); + for (ClientFilter filter : filters) { + webResource.addFilter(filter); + } + + return webResource; + } + + @Override + public void createContainer(String container) throws ServiceException { + createContainer(container, new CreateContainerOptions()); + } + + @Override + public void createContainer(String container, CreateContainerOptions options) + throws ServiceException { + if (container == null || container.isEmpty()) { + throw new IllegalArgumentException( + "The container cannot be null or empty."); + } + WebResource webResource = getResource(options).path(container) + .queryParam("resType", "container"); + + WebResource.Builder builder = webResource.header("x-ms-version", + API_VERSION); + builder = addOptionalMetadataHeader(builder, options.getMetadata()); + builder = addOptionalHeader(builder, "x-ms-blob-public-access", + options.getPublicAccess()); + + builder.put(); + } + + @Override + public void deleteContainer(String container) throws ServiceException { + deleteContainer(container, new DeleteContainerOptions()); + } + + @Override + public void deleteContainer(String container, DeleteContainerOptions options) + throws ServiceException { + if ((container == null) || (container.isEmpty())) { + throw new IllegalArgumentException( + "The root container has already been created."); + } + WebResource webResource = getResource(options).path(container) + .queryParam("resType", "container"); + + WebResource.Builder builder = webResource.header("x-ms-version", + API_VERSION); + builder = addOptionalAccessConditionHeader(builder, + options.getAccessCondition()); + + builder.delete(); + } + + @Override + public void deleteBlob(String container, String blob) + throws ServiceException { + deleteBlob(container, blob, new DeleteBlobOptions()); + } + + @Override + public void deleteBlob(String container, String blob, + DeleteBlobOptions options) throws ServiceException { + String path = createPathFromContainer(container); + WebResource webResource = getResource(options).path(path).path(blob); + webResource = addOptionalQueryParam(webResource, "snapshot", + options.getSnapshot()); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + builder = addOptionalHeader(builder, "x-ms-lease-id", + options.getLeaseId()); + if (options.getDeleteSnaphotsOnly() != null) { + builder = addOptionalHeader(builder, "x-ms-delete-snapshots", + options.getDeleteSnaphotsOnly() ? "only" : "include"); + } + builder = addOptionalAccessConditionHeader(builder, + options.getAccessCondition()); + + builder.delete(); + } + + @Override + public ListContainersResult listContainers() throws ServiceException { + return listContainers(new ListContainersOptions()); + } + + @Override + public ListContainersResult listContainers(ListContainersOptions options) + throws ServiceException { + WebResource webResource = getResource(options).path("/").queryParam( + "comp", "list"); + webResource = addOptionalQueryParam(webResource, "prefix", + options.getPrefix()); + webResource = addOptionalQueryParam(webResource, "marker", + options.getMarker()); + webResource = addOptionalQueryParam(webResource, "maxresults", + options.getMaxResults(), 0); + webResource = addOptionalContainerIncludeQueryParam(options, + webResource); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + return builder.get(ListContainersResult.class); + } + + @Override + public CreateBlobResult createBlockBlob(String container, String blob, + InputStream contentStream) throws ServiceException { + return createBlockBlob(container, blob, contentStream, + new CreateBlobOptions()); + } + + @Override + public CreateBlobResult createBlockBlob(String container, String blob, + InputStream contentStream, CreateBlobOptions options) + throws ServiceException { + String path = createPathFromContainer(container); + WebResource webResource = getResource(options).path(path).path(blob); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + builder = builder.header("x-ms-blob-type", "BlockBlob"); + builder = addPutBlobHeaders(options, builder); + + Object contentObject = (contentStream == null ? new byte[0] + : contentStream); + ClientResponse clientResponse = builder.put(ClientResponse.class, + contentObject); + throwIfError(clientResponse); + + CreateBlobResult createBlobResult = new CreateBlobResult(); + createBlobResult.setEtag(clientResponse.getHeaders().getFirst("ETag")); + createBlobResult.setLastModified(dateMapper.parse(clientResponse + .getHeaders().getFirst("Last-Modified"))); + + return createBlobResult; + } + + @Override + public void createBlobBlock(String container, String blob, String blockId, + InputStream contentStream) throws ServiceException { + createBlobBlock(container, blob, blockId, contentStream, + new CreateBlobBlockOptions()); + } + + @Override + public void createBlobBlock(String container, String blob, String blockId, + InputStream contentStream, CreateBlobBlockOptions options) + throws ServiceException { + String path = createPathFromContainer(container); + WebResource webResource = getResource(options).path(path).path(blob) + .queryParam("comp", "block"); + try { + webResource = addOptionalQueryParam(webResource, "blockid", + new String(Base64.encode(blockId), "UTF-8")); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + + Builder builder = webResource.header("x-ms-version", API_VERSION); + builder = addOptionalHeader(builder, "x-ms-lease-id", + options.getLeaseId()); + builder = addOptionalHeader(builder, "Content-MD5", + options.getContentMD5()); + + builder.put(contentStream); + } + + @Override + public void commitBlobBlocks(String container, String blob, + BlockList blockList) throws ServiceException { + commitBlobBlocks(container, blob, blockList, + new CommitBlobBlocksOptions()); + } + + @Override + public void commitBlobBlocks(String container, String blob, + BlockList blockList, CommitBlobBlocksOptions options) + throws ServiceException { + String path = createPathFromContainer(container); + WebResource webResource = getResource(options).path(path).path(blob) + .queryParam("comp", "blocklist"); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + builder = addOptionalHeader(builder, "x-ms-lease-id", + options.getLeaseId()); + builder = addOptionalHeader(builder, "x-ms-blob-cache-control", + options.getBlobCacheControl()); + builder = addOptionalHeader(builder, "x-ms-blob-content-type", + options.getBlobContentType()); + builder = addOptionalHeader(builder, "x-ms-blob-content-encoding", + options.getBlobContentEncoding()); + builder = addOptionalHeader(builder, "x-ms-blob-content-language", + options.getBlobContentLanguage()); + builder = addOptionalHeader(builder, "x-ms-blob-content-md5", + options.getBlobContentMD5()); + builder = addOptionalMetadataHeader(builder, options.getMetadata()); + builder = addOptionalAccessConditionHeader(builder, + options.getAccessCondition()); + + builder.put(blockList); + } + + @Override + public GetBlobPropertiesResult getBlobProperties(String container, + String blob) throws ServiceException { + return getBlobProperties(container, blob, + new GetBlobPropertiesOptions()); + } + + @Override + public GetBlobPropertiesResult getBlobProperties(String container, + String blob, GetBlobPropertiesOptions options) + throws ServiceException { + String path = createPathFromContainer(container); + WebResource webResource = getResource(options).path(path).path(blob); + webResource = addOptionalQueryParam(webResource, "snapshot", + options.getSnapshot()); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + builder = addOptionalHeader(builder, "x-ms-lease-id", + options.getLeaseId()); + builder = addOptionalAccessConditionHeader(builder, + options.getAccessCondition()); + + ClientResponse response = builder.method("HEAD", ClientResponse.class); + throwIfNotSuccess(response); + + return getBlobPropertiesResultFromResponse(response); + } + + @Override + public GetBlobResult getBlob(String container, String blob) + throws ServiceException { + return getBlob(container, blob, new GetBlobOptions()); + } + + @Override + public GetBlobResult getBlob(String container, String blob, + GetBlobOptions options) throws ServiceException { + String path = createPathFromContainer(container); + WebResource webResource = getResource(options).path(path).path(blob); + webResource = addOptionalQueryParam(webResource, "snapshot", + options.getSnapshot()); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + builder = addOptionalHeader(builder, "x-ms-lease-id", + options.getLeaseId()); + builder = addOptionalRangeHeader(builder, options.getRangeStart(), + options.getRangeEnd()); + builder = addOptionalAccessConditionHeader(builder, + options.getAccessCondition()); + if (options.isComputeRangeMD5()) { + builder = addOptionalHeader(builder, "x-ms-range-get-content-md5", + "true"); + } + + ClientResponse response = builder.get(ClientResponse.class); + throwIfNotSuccess(response); + + GetBlobPropertiesResult properties = getBlobPropertiesResultFromResponse(response); + GetBlobResult blobResult = new GetBlobResult(); + blobResult.setProperties(properties.getProperties()); + blobResult.setMetadata(properties.getMetadata()); + blobResult.setContentStream(response.getEntityInputStream()); + return blobResult; + } + + private GetBlobPropertiesResult getBlobPropertiesResultFromResponse( + ClientResponse response) { + // Properties + BlobProperties properties = new BlobProperties(); + properties.setLastModified(dateMapper.parse(response.getHeaders() + .getFirst("Last-Modified"))); + properties + .setBlobType(response.getHeaders().getFirst("x-ms-blob-type")); + properties.setLeaseStatus(response.getHeaders().getFirst( + "x-ms-lease-status")); + + properties.setContentLength(Long.parseLong(response.getHeaders() + .getFirst("Content-Length"))); + properties.setContentType(response.getHeaders() + .getFirst("Content-Type")); + properties.setContentMD5(response.getHeaders().getFirst("Content-MD5")); + properties.setContentEncoding(response.getHeaders().getFirst( + "Content-Encoding")); + properties.setContentLanguage(response.getHeaders().getFirst( + "Content-Language")); + properties.setCacheControl(response.getHeaders().getFirst( + "Cache-Control")); + + properties.setEtag(response.getHeaders().getFirst("Etag")); + if (response.getHeaders().containsKey("x-ms-blob-sequence-number")) { + properties.setSequenceNumber(Long.parseLong(response.getHeaders() + .getFirst("x-ms-blob-sequence-number"))); + } + + // Metadata + HashMap metadata = getMetadataFromHeaders(response); + + // Result + GetBlobPropertiesResult result = new GetBlobPropertiesResult(); + result.setMetadata(metadata); + result.setProperties(properties); + return result; + } + + @Override + public ListBlobBlocksResult listBlobBlocks(String container, String blob) + throws ServiceException { + return listBlobBlocks(container, blob, new ListBlobBlocksOptions()); + } + + @Override + public ListBlobBlocksResult listBlobBlocks(String container, String blob, + ListBlobBlocksOptions options) throws ServiceException { + String path = createPathFromContainer(container); + WebResource webResource = getResource(options).path(path).path(blob) + .queryParam("comp", "blocklist"); + webResource = addOptionalQueryParam(webResource, "snapshot", + options.getSnapshot()); + if (options.isCommittedList() && options.isUncommittedList()) { + webResource = addOptionalQueryParam(webResource, "blocklisttype", + "all"); + } else if (options.isCommittedList()) { + webResource = addOptionalQueryParam(webResource, "blocklisttype", + "committed"); + } else if (options.isUncommittedList()) { + webResource = addOptionalQueryParam(webResource, "blocklisttype", + "uncommitted"); + } + + Builder builder = webResource.header("x-ms-version", API_VERSION); + builder = addOptionalHeader(builder, "x-ms-lease-id", + options.getLeaseId()); + + ClientResponse response = builder.get(ClientResponse.class); + throwIfError(response); + + ListBlobBlocksResult result = response + .getEntity(ListBlobBlocksResult.class); + result.setEtag(response.getHeaders().getFirst("ETag")); + result.setContentType(response.getHeaders().getFirst("Content-Type")); + + String blobContentLength = response.getHeaders().getFirst( + "x-ms-blob-content-length"); + if (blobContentLength != null) { + result.setContentLength(Long.parseLong(blobContentLength)); + } else { + result.setContentLength(0); + } + + String lastModified = response.getHeaders().getFirst("Last-Modified"); + if (lastModified != null) { + result.setLastModified(dateMapper.parse(lastModified)); + } + + return result; + } + + private HashMap getMetadataFromHeaders( + ClientResponse response) { + return PipelineHelpers.getMetadataFromHeaders(response); + } + + private String createPathFromContainer(String containerName) { + String path; + if (containerName == null || containerName.isEmpty()) { + path = "$root"; + } else { + path = containerName; + } + return path; + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobRestProxy.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobRestProxy.java new file mode 100644 index 0000000000000..f2d95c1bc6084 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobRestProxy.java @@ -0,0 +1,119 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.implementation; + +import java.util.Arrays; + +import javax.inject.Inject; +import javax.inject.Named; + +import com.microsoft.windowsazure.core.RFC1123DateConverter; +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterRequestAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterResponseAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.HttpURLConnectionClient; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.services.blob.BlobConfiguration; +import com.microsoft.windowsazure.services.blob.BlobContract; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class BlobRestProxy extends BlobOperationRestProxy implements + BlobContract { + private final SharedKeyFilter sharedKeyFilter; + + @Inject + public BlobRestProxy(HttpURLConnectionClient channel, + @Named(BlobConfiguration.ACCOUNT_NAME) String accountName, + @Named(BlobConfiguration.URI) String url, + SharedKeyFilter sharedKeyFilter, UserAgentFilter userAgentFilter) { + super(channel, accountName, url); + + this.sharedKeyFilter = sharedKeyFilter; + + channel.addFilter(sharedKeyFilter); + channel.addFilter(new ClientFilterRequestAdapter(userAgentFilter)); + } + + public BlobRestProxy(Client client, ClientFilter[] filters, + String accountName, String url, SharedKeyFilter sharedKeyFilter, + RFC1123DateConverter dateMapper) { + super(client, filters, accountName, url, dateMapper); + + this.sharedKeyFilter = sharedKeyFilter; + } + + @Override + public BlobContract withFilter(ServiceFilter filter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterAdapter(filter); + return new BlobRestProxy(getChannel(), newFilters, getAccountName(), + getUrl(), this.sharedKeyFilter, getDateMapper()); + } + + @Override + public BlobContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterRequestAdapter(serviceRequestFilter); + return new BlobRestProxy(getChannel(), newFilters, getAccountName(), + getUrl(), this.sharedKeyFilter, getDateMapper()); + } + + @Override + public BlobContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterRequestAdapter( + serviceRequestFilter); + return new BlobRestProxy(getChannel(), newFilters, getAccountName(), + getUrl(), this.sharedKeyFilter, getDateMapper()); + } + + @Override + public BlobContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterResponseAdapter(serviceResponseFilter); + return new BlobRestProxy(getChannel(), newFilters, getAccountName(), + getUrl(), this.sharedKeyFilter, getDateMapper()); + } + + @Override + public BlobContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterResponseAdapter( + serviceResponseFilter); + return new BlobRestProxy(getChannel(), newFilters, getAccountName(), + getUrl(), this.sharedKeyFilter, getDateMapper()); + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/ContainerACLDateAdapter.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/ContainerACLDateAdapter.java similarity index 94% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/ContainerACLDateAdapter.java rename to media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/ContainerACLDateAdapter.java index 5697162a06ab6..afd028fae9115 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/ContainerACLDateAdapter.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/ContainerACLDateAdapter.java @@ -18,7 +18,7 @@ import javax.xml.bind.annotation.adapters.XmlAdapter; -import com.microsoft.windowsazure.services.core.ISO8601DateConverter; +import com.microsoft.windowsazure.core.ISO8601DateConverter; /* * JAXB adapter for a "not quite" ISO 8601 date time element diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/HmacSHA256Sign.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/HmacSHA256Sign.java similarity index 97% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/HmacSHA256Sign.java rename to media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/HmacSHA256Sign.java index e40607c675220..6e66eec8117b6 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/HmacSHA256Sign.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/HmacSHA256Sign.java @@ -35,8 +35,7 @@ public String sign(String stringToSign) { hmac.init(new SecretKeySpec(Base64.decode(accessKey), "hmacSHA256")); byte[] digest = hmac.doFinal(stringToSign.getBytes("UTF-8")); return new String(Base64.encode(digest), "UTF-8"); - } - catch (Exception e) { + } catch (Exception e) { throw new IllegalArgumentException("accessKey", e); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/MetadataAdapter.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/MetadataAdapter.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/MetadataAdapter.java rename to media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/MetadataAdapter.java index b174cf5f5f493..c671d47cbbe85 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/MetadataAdapter.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/MetadataAdapter.java @@ -27,19 +27,24 @@ /* * JAXB adapter for element */ -public class MetadataAdapter extends XmlAdapter> { +public class MetadataAdapter + extends + XmlAdapter> { @Override - public HashMap unmarshal(MetadataHashMapType arg0) throws Exception { + public HashMap unmarshal(MetadataHashMapType arg0) + throws Exception { HashMap result = new HashMap(); for (Element entry : arg0.getEntries()) { - result.put(entry.getLocalName(), entry.getFirstChild().getNodeValue()); + result.put(entry.getLocalName(), entry.getFirstChild() + .getNodeValue()); } return result; } @Override - public MetadataHashMapType marshal(HashMap arg0) throws Exception { + public MetadataHashMapType marshal(HashMap arg0) + throws Exception { // We don't need marshaling for blob/container metadata throw new OperationNotSupportedException(); } diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyFilter.java new file mode 100644 index 0000000000000..7d8f736078768 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyFilter.java @@ -0,0 +1,241 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.implementation; + +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import javax.inject.Named; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.microsoft.windowsazure.core.RFC1123DateConverter; +import com.microsoft.windowsazure.core.pipeline.jersey.EntityStreamingListener; +import com.microsoft.windowsazure.services.blob.BlobConfiguration; +import com.microsoft.windowsazure.services.blob.implementation.SharedKeyUtils.QueryParam; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class SharedKeyFilter extends ClientFilter implements + EntityStreamingListener { + private static Log log = LogFactory.getLog(SharedKeyFilter.class); + + private final String accountName; + private final HmacSHA256Sign signer; + + public SharedKeyFilter( + @Named(BlobConfiguration.ACCOUNT_NAME) String accountName, + @Named(BlobConfiguration.ACCOUNT_KEY) String accountKey) { + this.accountName = accountName; + this.signer = new HmacSHA256Sign(accountKey); + } + + protected String getHeader(ClientRequest cr, String headerKey) { + return SharedKeyUtils.getHeader(cr, headerKey); + } + + protected HmacSHA256Sign getSigner() { + return signer; + } + + protected String getAccountName() { + return accountName; + } + + @Override + public ClientResponse handle(ClientRequest cr) { + // Only sign if no other filter is handling authorization + if (cr.getProperties().get(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER) == null) { + cr.getProperties().put(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER, + null); + + // Register ourselves as listener so we are called back when the + // entity is + // written to the output stream by the next filter in line. + if (cr.getProperties().get(EntityStreamingListener.class.getName()) == null) { + cr.getProperties().put(EntityStreamingListener.class.getName(), + this); + } + + } + return this.getNext().handle(cr); + } + + @Override + public void onBeforeStreamingEntity(ClientRequest clientRequest) { + // All headers should be known at this point, time to sign! + sign(clientRequest); + } + + /* + * StringToSign = VERB + "\n" + Content-Encoding + "\n" Content-Language + + * "\n" Content-Length + "\n" Content-MD5 + "\n" + Content-Type + "\n" + + * Date + "\n" + If-Modified-Since + "\n" If-Match + "\n" If-None-Match + + * "\n" If-Unmodified-Since + "\n" Range + "\n" CanonicalizedHeaders + + * CanonicalizedResource; + */ + public void sign(ClientRequest cr) { + // gather signed material + addOptionalDateHeader(cr); + + // build signed string + String stringToSign = cr.getMethod() + "\n" + + getHeader(cr, "Content-Encoding") + "\n" + + getHeader(cr, "Content-Language") + "\n" + + getHeader(cr, "Content-Length") + "\n" + + getHeader(cr, "Content-MD5") + "\n" + + getHeader(cr, "Content-Type") + "\n" + getHeader(cr, "Date") + + "\n" + getHeader(cr, "If-Modified-Since") + "\n" + + getHeader(cr, "If-Match") + "\n" + + getHeader(cr, "If-None-Match") + "\n" + + getHeader(cr, "If-Unmodified-Since") + "\n" + + getHeader(cr, "Range") + "\n"; + + stringToSign += getCanonicalizedHeaders(cr); + stringToSign += getCanonicalizedResource(cr); + + if (log.isDebugEnabled()) { + log.debug(String.format("String to sign: \"%s\"", stringToSign)); + } + // System.out.println(String.format("String to sign: \"%s\"", + // stringToSign)); + + String signature = this.signer.sign(stringToSign); + cr.getHeaders().putSingle("Authorization", + "SharedKey " + this.accountName + ":" + signature); + } + + protected void addOptionalDateHeader(ClientRequest cr) { + String date = getHeader(cr, "Date"); + if (date == "") { + date = new RFC1123DateConverter().format(new Date()); + cr.getHeaders().putSingle("Date", date); + } + } + + /** + * Constructing the Canonicalized Headers String + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: + * + * 1. Retrieve all headers for the resource that begin with x-ms-, including + * the x-ms-date header. + * + * 2. Convert each HTTP header name to lowercase. + * + * 3. Sort the headers lexicographically by header name, in ascending order. + * Note that each header may appear only once in the string. + * + * 4. Unfold the string by replacing any breaking white space with a single + * space. + * + * 5. Trim any white space around the colon in the header. + * + * 6. Finally, append a new line character to each canonicalized header in + * the resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + private String getCanonicalizedHeaders(ClientRequest cr) { + return SharedKeyUtils.getCanonicalizedHeaders(cr); + } + + /** + * This format supports Shared Key authentication for the 2009-09-19 version + * of the Blob and Queue services. Construct the CanonicalizedResource + * string in this format as follows: + * + * 1. Beginning with an empty string (""), append a forward slash (/), + * followed by the name of the account that owns the resource being + * accessed. + * + * 2. Append the resource's encoded URI path, without any query parameters. + * + * 3. Retrieve all query parameters on the resource URI, including the comp + * parameter if it exists. + * + * 4. Convert all parameter names to lowercase. + * + * 5. Sort the query parameters lexicographically by parameter name, in + * ascending order. + * + * 6. URL-decode each query parameter name and value. + * + * 7. Append each query parameter name and value to the string in the + * following format, making sure to include the colon (:) between the name + * and the value: + * + * parameter-name:parameter-value + * + * 8. If a query parameter has more than one value, sort all values + * lexicographically, then include them in a comma-separated list: + * + * parameter-name:parameter-value-1,parameter-value-2,parameter-value-n + * + * 9. Append a new line character (\n) after each name-value pair. + */ + private String getCanonicalizedResource(ClientRequest cr) { + // 1. Beginning with an empty string (""), append a forward slash (/), + // followed by the name of the account that owns + // the resource being accessed. + String result = "/" + this.accountName; + + // 2. Append the resource's encoded URI path, without any query + // parameters. + result += cr.getURI().getPath(); + + // 3. Retrieve all query parameters on the resource URI, including the + // comp parameter if it exists. + // 6. URL-decode each query parameter name and value. + List queryParams = SharedKeyUtils.getQueryParams(cr + .getURI().getQuery()); + + // 4. Convert all parameter names to lowercase. + for (QueryParam param : queryParams) { + param.setName(param.getName().toLowerCase(Locale.US)); + } + + // 5. Sort the query parameters lexicographically by parameter name, in + // ascending order. + Collections.sort(queryParams); + + // 7. Append each query parameter name and value to the string + // 8. If a query parameter has more than one value, sort all values + // lexicographically, then include them in a comma-separated list + for (int i = 0; i < queryParams.size(); i++) { + QueryParam param = queryParams.get(i); + + List values = param.getValues(); + // Collections.sort(values); + + // 9. Append a new line character (\n) after each name-value pair. + result += "\n"; + result += param.getName(); + result += ":"; + for (int j = 0; j < values.size(); j++) { + if (j > 0) { + result += ","; + } + result += values.get(j); + } + } + + return result; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyLiteFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyLiteFilter.java new file mode 100644 index 0000000000000..45fe7b3d0e005 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyLiteFilter.java @@ -0,0 +1,167 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.implementation; + +import java.util.Date; +import java.util.List; + +import javax.inject.Named; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.microsoft.windowsazure.core.RFC1123DateConverter; +import com.microsoft.windowsazure.core.pipeline.jersey.EntityStreamingListener; +import com.microsoft.windowsazure.services.blob.BlobConfiguration; +import com.microsoft.windowsazure.services.blob.implementation.SharedKeyUtils.QueryParam; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class SharedKeyLiteFilter extends ClientFilter implements + EntityStreamingListener { + private static Log log = LogFactory.getLog(SharedKeyLiteFilter.class); + + private final String accountName; + private final HmacSHA256Sign signer; + + public SharedKeyLiteFilter( + @Named(BlobConfiguration.ACCOUNT_NAME) String accountName, + @Named(BlobConfiguration.ACCOUNT_KEY) String accountKey) { + + this.accountName = accountName; + this.signer = new HmacSHA256Sign(accountKey); + } + + @Override + public ClientResponse handle(ClientRequest cr) { + // Only sign if no other filter is handling authorization + if (cr.getProperties().get(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER) == null) { + cr.getProperties().put(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER, + null); + + // Register ourselves as listener so we are called back when the + // entity is + // written to the output stream by the next filter in line. + if (cr.getProperties().get(EntityStreamingListener.class.getName()) == null) { + cr.getProperties().put(EntityStreamingListener.class.getName(), + this); + } + } + + return this.getNext().handle(cr); + } + + @Override + public void onBeforeStreamingEntity(ClientRequest clientRequest) { + // All headers should be known at this point, time to sign! + sign(clientRequest); + } + + /* + * StringToSign = VERB + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + + * Date + "\n" + CanonicalizedHeaders + CanonicalizedResource; + */ + public void sign(ClientRequest cr) { + // gather signed material + String requestMethod = cr.getMethod(); + String contentMD5 = getHeader(cr, "Content-MD5"); + String contentType = getHeader(cr, "Content-Type"); + String date = getHeader(cr, "Date"); + + if (date == "") { + date = new RFC1123DateConverter().format(new Date()); + cr.getHeaders().add("Date", date); + } + + // build signed string + String stringToSign = requestMethod + "\n" + contentMD5 + "\n" + + contentType + "\n" + date + "\n"; + + stringToSign += addCanonicalizedHeaders(cr); + stringToSign += addCanonicalizedResource(cr); + + if (log.isDebugEnabled()) { + log.debug(String.format("String to sign: \"%s\"", stringToSign)); + } + + String signature = this.signer.sign(stringToSign); + cr.getHeaders().putSingle("Authorization", + "SharedKeyLite " + this.accountName + ":" + signature); + } + + /** + * Constructing the Canonicalized Headers String + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: + * + * 1. Retrieve all headers for the resource that begin with x-ms-, including + * the x-ms-date header. + * + * 2. Convert each HTTP header name to lowercase. + * + * 3. Sort the headers lexicographically by header name in ascending order. + * Note that each header may appear only once in the string. + * + * 4. Unfold the string by replacing any breaking white space with a single + * space. + * + * 5. Trim any white space around the colon in the header. + * + * 6. Finally, append a new line character to each canonicalized header in + * the resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + private String addCanonicalizedHeaders(ClientRequest cr) { + return SharedKeyUtils.getCanonicalizedHeaders(cr); + } + + /** + * This format supports Shared Key and Shared Key Lite for all versions of + * the Table service, and Shared Key Lite for the 2009-09-19 version of the + * Blob and Queue services. This format is identical to that used with + * previous versions of the storage services. Construct the + * CanonicalizedResource string in this format as follows: + * + * 1. Beginning with an empty string (""), append a forward slash (/), + * followed by the name of the account that owns the resource being + * accessed. + * + * 2. Append the resource's encoded URI path. If the request URI addresses a + * component of the resource, append the appropriate query string. The query + * string should include the question mark and the comp parameter (for + * example, ?comp=metadata). No other parameters should be included on the + * query string. + */ + private String addCanonicalizedResource(ClientRequest cr) { + String result = "/" + this.accountName; + + result += cr.getURI().getPath(); + + List queryParams = SharedKeyUtils.getQueryParams(cr + .getURI().getQuery()); + for (QueryParam p : queryParams) { + if ("comp".equals(p.getName())) { + result += "?" + p.getName() + "=" + p.getValues().get(0); + } + } + return result; + } + + private String getHeader(ClientRequest cr, String headerKey) { + return SharedKeyUtils.getHeader(cr, headerKey); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyUtils.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyUtils.java similarity index 96% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyUtils.java rename to media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyUtils.java index f54dcc1707422..9cdfb9e6087dd 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyUtils.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyUtils.java @@ -21,12 +21,13 @@ import com.sun.jersey.api.client.ClientRequest; -public class SharedKeyUtils { - public static final String AUTHORIZATION_FILTER_MARKER = SharedKeyUtils.class.getName(); +public abstract class SharedKeyUtils { + public static final String AUTHORIZATION_FILTER_MARKER = SharedKeyUtils.class + .getName(); /* * Constructing the Canonicalized Headers String - * + * * To construct the CanonicalizedHeaders portion of the signature string, * follow these steps: 1. Retrieve all headers for the resource that begin * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header @@ -49,7 +50,8 @@ public static String getCanonicalizedHeaders(ClientRequest cr) { String result = ""; for (String msHeader : msHeaders) { - result += msHeader + ":" + cr.getHeaders().getFirst(msHeader) + "\n"; + result += msHeader + ":" + cr.getHeaders().getFirst(msHeader) + + "\n"; } return result; } @@ -86,16 +88,14 @@ private static QueryParam getQueryParam(String param) { int index = param.indexOf("="); if (index < 0) { result.setName(param); - } - else { + } else { result.setName(param.substring(0, index)); String value = param.substring(index + 1); int commaIndex = value.indexOf(','); if (commaIndex < 0) { result.addValue(value); - } - else { + } else { for (String v : value.split(",")) { result.addValue(v); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/package.html b/media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/blob/implementation/package.html diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessCondition.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessCondition.java new file mode 100644 index 0000000000000..3594c82eaf68c --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessCondition.java @@ -0,0 +1,446 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.net.HttpURLConnection; +import java.util.Date; + +import com.microsoft.windowsazure.core.utils.Utility; + +/** + * Represents a set of access conditions to be used for operations against the + * storage services. + */ +public final class AccessCondition { + /** + * Generates a new empty AccessCondition. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @return An AccessCondition object that has no conditions + * set. + */ + public static AccessCondition generateEmptyCondition() { + return new AccessCondition(); + } + + /** + * Returns an access condition such that an operation will be performed only + * if the resource's ETag value matches the specified ETag value. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-Match conditional header. If this access condition is set, the + * operation is performed only if the ETag of the resource matches the + * specified ETag. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param etag + * A String that represents the ETag value to check. + * + * @return An AccessCondition object that represents the + * If-Match condition. + */ + public static AccessCondition generateIfMatchCondition(final String etag) { + AccessCondition retCondition = new AccessCondition(); + retCondition.setIfMatch(etag); + return retCondition; + } + + /** + * Returns an access condition such that an operation will be performed only + * if the resource has been modified since the specified time. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-Modified-Since conditional header. If this access condition is + * set, the operation is performed only if the resource has been modified + * since the specified time. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param lastMotified + * A java.util.Date object that represents the + * last-modified time to check for the resource. + * + * @return An AccessCondition object that represents the + * If-Modified-Since condition. + */ + public static AccessCondition generateIfModifiedSinceCondition( + final Date lastMotified) { + AccessCondition retCondition = new AccessCondition(); + retCondition.ifModifiedSinceDate = lastMotified; + return retCondition; + } + + /** + * Returns an access condition such that an operation will be performed only + * if the resource's ETag value does not match the specified ETag value. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-None-Match conditional header. If this access condition is set, + * the operation is performed only if the ETag of the resource does not + * match the specified ETag. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param etag + * A String that represents the ETag value to check. + * + * @return An AccessCondition object that represents the + * If-None-Match condition. + */ + public static AccessCondition generateIfNoneMatchCondition(final String etag) { + AccessCondition retCondition = new AccessCondition(); + retCondition.setIfNoneMatch(etag); + return retCondition; + } + + /** + * Returns an access condition such that an operation will be performed only + * if the resource has not been modified since the specified time. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-Unmodified-Since conditional header. If this access condition + * is set, the operation is performed only if the resource has not been + * modified since the specified time. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param lastMotified + * A java.util.Date object that represents the + * last-modified time to check for the resource. + * + * @return An AccessCondition object that represents the + * If-Unmodified-Since condition. + */ + public static AccessCondition generateIfNotModifiedSinceCondition( + final Date lastMotified) { + AccessCondition retCondition = new AccessCondition(); + retCondition.ifUnmodifiedSinceDate = lastMotified; + return retCondition; + } + + /** + * Returns an access condition such that an operation will be performed only + * if the resource is accessible under the specified lease id. + *

+ * Setting this access condition modifies the request to include the HTTP + * If-Unmodified-Since conditional header. If this access condition + * is set, the operation is performed only if the resource has not been + * modified since the specified time. + *

+ * For more information, see Specifying + * Conditional Headers for Blob Service Operations. + * + * @param leaseID + * The lease id to specify. + * + */ + public static AccessCondition generateLeaseCondition(final String leaseID) { + AccessCondition retCondition = new AccessCondition(); + retCondition.leaseID = leaseID; + return retCondition; + } + + private String leaseID = null; + + /** + * Represents the etag of the resource for if [none] match conditions + */ + private String etag = null; + + /** + * Represents the date for IfModifiedSince conditions. + */ + private Date ifModifiedSinceDate = null; + + /** + * Represents the date for IfUn,odifiedSince conditions. + */ + private Date ifUnmodifiedSinceDate = null; + + /** + * Represents the ifMatchHeaderType type. + */ + private String ifMatchHeaderType = null; + + /** + * Creates an instance of the AccessCondition class. + */ + public AccessCondition() { + // Empty Default Ctor + } + + /** + * RESERVED FOR INTERNAL USE. Applies the access condition to the request. + * + * @param request + * A java.net.HttpURLConnection object that + * represents the request to which the condition is being + * applied. + * + * @throws StorageException + * If there is an error parsing the date value of the access + * condition. + */ + public void applyConditionToRequest(final HttpURLConnection request) { + applyConditionToRequest(request, false); + } + + /** + * RESERVED FOR INTERNAL USE. Applies the access condition to the request. + * + * @param request + * A java.net.HttpURLConnection object that + * represents the request to which the condition is being + * applied. + * @param useSourceAccessHeaders + * If true will use the Source_ headers for the conditions, + * otherwise standard headers are used. + * @throws StorageException + * If there is an error parsing the date value of the access + * condition. + */ + public void applyConditionToRequest(final HttpURLConnection request, + boolean useSourceAccessHeaders) { + // When used as a source access condition + if (useSourceAccessHeaders) { + if (!Utility.isNullOrEmpty(this.leaseID)) { + request.setRequestProperty( + Constants.HeaderConstants.SOURCE_LEASE_ID_HEADER, + this.leaseID); + } + + if (this.ifModifiedSinceDate != null) { + request.setRequestProperty( + Constants.HeaderConstants.SOURCE_IF_MODIFIED_SINCE_HEADER, + Utility.getGMTTime(this.ifModifiedSinceDate)); + } + + if (this.ifUnmodifiedSinceDate != null) { + request.setRequestProperty( + Constants.HeaderConstants.SOURCE_IF_UNMODIFIED_SINCE_HEADER, + Utility.getGMTTime(this.ifUnmodifiedSinceDate)); + } + + if (!Utility.isNullOrEmpty(this.etag)) { + if (this.ifMatchHeaderType + .equals(Constants.HeaderConstants.IF_MATCH)) { + request.setRequestProperty( + Constants.HeaderConstants.SOURCE_IF_MATCH_HEADER, + this.etag); + } else if (this.ifMatchHeaderType + .equals(Constants.HeaderConstants.IF_NONE_MATCH)) { + request.setRequestProperty( + Constants.HeaderConstants.SOURCE_IF_NONE_MATCH_HEADER, + this.etag); + } + } + } else { + if (!Utility.isNullOrEmpty(this.leaseID)) { + addOptionalHeader(request, "x-ms-lease-id", this.leaseID); + + } + + if (this.ifModifiedSinceDate != null) { + // The IfModifiedSince has a special helper in + // HttpURLConnection, use it instead of manually setting the + // header. + request.setIfModifiedSince(this.ifModifiedSinceDate.getTime()); + } + + if (this.ifUnmodifiedSinceDate != null) { + request.setRequestProperty( + Constants.HeaderConstants.IF_UNMODIFIED_SINCE, + Utility.getGMTTime(this.ifUnmodifiedSinceDate)); + } + + if (!Utility.isNullOrEmpty(this.etag)) { + request.setRequestProperty(this.ifMatchHeaderType, this.etag); + } + } + } + + /** + * @return the etag when the If-Match condition is set. + */ + public String getIfMatch() { + return this.ifMatchHeaderType + .equals(Constants.HeaderConstants.IF_MATCH) ? this.etag : null; + } + + /** + * @return the ifModifiedSinceDate + */ + public Date getIfModifiedSinceDate() { + return this.ifModifiedSinceDate; + } + + /** + * @return the etag when the If-None-Match condition is set. + */ + public String getIfNoneMatch() { + return this.ifMatchHeaderType + .equals(Constants.HeaderConstants.IF_NONE_MATCH) ? this.etag + : null; + } + + /** + * @return the ifUnmodifiedSinceDate + */ + public Date getIfUnmodifiedSinceDate() { + return this.ifUnmodifiedSinceDate; + } + + /** + * @return the leaseID + */ + public String getLeaseID() { + return this.leaseID; + } + + /** + * @param etag + * the etag to set + */ + public void setIfMatch(String etag) { + this.etag = normalizeEtag(etag); + this.ifMatchHeaderType = Constants.HeaderConstants.IF_MATCH; + } + + /** + * @param ifModifiedSinceDate + * the ifModifiedSinceDate to set + */ + public void setIfModifiedSinceDate(Date ifModifiedSinceDate) { + this.ifModifiedSinceDate = ifModifiedSinceDate; + } + + /** + * @param etag + * the etag to set + */ + public void setIfNoneMatch(String etag) { + this.etag = normalizeEtag(etag); + this.ifMatchHeaderType = Constants.HeaderConstants.IF_NONE_MATCH; + } + + /** + * @param ifUnmodifiedSinceDate + * the ifUnmodifiedSinceDate to set + */ + public void setIfUnmodifiedSinceDate(Date ifUnmodifiedSinceDate) { + this.ifUnmodifiedSinceDate = ifUnmodifiedSinceDate; + } + + /** + * @param leaseID + * the leaseID to set + */ + public void setLeaseID(String leaseID) { + this.leaseID = leaseID; + } + + /** + * Reserved for internal use. Verifies the condition is satisfied. + * + * @param etag + * A String that represents the ETag to check. + * @param lastModified + * A java.util.Date object that represents the last + * modified date/time. + * + * @return true if the condition is satisfied; otherwise, + * false. + * + */ + public boolean verifyConditional(final String etag, final Date lastModified) { + if (this.ifModifiedSinceDate != null) { + // The IfModifiedSince has a special helper in HttpURLConnection, + // use it instead of manually setting the + // header. + if (!lastModified.after(this.ifModifiedSinceDate)) { + return false; + } + } + + if (this.ifUnmodifiedSinceDate != null) { + if (lastModified.after(this.ifUnmodifiedSinceDate)) { + return false; + } + } + + if (!Utility.isNullOrEmpty(this.etag)) { + if (this.ifMatchHeaderType + .equals(Constants.HeaderConstants.IF_MATCH)) { + if (!this.etag.equals(etag) && !this.etag.equals("*")) { + return false; + } + } else if (this.ifMatchHeaderType + .equals(Constants.HeaderConstants.IF_NONE_MATCH)) { + if (this.etag.equals(etag)) { + return false; + } + } + } + + return true; + } + + /** + * Normalizes an Etag to be quoted, unless it is * + * + * @param inTag + * the etag to normalize + * @return the quoted etag + */ + private static String normalizeEtag(String inTag) { + if (Utility.isNullOrEmpty(inTag) || inTag.equals("*")) { + return inTag; + } else if (inTag.startsWith("\"") && inTag.endsWith("\"")) { + return inTag; + } else { + return String.format("\"%s\"", inTag); + } + } + + /** + * Adds the optional header. + * + * @param request + * a HttpURLConnection for the operation. + * @param name + * the metadata name. + * @param value + * the metadata value. + */ + public static void addOptionalHeader(final HttpURLConnection request, + final String name, final String value) { + if (value != null && !value.equals(Constants.EMPTY_STRING)) { + request.setRequestProperty(name, value); + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseOptions.java new file mode 100644 index 0000000000000..84f3273683476 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseOptions.java @@ -0,0 +1,76 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + + +/** + * Represents the options that may be set on an + * {@link com.microsoft.windowsazure.services.blob.BlobContract#acquireLease(String, String, AcquireLeaseOptions) + * acquireLease} request. These options include an optional server timeout for + * the operation and any access conditions for the operation. + */ +public class AcquireLeaseOptions extends BlobServiceOptions { + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link AcquireLeaseOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link AcquireLeaseOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link AcquireLeaseOptions} instance. + */ + @Override + public AcquireLeaseOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the access conditions set in this {@link AcquireLeaseOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions for acquiring a lease on a blob. By default, + * the operation will acquire the lease unconditionally. Use this method to + * specify conditions on the ETag or last modified time value for performing + * the operation. + *

+ * The accessCondition value only affects calls made on methods + * where this {@link AcquireLeaseOptions} instance is passed as a parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link AcquireLeaseOptions} instance. + */ + public AcquireLeaseOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseResult.java new file mode 100644 index 0000000000000..dea8a5c853b18 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseResult.java @@ -0,0 +1,61 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * A wrapper class for the response returned from a Blob Service REST API Lease + * Blob operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#acquireLease(String, String)}, + * {@link com.microsoft.windowsazure.services.blob.BlobContract#acquireLease(String, String, AcquireLeaseOptions)}, + * {@link com.microsoft.windowsazure.services.blob.BlobContract#renewLease(String, String, String, BlobServiceOptions)}, + * and {@link com.microsoft.windowsazure.services.blob.BlobContract#renewLease(String, String, String)}. + *

+ * See the Lease Blob documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class AcquireLeaseResult { + private String leaseId; + + /** + * Gets the lease ID of the blob. + *

+ * This value is used when updating or deleting a blob with an active lease, + * and when renewing or releasing the lease. + * + * @return A {@link String} containing the server-assigned lease ID for the + * blob. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Reserved for internal use. Sets the lease ID of the blob from the + * x-ms-lease-id header of the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param leaseId + * A {@link String} containing the server-assigned lease ID for + * the blob. + */ + public void setLeaseId(String leaseId) { + this.leaseId = leaseId; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobProperties.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobProperties.java new file mode 100644 index 0000000000000..751eaea619b1a --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobProperties.java @@ -0,0 +1,321 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.core.RFC1123DateAdapter; + +/** + * Represents the HTML properties and system properties that may be set on a + * blob. + */ +public class BlobProperties { + private Date lastModified; + private String etag; + private String contentType; + private long contentLength; + private String contentEncoding; + private String contentLanguage; + private String contentMD5; + private String cacheControl; + private String blobType; + private String leaseStatus; + private long sequenceNumber; + + /** + * Gets the last modified time of the blob. For block blobs, this value is + * returned only if the blob has committed blocks. + *

+ * Any operation that modifies the blob, including updates to the blob's + * metadata or properties, changes the last modified time of the blob. This + * value can be used in an access condition when updating or deleting a blob + * to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * blob. + */ + @XmlElement(name = "Last-Modified") + @XmlJavaTypeAdapter(RFC1123DateAdapter.class) + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the blob from + * the Last-Modified header value returned in a server + * response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the ETag of the blob. For block blobs, this value is returned only + * if the blob has committed blocks. + *

+ * This value can be used in an access condition when updating or deleting a + * blob to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value for + * the blob. + */ + @XmlElement(name = "Etag") + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag value of the blob from the + * ETag header value returned in a server response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the MIME content type of the blob. + * + * @return A {@link String} containing the MIME content type value for the + * blob. + */ + @XmlElement(name = "Content-Type") + public String getContentType() { + return contentType; + } + + /** + * Reserved for internal use. Sets the MIME content type value for the blob + * from the Content-Type header value returned in the server + * response. + * + * @param contentType + * A {@link String} containing the MIME content type value for + * the blob. + */ + public void setContentType(String contentType) { + this.contentType = contentType; + } + + /** + * Gets the size of the blob in bytes. + * + * @return The size of the blob in bytes. + */ + @XmlElement(name = "Content-Length") + public long getContentLength() { + return contentLength; + } + + /** + * Reserved for internal use. Sets the content length value for the blob + * from the Content-Length header value returned in the server + * response. + * + * @param contentLength + * The size of the blob in bytes. + */ + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + /** + * Gets the HTTP content encoding value of the blob. + * + * @return A {@link String} containing the HTTP content encoding value set, + * if any. + */ + @XmlElement(name = "Content-Encoding") + public String getContentEncoding() { + return contentEncoding; + } + + /** + * Reserved for internal use. Sets the HTTP content encoding value for the + * blob from the Content-Encoding header value returned in the + * server response. + * + * @param contentEncoding + * A {@link String} containing the HTTP content encoding value to + * set. + */ + public void setContentEncoding(String contentEncoding) { + this.contentEncoding = contentEncoding; + } + + /** + * Gets the HTTP content language value of the blob. + * + * @return A {@link String} containing the HTTP content language value set, + * if any. + */ + @XmlElement(name = "Content-Language") + public String getContentLanguage() { + return contentLanguage; + } + + /** + * Reserved for internal use. Sets the HTTP content language value for the + * blob from the Content-Language header value returned in the + * server response. + * + * @param contentLanguage + * A {@link String} containing the HTTP content language value to + * set. + */ + public void setContentLanguage(String contentLanguage) { + this.contentLanguage = contentLanguage; + } + + /** + * Gets the MD5 hash value of the blob content. + * + * @return A {@link String} containing the MD5 hash value of the blob + * content. + */ + @XmlElement(name = "Content-MD5") + public String getContentMD5() { + return contentMD5; + } + + /** + * Reserved for internal use. Sets the MD5 hash value of the blob content + * from the Content-MD5 header value returned in the server + * response. + * + * @param contentMD5 + * A {@link String} containing the MD5 hash value of the blob + * content. + */ + public void setContentMD5(String contentMD5) { + this.contentMD5 = contentMD5; + } + + /** + * Gets the HTTP cache control value of the blob. + * + * @return A {@link String} containing the HTTP cache control value of the + * blob. + */ + @XmlElement(name = "Cache-Control") + public String getCacheControl() { + return cacheControl; + } + + /** + * Reserved for internal use. Sets the HTTP cache control value of the blob + * from the Cache-Control header value returned in the server + * response. + * + * @param cacheControl + * A {@link String} containing the HTTP cache control value of + * the blob. + */ + public void setCacheControl(String cacheControl) { + this.cacheControl = cacheControl; + } + + /** + * Gets a string representing the type of the blob, with a value of + * "BlockBlob" for block blobs, and "PageBlob" for page blobs. + * + * @return A {@link String} containing "BlockBlob" for block blobs, or + * "PageBlob" for page blobs. + */ + @XmlElement(name = "BlobType") + public String getBlobType() { + return blobType; + } + + /** + * Reserved for internal use. Sets the blob type from the + * x-ms-blob-type header value returned in the server response. + * + * @param blobType + * A {@link String} containing "BlockBlob" for block blobs, or + * "PageBlob" for page blobs. + */ + public void setBlobType(String blobType) { + this.blobType = blobType; + } + + /** + * Gets a string representing the lease status of the blob, with a value of + * "locked" for blobs with an active lease, and "unlocked" for blobs without + * an active lease. + * + * @return A {@link String} containing "locked" for blobs with an active + * lease, and "unlocked" for blobs without an active lease. + */ + @XmlElement(name = "LeaseStatus") + public String getLeaseStatus() { + return leaseStatus; + } + + /** + * Reserved for internal use. Sets the blob lease status from the + * x-ms-lease-status header value returned in the server + * response. + * + * @param leaseStatus + * A {@link String} containing "locked" for blobs with an active + * lease, and "unlocked" for blobs without an active lease. + */ + public void setLeaseStatus(String leaseStatus) { + this.leaseStatus = leaseStatus; + } + + /** + * Gets the current sequence number for a page blob. This value is not set + * for block blobs. + * + * @return The current sequence number of the page blob. + */ + @XmlElement(name = "x-ms-blob-sequence-number") + public long getSequenceNumber() { + return sequenceNumber; + } + + /** + * Reserved for internal use. Sets the page blob sequence number from the + * x-ms-blob-sequence-number header value returned in the + * server response. + * + * @param sequenceNumber + * The current sequence number of the page blob. + */ + public void setSequenceNumber(long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobServiceOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobServiceOptions.java new file mode 100644 index 0000000000000..b6813f598a51d --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobServiceOptions.java @@ -0,0 +1,55 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * Represents the base class for options that may be set on Blob Service REST + * API operations invoked through the {@link com.microsoft.windowsazure.services.blob.BlobContract} interface. This class + * defines a server request timeout, which can be applied to all operations. + */ +public class BlobServiceOptions { + // Nullable because it is optional + private Integer timeout; + + /** + * Gets the server request timeout value associated with this + * {@link BlobServiceOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link BlobServiceOptions} instance is passed as a parameter. + * + * @return The server request timeout value in milliseconds. + */ + public Integer getTimeout() { + return timeout; + } + + /** + * Sets the server request timeout value associated with this + * {@link BlobServiceOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link BlobServiceOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link BlobServiceOptions} instance. + */ + public BlobServiceOptions setTimeout(Integer timeout) { + this.timeout = timeout; + return this; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlockList.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlockList.java similarity index 75% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlockList.java rename to media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlockList.java index 71b1ef0f31a44..a8e4d003e31b9 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlockList.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BlockList.java @@ -24,7 +24,7 @@ import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import com.microsoft.windowsazure.services.core.utils.pipeline.Base64StringAdapter; +import com.microsoft.windowsazure.core.pipeline.Base64StringAdapter; /** * Represents a list of blocks that may be committed to a block blob. @@ -37,9 +37,9 @@ public class BlockList { * Adds the committed block specified by the block ID to the block list. * * @param blockId - * A {@link String} containing the client-specified block ID for a committed block. - * @return - * A reference to this {@link BlockList} instance. + * A {@link String} containing the client-specified block ID for + * a committed block. + * @return A reference to this {@link BlockList} instance. */ public BlockList addCommittedEntry(String blockId) { CommittedEntry entry = new CommittedEntry(); @@ -52,9 +52,9 @@ public BlockList addCommittedEntry(String blockId) { * Adds the uncommitted block specified by the block ID to the block list. * * @param blockId - * A {@link String} containing the client-specified block ID for an uncommitted block. - * @return - * A reference to this {@link BlockList} instance. + * A {@link String} containing the client-specified block ID for + * an uncommitted block. + * @return A reference to this {@link BlockList} instance. */ public BlockList addUncommittedEntry(String blockId) { UncommittedEntry entry = new UncommittedEntry(); @@ -64,14 +64,15 @@ public BlockList addUncommittedEntry(String blockId) { } /** - * Adds the latest block specified by the block ID to the block list. An entry of this type will cause the server - * commit the most recent uncommitted block with the specified block ID, or the committed block with the specified - * block ID if no uncommitted block is found. + * Adds the latest block specified by the block ID to the block list. An + * entry of this type will cause the server commit the most recent + * uncommitted block with the specified block ID, or the committed block + * with the specified block ID if no uncommitted block is found. * * @param blockId - * A {@link String} containing the client-specified block ID for the latest matching block. - * @return - * A reference to this {@link BlockList} instance. + * A {@link String} containing the client-specified block ID for + * the latest matching block. + * @return A reference to this {@link BlockList} instance. */ public BlockList addLatestEntry(String blockId) { LatestEntry entry = new LatestEntry(); @@ -83,10 +84,11 @@ public BlockList addLatestEntry(String blockId) { /** * Gets the collection of entries for the block list. * - * @return - * A {@link List} of {@link Entry} instances specifying the blocks to commit. + * @return A {@link List} of {@link Entry} instances specifying the blocks + * to commit. */ - @XmlElementRefs({ @XmlElementRef(name = "Committed", type = CommittedEntry.class), + @XmlElementRefs({ + @XmlElementRef(name = "Committed", type = CommittedEntry.class), @XmlElementRef(name = "Uncommitted", type = UncommittedEntry.class), @XmlElementRef(name = "Latest", type = LatestEntry.class) }) @XmlMixed @@ -98,9 +100,9 @@ public List getEntries() { * Sets the block list to the specified collection of entries. * * @param entries - * A {@link List} of {@link Entry} instances specifying the blocks to commit. - * @return - * A reference to this {@link BlockList} instance. + * A {@link List} of {@link Entry} instances specifying the + * blocks to commit. + * @return A reference to this {@link BlockList} instance. */ public BlockList setEntries(List entries) { this.entries = entries; @@ -108,7 +110,8 @@ public BlockList setEntries(List entries) { } /** - * The abstract base class for an entry in a {@link BlockList}, representing a committed or uncommitted block. + * The abstract base class for an entry in a {@link BlockList}, representing + * a committed or uncommitted block. */ public abstract static class Entry { private String blockId; @@ -116,8 +119,8 @@ public abstract static class Entry { /** * Gets the client-specified block ID for a {@link BlockList} entry. * - * @return - * A {@link String} containing the client-specified block ID for a block. + * @return A {@link String} containing the client-specified block ID for + * a block. */ @XmlJavaTypeAdapter(Base64StringAdapter.class) @XmlValue @@ -129,7 +132,8 @@ public String getBlockId() { * Sets the client-specified block ID for a {@link BlockList} entry. * * @param blockId - * A {@link String} containing the client-specified block ID for the block. + * A {@link String} containing the client-specified block ID + * for the block. */ public void setBlockId(String blockId) { this.blockId = blockId; @@ -137,7 +141,8 @@ public void setBlockId(String blockId) { } /** - * Represents an entry in a {@link BlockList} for a previously committed block. + * Represents an entry in a {@link BlockList} for a previously committed + * block. */ @XmlRootElement(name = "Committed") public static class CommittedEntry extends Entry { @@ -151,8 +156,9 @@ public static class UncommittedEntry extends Entry { } /** - * Represents an entry in a {@link BlockList} for the most recent uncommitted block with the specified block ID, or - * the committed block with the specified block ID if no uncommitted block is found. + * Represents an entry in a {@link BlockList} for the most recent + * uncommitted block with the specified block ID, or the committed block + * with the specified block ID if no uncommitted block is found. */ @XmlRootElement(name = "Latest") public static class LatestEntry extends Entry { diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BreakLeaseResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BreakLeaseResult.java new file mode 100644 index 0000000000000..948c5b4c7afc9 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/BreakLeaseResult.java @@ -0,0 +1,39 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.blob.models; + +/** + * A wrapper class for the response returned from a Blob Service REST API Break + * Lease Blob operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#breakLease(String, String, BlobServiceOptions)} + * , + *

+ * See the Lease Blob documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class BreakLeaseResult { + private int remainingLeaseTimeInSeconds; + + public int getRemainingLeaseTimeInSeconds() { + return remainingLeaseTimeInSeconds; + } + + public void setRemainingLeaseTimeInSeconds(int remainingLeaseTimeInSeconds) { + this.remainingLeaseTimeInSeconds = remainingLeaseTimeInSeconds; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CommitBlobBlocksOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CommitBlobBlocksOptions.java new file mode 100644 index 0000000000000..7b664103c1fa9 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CommitBlobBlocksOptions.java @@ -0,0 +1,324 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.HashMap; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions) + * commitBlobBlocks} request. These options include an optional server timeout + * for the operation, the MIME content type and content encoding for the blob, + * the content language, the MD5 hash, a cache control value, blob metadata, a + * blob lease ID, and any access conditions for the operation. + */ +public class CommitBlobBlocksOptions extends BlobServiceOptions { + private String blobContentType; + private String blobContentEncoding; + private String blobContentLanguage; + private String blobContentMD5; + private String blobCacheControl; + private HashMap metadata = new HashMap(); + private String leaseId; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link CommitBlobBlocksOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + @Override + public CommitBlobBlocksOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the MIME content type value set in this + * {@link CommitBlobBlocksOptions} instance. + * + * @return A {@link String} containing the MIME content type value set, if + * any. + */ + public String getBlobContentType() { + return blobContentType; + } + + /** + * Sets the optional MIME content type for the blob content. This value will + * be returned to clients in the Content-Type header of the + * response when the blob data or blob properties are requested. If no + * content type is specified, the default content type is + * application/octet-stream. + *

+ * Note that this value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param blobContentType + * A {@link String} containing the MIME content type value to + * set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setBlobContentType(String blobContentType) { + this.blobContentType = blobContentType; + return this; + } + + /** + * Gets the HTTP content encoding value set in this + * {@link CommitBlobBlocksOptions} instance. + * + * @return A {@link String} containing the HTTP content encoding value set, + * if any. + */ + public String getBlobContentEncoding() { + return blobContentEncoding; + } + + /** + * Sets the optional HTTP content encoding value for the blob content. Use + * this value to specify any HTTP content encodings applied to the blob, + * passed as a x-ms-blob-content-encoding header value to the + * server. This value will be returned to clients in the headers of the + * response when the blob data or blob properties are requested. Pass an + * empty value to update a blob to the default value, which will cause no + * content encoding header to be returned with the blob. + *

+ * Note that this value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param blobContentEncoding + * A {@link String} containing the + * x-ms-blob-content-encoding header value to set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setBlobContentEncoding( + String blobContentEncoding) { + this.blobContentEncoding = blobContentEncoding; + return this; + } + + /** + * Gets the HTTP content language header value set in this + * {@link CommitBlobBlocksOptions} instance. + * + * @return A {@link String} containing the HTTP content language header + * value set, if any. + */ + public String getBlobContentLanguage() { + return blobContentLanguage; + } + + /** + * Sets the optional HTTP content language header value for the blob + * content. Use this value to specify the content language of the blob. This + * value will be returned to clients in the + * x-ms-blob-content-language header of the response when the + * blob data or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param blobContentLanguage + * A {@link String} containing the + * x-ms-blob-content-language header value to set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setBlobContentLanguage( + String blobContentLanguage) { + this.blobContentLanguage = blobContentLanguage; + return this; + } + + /** + * Gets the MD5 hash value for the blob content set in this + * {@link CommitBlobBlocksOptions} instance. + * + * @return A {@link String} containing the MD5 hash value for the blob + * content set, if any. + */ + public String getBlobContentMD5() { + return blobContentMD5; + } + + /** + * Sets the optional MD5 hash value for the blob content. This value will be + * returned to clients in the x-ms-blob-content-md5 header + * value of the response when the blob data or blob properties are + * requested. This hash is used to verify the integrity of the blob during + * transport. When this header is specified, the storage service checks the + * hash of the content that has arrived with the one that was sent. If the + * two hashes do not match, the operation will fail with error code 400 (Bad + * Request), which will cause a ServiceException to be thrown. + *

+ * Note that this value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param blobContentMD5 + * A {@link String} containing the MD5 hash value for the blob + * content to set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setBlobContentMD5(String blobContentMD5) { + this.blobContentMD5 = blobContentMD5; + return this; + } + + /** + * Gets the HTTP cache control value set in this + * {@link CommitBlobBlocksOptions} instance. + * + * @return A {@link String} containing the HTTP cache control value set, if + * any. + */ + public String getBlobCacheControl() { + return blobCacheControl; + } + + /** + * Sets the optional HTTP cache control value for the blob content. The Blob + * service stores this value but does not use or modify it. This value will + * be returned to clients in the headers of the response when the blob data + * or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param blobCacheControl + * A {@link String} containing the HTTP cache control value to + * set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setBlobCacheControl(String blobCacheControl) { + this.blobCacheControl = blobCacheControl; + return this; + } + + /** + * Gets the blob metadata collection set in this + * {@link CommitBlobBlocksOptions} instance. + * + * @return A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata set, if any. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Sets the blob metadata collection to associate with the created blob. + * Metadata is a collection of name-value {@link String} pairs for client + * use and is opaque to the server. Metadata names must adhere to the naming + * rules for C# + * identifiers. + *

+ * The metadata value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param metadata + * A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata to set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setMetadata(HashMap metadata) { + this.metadata = metadata; + return this; + } + + /** + * Adds a name-value pair to the blob metadata collection associated with + * this {@link CommitBlobBlocksOptions} instance. + * + * @param key + * A {@link String} containing the name portion of the name-value + * pair to add to the metadata collection. + * @param value + * A {@link String} containing the value portion of the + * name-value pair to add to the metadata collection. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions addMetadata(String key, String value) { + this.getMetadata().put(key, value); + return this; + } + + /** + * Gets the lease ID for the blob set in this + * {@link CommitBlobBlocksOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets a lease ID value to match when updating the blob. If the blob has a + * lease, this parameter must be set with the matching leaseId value for the + * commit block blobs operation to succeed. + *

+ * The leaseId value only affects calls made on methods where this + * {@link CommitBlobBlocksOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the access conditions set in this {@link CommitBlobBlocksOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions for updating a blob. By default, the commit + * block blobs operation will set the container metadata unconditionally. + * Use this method to specify conditions on the ETag or last modified time + * value for performing the commit block blobs operation. + *

+ * The accessCondition value only affects calls made on methods + * where this {@link CommitBlobBlocksOptions} instance is passed as a + * parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link CommitBlobBlocksOptions} instance. + */ + public CommitBlobBlocksOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/Constants.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/Constants.java new file mode 100644 index 0000000000000..54c99e0ef946e --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/Constants.java @@ -0,0 +1,694 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +/** + * Defines constants for use with blob operations, HTTP headers, and query + * strings. + */ +public final class Constants { + /** + * Defines constants for use Analytics requests. + */ + public static class AnalyticsConstants { + /** + * The XML element for the Analytics RetentionPolicy Days. + */ + public static final String DAYS_ELEMENT = "Days"; + + /** + * The XML element for the Default Service Version. + */ + public static final String DEFAULT_SERVICE_VERSION = "DefaultServiceVersion"; + + /** + * The XML element for the Analytics Logging Delete type. + */ + public static final String DELETE_ELEMENT = "Delete"; + + /** + * The XML element for the Analytics RetentionPolicy Enabled. + */ + public static final String ENABLED_ELEMENT = "Enabled"; + + /** + * The XML element for the Analytics Metrics IncludeAPIs. + */ + public static final String INCLUDE_APIS_ELEMENT = "IncludeAPIs"; + + /** + * The XML element for the Analytics Logging + */ + public static final String LOGGING_ELEMENT = "Logging"; + + /** + * The XML element for the Analytics Metrics + */ + public static final String METRICS_ELEMENT = "Metrics"; + + /** + * The XML element for the Analytics Logging Read type. + */ + public static final String READ_ELEMENT = "Read"; + + /** + * The XML element for the Analytics RetentionPolicy. + */ + public static final String RETENTION_POLICY_ELEMENT = "RetentionPolicy"; + + /** + * The XML element for the StorageServiceProperties + */ + public static final String STORAGE_SERVICE_PROPERTIES_ELEMENT = "StorageServiceProperties"; + + /** + * The XML element for the Analytics Version + */ + public static final String VERSION_ELEMENT = "Version"; + + /** + * The XML element for the Analytics Logging Write type. + */ + public static final String WRITE_ELEMENT = "Write"; + } + + /** + * Defines constants for use with HTTP headers. + */ + public static class HeaderConstants { + /** + * The Accept header. + */ + public static final String ACCEPT = "Accept"; + + /** + * The Accept header. + */ + public static final String ACCEPT_CHARSET = "Accept-Charset"; + + /** + * The Authorization header. + */ + public static final String AUTHORIZATION = "Authorization"; + + /** + * The CacheControl header. + */ + public static final String CACHE_CONTROL = "Cache-Control"; + + /** + * The header that specifies blob caching control. + */ + public static final String CACHE_CONTROL_HEADER = PREFIX_FOR_STORAGE_HEADER + + "blob-cache-control"; + + /** + * The Comp value. + */ + public static final String COMP = "comp"; + + /** + * The ContentEncoding header. + */ + public static final String CONTENT_ENCODING = "Content-Encoding"; + + /** + * The ContentLangauge header. + */ + public static final String CONTENT_LANGUAGE = "Content-Language"; + + /** + * The ContentLength header. + */ + public static final String CONTENT_LENGTH = "Content-Length"; + + /** + * The ContentMD5 header. + */ + public static final String CONTENT_MD5 = "Content-MD5"; + + /** + * The ContentRange header. + */ + public static final String CONTENT_RANGE = "Cache-Range"; + + /** + * The ContentType header. + */ + public static final String CONTENT_TYPE = "Content-Type"; + + /** + * The header for copy source. + */ + public static final String COPY_SOURCE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "copy-source"; + + /** + * The header that specifies the date. + */ + public static final String DATE = PREFIX_FOR_STORAGE_HEADER + "date"; + + /** + * The header to delete snapshots. + */ + public static final String DELETE_SNAPSHOT_HEADER = PREFIX_FOR_STORAGE_HEADER + + "delete-snapshots"; + + /** + * The ETag header. + */ + public static final String ETAG = "ETag"; + + /** + * Buffer width used to copy data to output streams. + */ + public static final int HTTP_UNUSED_306 = 306; + + /** + * The IfMatch header. + */ + public static final String IF_MATCH = "If-Match"; + + /** + * The IfModifiedSince header. + */ + public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; + + /** + * The IfNoneMatch header. + */ + public static final String IF_NONE_MATCH = "If-None-Match"; + + /** + * The IfUnmodifiedSince header. + */ + public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; + + /** + * The header that specifies lease ID. + */ + public static final String LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "lease-id"; + + /** + * The header that specifies lease status. + */ + public static final String LEASE_STATUS = PREFIX_FOR_STORAGE_HEADER + + "lease-status"; + + /** + * The header that specifies lease state. + */ + public static final String LEASE_STATE = PREFIX_FOR_STORAGE_HEADER + + "lease-state"; + + /** + * The header that specifies lease duration. + */ + public static final String LEASE_DURATION = PREFIX_FOR_STORAGE_HEADER + + "lease-duration"; + + /** + * The header that specifies copy status. + */ + public static final String COPY_STATUS = PREFIX_FOR_STORAGE_HEADER + + "copy-status"; + + /** + * The header that specifies copy progress. + */ + public static final String COPY_PROGRESS = PREFIX_FOR_STORAGE_HEADER + + "copy-progress"; + + /** + * The header that specifies copy status description. + */ + public static final String COPY_STATUS_DESCRIPTION = PREFIX_FOR_STORAGE_HEADER + + "copy-status-description"; + + /** + * The header that specifies copy id. + */ + public static final String COPY_ID = PREFIX_FOR_STORAGE_HEADER + + "copy-id"; + + /** + * The header that specifies copy source. + */ + public static final String COPY_SOURCE = PREFIX_FOR_STORAGE_HEADER + + "copy-source"; + + /** + * The header that specifies copy completion time. + */ + public static final String COPY_COMPLETION_TIME = PREFIX_FOR_STORAGE_HEADER + + "copy-completion-time"; + + /** + * The header prefix for metadata. + */ + public static final String PREFIX_FOR_STORAGE_METADATA = "x-ms-meta-"; + + /** + * The header prefix for properties. + */ + public static final String PREFIX_FOR_STORAGE_PROPERTIES = "x-ms-prop-"; + + /** + * The Range header. + */ + public static final String RANGE = "Range"; + + /** + * The header that specifies if the request will populate the ContentMD5 + * header for range gets. + */ + public static final String RANGE_GET_CONTENT_MD5 = PREFIX_FOR_STORAGE_HEADER + + "range-get-content-md5"; + + /** + * The format string for specifying ranges. + */ + public static final String RANGE_HEADER_FORMAT = "bytes=%d-%d"; + + /** + * The header that indicates the request ID. + */ + public static final String REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "request-id"; + + /** + * The header that indicates the client request ID. + */ + public static final String CLIENT_REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "client-request-id"; + + /** + * The header for the If-Match condition. + */ + public static final String SOURCE_IF_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-match"; + + /** + * The header for the If-Modified-Since condition. + */ + public static final String SOURCE_IF_MODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-modified-since"; + + /** + * The header for the If-None-Match condition. + */ + public static final String SOURCE_IF_NONE_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-none-match"; + + /** + * The header for the If-Unmodified-Since condition. + */ + public static final String SOURCE_IF_UNMODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-if-unmodified-since"; + + /** + * The header for the source lease id. + */ + public static final String SOURCE_LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + + "source-lease-id"; + + /** + * The header for data ranges. + */ + public static final String STORAGE_RANGE_HEADER = PREFIX_FOR_STORAGE_HEADER + + "range"; + + /** + * The header for storage version. + */ + public static final String STORAGE_VERSION_HEADER = PREFIX_FOR_STORAGE_HEADER + + "version"; + + /** + * The current storage version header value. + */ + public static final String TARGET_STORAGE_VERSION = "2012-02-12"; + + /** + * The UserAgent header. + */ + public static final String USER_AGENT = "User-Agent"; + + /** + * Specifies the value to use for UserAgent header. + */ + public static final String USER_AGENT_PREFIX = "WA-Storage"; + + /** + * Specifies the value to use for UserAgent header. + */ + public static final String USER_AGENT_VERSION = "Client v0.1.3.2"; + } + + /** + * Defines constants for use with query strings. + */ + public static class QueryConstants { + /** + * The query component for the SAS signature. + */ + public static final String SIGNATURE = "sig"; + + /** + * The query component for the signed SAS expiry time. + */ + public static final String SIGNED_EXPIRY = "se"; + + /** + * The query component for the signed SAS identifier. + */ + public static final String SIGNED_IDENTIFIER = "si"; + + /** + * The query component for the signed SAS permissions. + */ + public static final String SIGNED_PERMISSIONS = "sp"; + + /** + * The query component for the signed SAS resource. + */ + public static final String SIGNED_RESOURCE = "sr"; + + /** + * The query component for the signed SAS start time. + */ + public static final String SIGNED_START = "st"; + + /** + * The query component for the SAS start partition key. + */ + public static final String START_PARTITION_KEY = "spk"; + + /** + * The query component for the SAS start row key. + */ + public static final String START_ROW_KEY = "srk"; + + /** + * The query component for the SAS end partition key. + */ + public static final String END_PARTITION_KEY = "epk"; + + /** + * The query component for the SAS end row key. + */ + public static final String END_ROW_KEY = "erk"; + + /** + * The query component for the SAS table name. + */ + public static final String SAS_TABLE_NAME = "tn"; + + /** + * The query component for the signing SAS key. + */ + public static final String SIGNED_KEY = "sk"; + + /** + * The query component for the signed SAS version. + */ + public static final String SIGNED_VERSION = "sv"; + + /** + * The query component for snapshot time. + */ + public static final String SNAPSHOT = "snapshot"; + } + + /** + * The master Windows Azure Storage header prefix. + */ + public static final String PREFIX_FOR_STORAGE_HEADER = "x-ms-"; + + /** + * Constant representing a kilobyte (Non-SI version). + */ + public static final int KB = 1024; + + /** + * Constant representing a megabyte (Non-SI version). + */ + public static final int MB = 1024 * KB; + + /** + * Constant representing a gigabyte (Non-SI version). + */ + public static final int GB = 1024 * MB; + + /** + * Buffer width used to copy data to output streams. + */ + public static final int BUFFER_COPY_LENGTH = 8 * KB; + + /** + * Default client side timeout, in milliseconds, for all service clients. + */ + public static final int DEFAULT_TIMEOUT_IN_MS = 90 * 1000; + + /** + * XML element for delimiters. + */ + public static final String DELIMITER_ELEMENT = "Delimiter"; + + /** + * An empty String to use for comparison. + */ + public static final String EMPTY_STRING = ""; + + /** + * XML element for page range end elements. + */ + public static final String END_ELEMENT = "End"; + + /** + * XML element for error codes. + */ + public static final String ERROR_CODE = "Code"; + + /** + * XML element for exception details. + */ + public static final String ERROR_EXCEPTION = "ExceptionDetails"; + + /** + * XML element for exception messages. + */ + public static final String ERROR_EXCEPTION_MESSAGE = "ExceptionMessage"; + + /** + * XML element for stack traces. + */ + public static final String ERROR_EXCEPTION_STACK_TRACE = "StackTrace"; + + /** + * XML element for error messages. + */ + public static final String ERROR_MESSAGE = "Message"; + + /** + * XML root element for errors. + */ + public static final String ERROR_ROOT_ELEMENT = "Error"; + + /** + * XML element for the ETag. + */ + public static final String ETAG_ELEMENT = "Etag"; + + /** + * Constant for False. + */ + public static final String FALSE = "false"; + + /** + * Specifies HTTP. + */ + public static final String HTTP = "http"; + + /** + * Specifies HTTPS. + */ + public static final String HTTPS = "https"; + + /** + * XML attribute for IDs. + */ + public static final String ID = "Id"; + + /** + * XML element for an invalid metadata name. + */ + public static final String INVALID_METADATA_NAME = "x-ms-invalid-name"; + + /** + * XML element for the last modified date. + */ + public static final String LAST_MODIFIED_ELEMENT = "Last-Modified"; + + /** + * XML element for the lease status. + */ + public static final String LEASE_STATUS_ELEMENT = "LeaseStatus"; + + /** + * XML element for the lease state. + */ + public static final String LEASE_STATE_ELEMENT = "LeaseState"; + + /** + * XML element for the lease duration. + */ + public static final String LEASE_DURATION_ELEMENT = "LeaseDuration"; + + /** + * XML element for the copy id. + */ + public static final String COPY_ID_ELEMENT = "CopyId"; + + /** + * XML element for the copy status. + */ + public static final String COPY_STATUS_ELEMENT = "CopyStatus"; + + /** + * XML element for the copy source . + */ + public static final String COPY_SOURCE_ELEMENT = "CopySource"; + + /** + * XML element for the copy progress. + */ + public static final String COPY_PROGRESS_ELEMENT = "CopyProgress"; + + /** + * XML element for the copy completion time. + */ + public static final String COPY_COMPLETION_TIME_ELEMENT = "CopyCompletionTime"; + + /** + * XML element for the copy status description. + */ + public static final String COPY_STATUS_DESCRIPTION_ELEMENT = "CopyStatusDescription"; + + /** + * Constant signaling the resource is locked. + */ + public static final String LOCKED_VALUE = "Locked"; + + /** + * XML element for a marker. + */ + public static final String MARKER_ELEMENT = "Marker"; + + /** + * XML element for maximum results. + */ + public static final String MAX_RESULTS_ELEMENT = "MaxResults"; + + /** + * Number of default concurrent requests for parallel operation. + */ + public static final int MAXIMUM_SEGMENTED_RESULTS = 5000; + + /** + * The maximum size, in bytes, of a given stream mark operation. + */ + // Note if BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES is updated + // then this needs to be as well. + public static final int MAX_MARK_LENGTH = 64 * MB; + + /** + * XML element for the metadata. + */ + public static final String METADATA_ELEMENT = "Metadata"; + + /** + * XML element for names. + */ + public static final String NAME_ELEMENT = "Name"; + + /** + * XML element for the next marker. + */ + public static final String NEXT_MARKER_ELEMENT = "NextMarker"; + + /** + * XML element for a prefix. + */ + public static final String PREFIX_ELEMENT = "Prefix"; + + /** + * Constant for True. + */ + public static final String TRUE = "true"; + + /** + * Constant signaling the resource is unlocked. + */ + public static final String UNLOCKED_VALUE = "Unlocked"; + + /** + * XML element for the URL. + */ + public static final String URL_ELEMENT = "Url"; + + /** + * XML element for a signed identifier. + */ + public static final String SIGNED_IDENTIFIER_ELEMENT = "SignedIdentifier"; + + /** + * XML element for signed identifiers. + */ + public static final String SIGNED_IDENTIFIERS_ELEMENT = "SignedIdentifiers"; + + /** + * XML element for an access policy. + */ + public static final String ACCESS_POLICY = "AccessPolicy"; + + /** + * Maximum number of shared access policy identifiers supported by server. + */ + public static final int MAX_SHARED_ACCESS_POLICY_IDENTIFIERS = 5; + + /** + * XML element for the start time of an access policy. + */ + public static final String START = "Start"; + + /** + * XML element for the end time of an access policy. + */ + public static final String EXPIRY = "Expiry"; + + /** + * XML element for the permission of an access policy. + */ + public static final String PERMISSION = "Permission"; + + /** + * Private Default Ctor + */ + private Constants() { + // No op + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ContainerACL.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ContainerACL.java new file mode 100644 index 0000000000000..5ea90a0abff75 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ContainerACL.java @@ -0,0 +1,484 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.services.blob.implementation.ContainerACLDateAdapter; + +/** + * Represents the public access properties and the container-level access + * policies of a container in the Blob storage service. This is returned by + * calls to implementations of {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerACL(String)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerACL(String, BlobServiceOptions)}, and passed + * as a parameter to calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)} + * . + *

+ * See the Get + * Container ACL and the Set + * Container ACL documentation on MSDN for details of the underlying Blob + * Service REST API operations. + */ +public class ContainerACL { + private String etag; + private Date lastModified; + private PublicAccessType publicAccess; + private List signedIdentifiers = new ArrayList(); + + /** + * Gets the Etag value associated with this + * {@link ContainerACL} instance. This is the value returned for a container + * by a Blob service REST API Get Container ACL operation, or the value to + * set on a container with a Set Container ACL operation. + * + * @return A {@link String} containing the Etag value + * associated with this {@link ContainerACL} instance. + */ + public String getEtag() { + return etag; + } + + /** + * Sets the Etag value to associate with this + * {@link ContainerACL} instance. + *

+ * This value is only set on a container when this {@link ContainerACL} + * instance is passed as a parameter to a call to an implementation of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. + * + * @param etag + * A {@link String} containing the Etag value to + * associate with this {@link ContainerACL} instance. + * + * @return A reference to this {@link ContainerACL} instance. + */ + public ContainerACL setEtag(String etag) { + this.etag = etag; + return this; + } + + /** + * Gets the last modified time associated with this {@link ContainerACL} + * instance. This is the value returned for a container by a Blob service + * REST API Get Container ACL operation, or the value to set on a container + * with a Set Container ACL operation. + * + * @return A {@link Date} containing the last modified time associated with + * this {@link ContainerACL} instance. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Sets the last modified time to associate with this {@link ContainerACL} + * instance. + *

+ * This value is only set on a container when this {@link ContainerACL} + * instance is passed as a parameter to a call to an implementation of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time to + * associate with this {@link ContainerACL} instance. + * @return A reference to this {@link ContainerACL} instance. + */ + public ContainerACL setLastModified(Date lastModified) { + this.lastModified = lastModified; + return this; + } + + /** + * Gets the public access level associated with this {@link ContainerACL} + * instance. This is the value returned for a container by a Blob service + * REST API Get Container ACL operation, or the value to set on a container + * with a Set Container ACL operation. + * + * @return A {@link PublicAccessType} value representing the public access + * level associated with this {@link ContainerACL} instance. + */ + public PublicAccessType getPublicAccess() { + return publicAccess; + } + + /** + * Sets the public access level to associate with this {@link ContainerACL} + * instance. + *

+ * This value is only set on a container when this {@link ContainerACL} + * instance is passed as a parameter to a call to an implementation of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. + * + * @param publicAccess + * A {@link PublicAccessType} value representing the public + * access level to associate with this {@link ContainerACL} + * instance. + * @return A reference to this {@link ContainerACL} instance. + */ + public ContainerACL setPublicAccess(PublicAccessType publicAccess) { + this.publicAccess = publicAccess; + return this; + } + + /** + * Gets the list of container-level access policies associated with this + * {@link ContainerACL} instance. This is the value returned for a container + * by a Blob service REST API Get Container ACL operation, or the value to + * set on a container with a Set Container ACL operation. + * + * @return A {@link List} of {@link SignedIdentifier} instances containing + * up to five container-level access policies associated with this + * {@link ContainerACL} instance. + */ + public List getSignedIdentifiers() { + return signedIdentifiers; + } + + /** + * Sets the list of container-level access policies to associate with this + * {@link ContainerACL} instance. + *

+ * This value is only set on a container when this {@link ContainerACL} + * instance is passed as a parameter to a call to an implementation of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. + * + * @param signedIdentifiers + * A {@link List} of {@link SignedIdentifier} instances + * containing up to five container-level access policies to + * associate with this {@link ContainerACL} instance. + * @return A reference to this {@link ContainerACL} instance. + */ + public ContainerACL setSignedIdentifiers( + List signedIdentifiers) { + this.signedIdentifiers = signedIdentifiers; + return this; + } + + /** + * Adds a container-level access policy to the list associated with this + * {@link ContainerACL} instance. A container may have up to five + * container-level access policies. + *

+ * Use the id parameter to specify a name for the access policy. + * The name may be up to 64 characters in length and must be unique within + * the container. + *

+ * Use the start parameter to specify the start time for valid + * access to a resource using the access policy. If this value is + * null, the start time for any resource request using the + * access policy is assumed to be the time when the Blob service receives + * the request. + *

+ * Use the expiry parameter to specify the expiration time for + * valid access to a resource using the access policy. If this value is + * null, the expiry time must be included in the Shared Access + * Signature for any resource request using the access policy. + *

+ * Use the permission parameter to specify the operations that can + * be performed on a blob that is accessed with the access policy. Supported + * permissions include read (r), write (w), delete (d), and list (l). + * Permissions may be grouped so as to allow multiple operations to be + * performed with the access policy. For example, to grant all permissions + * to a resource, specify "rwdl" for the parameter. To grant only read/write + * permissions, specify "rw" for the parameter. + *

+ * This value is only set on a container when this {@link ContainerACL} + * instance is passed as a parameter to a call to an implementation of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. + * + * @param id + * A {@link String} containing the name for the access policy. + * @param start + * A {@link Date} representing the start time for the access + * policy. If this value is null, any Shared Access + * Signature that refers to this policy may specify the start + * time. + * @param expiry + * A {@link Date} representing the expiration time for the access + * policy. If this value is null, any Shared Access + * Signature that refers to this policy must specify the expiry + * value. Resource access using a Shared Access Signature that + * refers to this policy after this time is not valid. + * @param permission + * A {@link String} containing the permissions specified for the + * access policy. + */ + public void addSignedIdentifier(String id, Date start, Date expiry, + String permission) { + AccessPolicy accessPolicy = new AccessPolicy(); + accessPolicy.setStart(start); + accessPolicy.setExpiry(expiry); + accessPolicy.setPermission(permission); + + SignedIdentifier signedIdentifier = new SignedIdentifier(); + signedIdentifier.setId(id); + signedIdentifier.setAccessPolicy(accessPolicy); + + this.getSignedIdentifiers().add(signedIdentifier); + } + + /** + * A static inner class representing a collection of container-level access + * policies. A container may have up to five container-level access + * policies, which may be associated with any number of Shared Access + * Signatures. + */ + @XmlRootElement(name = "SignedIdentifiers") + public static class SignedIdentifiers { + private List signedIdentifiers = new ArrayList(); + + /** + * Gets the list of container-level access policies associated with this + * {@link SignedIdentifiers} instance. + * + * @return A {@link List} of {@link SignedIdentifier} instances + * containing container-level access policies. + */ + @XmlElement(name = "SignedIdentifier") + public List getSignedIdentifiers() { + return signedIdentifiers; + } + + /** + * Sets the list of container-level access policies associated with this + * {@link SignedIdentifiers} instance. + * + * @param signedIdentifiers + * A {@link List} of {@link SignedIdentifier} instances + * containing container-level access policies. + */ + public void setSignedIdentifiers( + List signedIdentifiers) { + this.signedIdentifiers = signedIdentifiers; + } + } + + /** + * A static inner class representing a container-level access policy with a + * unique name. + */ + public static class SignedIdentifier { + private String id; + private AccessPolicy accessPolicy; + + /** + * Gets the name of the container-level access policy. The name may be + * up to 64 characters in length and must be unique within the + * container. + * + * @return A {@link String} containing the name for the access policy. + */ + @XmlElement(name = "Id") + public String getId() { + return id; + } + + /** + * Sets the name of the container-level access policy. The name may be + * up to 64 characters in length and must be unique within the + * container. + * + * @param id + * A {@link String} containing the name for the access + * policy. + * @return A reference to this {@link SignedIdentifier} instance. + */ + public SignedIdentifier setId(String id) { + this.id = id; + return this; + } + + /** + * Gets an {@link AccessPolicy} reference containing the start time, + * expiration time, and permissions associated with the container-level + * access policy. + * + * @return An {@link AccessPolicy} reference containing the start time, + * expiration time, and permissions associated with the access + * policy. + */ + @XmlElement(name = "AccessPolicy") + public AccessPolicy getAccessPolicy() { + return accessPolicy; + } + + /** + * Sets an {@link AccessPolicy} reference containing the start time, + * expiration time, and permissions to associate with the + * container-level access policy. + * + * @param accessPolicy + * An {@link AccessPolicy} reference containing the start + * time, expiration time, and permissions to associate with + * the access policy. + * @return A reference to this {@link SignedIdentifier} instance. + */ + public SignedIdentifier setAccessPolicy(AccessPolicy accessPolicy) { + this.accessPolicy = accessPolicy; + return this; + } + } + + /** + * An inner class representing the start time, expiration time, and + * permissions associated with an access policy. + */ + public static class AccessPolicy { + private Date start; + private Date expiry; + private String permission; + + /** + * Gets the start time for valid access to a resource using the access + * policy. If this value is null, the start time for any + * resource request using the access policy is assumed to be the time + * when the Blob service receives the request. + * + * @return A {@link Date} representing the start time for the access + * policy, or null if none is specified. + */ + @XmlElement(name = "Start") + @XmlJavaTypeAdapter(ContainerACLDateAdapter.class) + public Date getStart() { + return start; + } + + /** + * Sets the start time for valid access to a resource using the access + * policy. If this value is null, the start time for any + * resource request using the access policy is assumed to be the time + * when the Blob service receives the request. + * + * @param start + * A {@link Date} representing the start time for the access + * policy, or null to leave the time + * unspecified. + * @return A reference to this {@link AccessPolicy} instance. + */ + public AccessPolicy setStart(Date start) { + this.start = start; + return this; + } + + /** + * Gets the expiration time for valid access to a resource using the + * access policy. If this value is null, any Shared Access + * Signature that refers to this access policy must specify the expiry + * value. + * + * @return A {@link Date} representing the expiration time for the + * access policy, or null if none is specified. + */ + @XmlElement(name = "Expiry") + @XmlJavaTypeAdapter(ContainerACLDateAdapter.class) + public Date getExpiry() { + return expiry; + } + + /** + * Sets the expiration time for valid access to a resource using the + * access policy. If this value is null, any Shared Access + * Signature that refers to this access policy must specify the expiry + * value. + * + * @param expiry + * A {@link Date} representing the expiration time for the + * access policy, or null to leave the time + * unspecified. + * @return A reference to this {@link AccessPolicy} instance. + */ + public AccessPolicy setExpiry(Date expiry) { + this.expiry = expiry; + return this; + } + + /** + * Gets the permissions for operations on resources specified by the + * access policy. Supported permissions include read (r), write (w), + * delete (d), and list (l). Permissions may be grouped so as to allow + * multiple operations to be performed with the access policy. For + * example, if all permissions to a resource are granted, the method + * returns "rwdl" as the result. If only read/write permissions are + * granted, the method returns "rw" as the result. + * + * @return A {@link String} containing the permissions specified for the + * access policy. + */ + @XmlElement(name = "Permission") + public String getPermission() { + return permission; + } + + /** + * Sets the permissions for operations on resources specified by the + * access policy. Supported permissions include read (r), write (w), + * delete (d), and list (l). Permissions may be grouped so as to allow + * multiple operations to be performed with the access policy. For + * example, to grant all permissions to a resource, specify "rwdl" for + * the parameter. To grant only read/write permissions, specify "rw" for + * the parameter. + * + * @param permission + * A {@link String} containing the permissions specified for + * the access policy. + * @return A reference to this {@link AccessPolicy} instance. + */ + public AccessPolicy setPermission(String permission) { + this.permission = permission; + return this; + } + } + + /** + * An enumeration type for the public access levels that can be set on a + * blob container. + */ + public static enum PublicAccessType { + /** + * Access to this container and its blobs is restricted to calls made + * with the storage account private key. + */ + NONE, + /** + * Anonymous public read-only access is allowed for individual blobs + * within the container, but it is not possible to enumerate the blobs + * within the container or to enumerate the containers in the storage + * account. + */ + BLOBS_ONLY, + /** + * Anonymous public read-only access is allowed for individual blobs + * within the container, and the blobs within the container can be + * enumerated, but it is not possible to enumerate the containers in the + * storage account. + */ + CONTAINER_AND_BLOBS, + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobOptions.java new file mode 100644 index 0000000000000..5c99629c93032 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobOptions.java @@ -0,0 +1,254 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.HashMap; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#copyBlob(String, String, String, String, CopyBlobOptions) + * copyBlob} request. These options include an optional server timeout for the + * operation, an optional source snapshot timestamp value to copy from a + * particular snapshot of the source blob, blob metadata to set on the + * destination blob, a blob lease ID to overwrite a blob with an active lease, a + * source lease ID to copy from a source blob with an active lease, any access + * conditions to satisfy on the destination, and any access conditions to + * satisfy on the source. + */ +public class CopyBlobOptions extends BlobServiceOptions { + private String leaseId; + private AccessConditionHeader accessCondition; + private String sourceLeaseId; + private String sourceSnapshot; + private HashMap metadata = new HashMap(); + private AccessConditionHeader sourceAccessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link CopyBlobOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CopyBlobOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CopyBlobOptions} instance. + */ + @Override + public CopyBlobOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the source snapshot timestamp value set in this + * {@link CopyBlobOptions} instance. + * + * @return A {@link String} containing the snapshot timestamp value of the + * source blob snapshot to list. + */ + public String getSourceSnapshot() { + return sourceSnapshot; + } + + /** + * Sets the snapshot timestamp value used to identify the particular + * snapshot of the source blob to copy. The snapshot timestamp value is an + * opaque value returned by the server to identify a snapshot. When this + * option is set, the properties, metadata, and content of the snapshot are + * copied to the destination. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobBlocksOptions} instance is passed as a parameter. + * + * @param sourceSnapshot + * A {@link String} containing the snapshot timestamp value of + * the source blob snapshot to list. + * @return A reference to this {@link ListBlobBlocksOptions} instance. + */ + public CopyBlobOptions setSourceSnapshot(String sourceSnapshot) { + this.sourceSnapshot = sourceSnapshot; + return this; + } + + /** + * Gets the blob metadata collection set in this {@link CopyBlobOptions} + * instance. + * + * @return A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata set, if any. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Sets the blob metadata collection to associate with the destination blob. + * Metadata is a collection of name-value {@link String} pairs for client + * use and is opaque to the server. Metadata names must adhere to the naming + * rules for C# + * identifiers. + *

+ * Note that if any metadata is set with this option, no source blob + * metadata will be copied to the destination blob. + *

+ * The metadata value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param metadata + * A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CopyBlobOptions setMetadata(HashMap metadata) { + this.metadata = metadata; + return this; + } + + /** + * Adds a name-value pair to the blob metadata collection associated with + * this {@link CopyBlobOptions} instance. + *

+ * Note that if any metadata is set with this option, no source blob + * metadata will be copied to the destination blob. + * + * @param key + * A {@link String} containing the name portion of the name-value + * pair to add to the metadata collection. + * @param value + * A {@link String} containing the value portion of the + * name-value pair to add to the metadata collection. + * @return A reference to this {@link CopyBlobOptions} instance. + */ + public CopyBlobOptions addMetadata(String key, String value) { + this.getMetadata().put(key, value); + return this; + } + + /** + * Gets the lease ID to match for the destination blob set in this + * {@link CopyBlobOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets a lease ID value to match on the destination blob. If set, there + * must be an active lease with a matching lease ID set on the destination + * blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link CopyBlobOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link CopyBlobOptions} instance. + */ + public CopyBlobOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the lease ID to match for the source blob set in this + * {@link CopyBlobOptions} instance. + * + * @return A {@link String} containing the source blob lease ID set, if any. + */ + public String getSourceLeaseId() { + return sourceLeaseId; + } + + /** + * Sets a lease ID value to match on the source blob. If set, there must be + * an active lease with a matching lease ID set on the source blob for the + * operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link CopyBlobOptions} instance is passed as a parameter. + * + * @param sourceLeaseId + * A {@link String} containing the source blob lease ID to set. + * @return A reference to this {@link CopyBlobOptions} instance. + */ + public CopyBlobOptions setSourceLeaseId(String sourceLeaseId) { + this.sourceLeaseId = sourceLeaseId; + return this; + } + + /** + * Gets the access conditions on the destination blob set in this + * {@link CopyBlobOptions} instance. + * + * @return An {@link AccessCondition} containing the destination blob access + * conditions set, if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets optional access conditions for the destination blob. The operation + * will return an error if the access conditions are not met. + *

+ * Note that this value only affects calls made on methods where this + * {@link CopyBlobOptions} instance is passed as a parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the destination blob + * access conditions to set. + * @return A reference to this {@link CopyBlobOptions} instance. + */ + public CopyBlobOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } + + /** + * Gets the access conditions on the source blob set in this + * {@link CopyBlobOptions} instance. + * + * @return An {@link AccessCondition} containing the source blob access + * conditions set, if any. + */ + public AccessConditionHeader getSourceAccessCondition() { + return sourceAccessCondition; + } + + /** + * Sets optional access conditions for the source blob. The operation will + * return an error if the access conditions are not met. + *

+ * Note that this value only affects calls made on methods where this + * {@link CopyBlobOptions} instance is passed as a parameter. + * + * @param sourceAccessCondition + * An {@link AccessCondition} containing the source blob access + * conditions to set. + * @return A reference to this {@link CopyBlobOptions} instance. + */ + public CopyBlobOptions setSourceAccessCondition( + AccessConditionHeader sourceAccessCondition) { + this.sourceAccessCondition = sourceAccessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobResult.java new file mode 100644 index 0000000000000..edf0bb9520337 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobResult.java @@ -0,0 +1,84 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; + +/** + * A wrapper class for the response returned from a Blob Service REST API Copy + * Blob operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#copyBlob(String, String, String, String, CopyBlobOptions)} + * . + *

+ * See the Copy Blob documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class CopyBlobResult { + private String etag; + private Date lastModified; + + /** + * Gets the ETag of the blob. + * + * @return A {@link String} containing the server-assigned ETag value for + * the copy blob. + */ + public String getEtag() { + return etag; + } + + /** + * Sets the ETag of the blob from the ETag header returned in + * the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modified time of the blob. + *

+ * + * @return A {@link java.util.Date} containing the last modified time of the + * blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Sets the last modified time of the blob from the + * Last-Modified header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobBlockOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobBlockOptions.java new file mode 100644 index 0000000000000..64f93bab2f3eb --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobBlockOptions.java @@ -0,0 +1,103 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobBlock(String, String, String, java.io.InputStream, CreateBlobBlockOptions) + * createBlobBlock} request. These options include an optional server timeout + * for the operation, the lease ID if the blob has an active lease, and the MD5 + * hash value for the block content. + */ +public class CreateBlobBlockOptions extends BlobServiceOptions { + private String leaseId; + private String contentMD5; + + /** + * Sets the optional server request timeout value associated with this + * {@link CreateBlobBlockOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CreateBlobBlockOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CreateBlobBlockOptions} instance. + */ + @Override + public CreateBlobBlockOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link CreateBlobBlockOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets a lease ID value to match when updating the blob. This value must + * match the lease ID set on a leased blob for an update to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobBlockOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link CreateBlobBlockOptions} instance. + */ + public CreateBlobBlockOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the MD5 hash value for the block content set in this + * {@link CreateBlobBlockOptions} instance. + * + * @return A {@link String} containing the MD5 hash value for the block + * content set, if any. + */ + public String getContentMD5() { + return contentMD5; + } + + /** + * Sets the optional MD5 hash value for the block content. This hash is used + * to verify the integrity of the blob during transport. When this value is + * specified, the storage service checks the hash of the content that has + * arrived with the one that was sent. If the two hashes do not match, the + * operation will fail with error code 400 (Bad Request), which will cause a + * ServiceException to be thrown. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobBlockOptions} instance is passed as a parameter. + * + * @param contentMD5 + * A {@link String} containing the MD5 hash value for the block + * content to set. + * @return A reference to this {@link CreateBlobBlockOptions} instance. + */ + public CreateBlobBlockOptions setContentMD5(String contentMD5) { + this.contentMD5 = contentMD5; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobOptions.java new file mode 100644 index 0000000000000..c5e0c0ca8ebb5 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobOptions.java @@ -0,0 +1,497 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.HashMap; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createPageBlob(String, String, long, CreateBlobOptions) + * createPageBlob} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlockBlob(String, String, java.io.InputStream, CreateBlobOptions) + * createBlockBlob} request. These options include an optional server timeout + * for the operation, the MIME content type and content encoding for the blob, + * the content language, the MD5 hash, a cache control value, blob metadata, a + * blob lease ID, a sequence number, and access conditions. + */ +public class CreateBlobOptions extends BlobServiceOptions { + private String contentType; + private String contentEncoding; + private String contentLanguage; + private String contentMD5; + private String cacheControl; + private String blobContentType; + private String blobContentEncoding; + private String blobContentLanguage; + private String blobContentMD5; + private String blobCacheControl; + private HashMap metadata = new HashMap(); + private String leaseId; + private Long sequenceNumber; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link CreateBlobOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + @Override + public CreateBlobOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the Content-Type header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the Content-Type header + * value set, if any. + */ + public String getContentType() { + return contentType; + } + + /** + * Sets the optional Content-Type header value for the blob + * content. This value will be returned to clients in the headers of the + * response when the blob data or blob properties are requested. If no + * content type is specified, the default content type is + * application/octet-stream. + * + * @param contentType + * A {@link String} containing the Content-Type + * header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Gets the Content-Encoding header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the Content-Encoding + * header value set, if any. + */ + public String getContentEncoding() { + return contentEncoding; + } + + /** + * Sets the optional Content-Encoding header value for the blob + * content. Use this value to specify the content encodings applied to the + * blob. This value will be returned to clients in the headers of the + * response when the blob data or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param contentEncoding + * A {@link String} containing the Content-Encoding + * header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setContentEncoding(String contentEncoding) { + this.contentEncoding = contentEncoding; + return this; + } + + /** + * Gets the Content-Language header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the Content-Language + * header value set, if any. + */ + public String getContentLanguage() { + return contentLanguage; + } + + /** + * Sets the optional Content-Language header value for the blob + * content. Use this value to specify the content language of the blob. This + * value will be returned to clients in the headers of the response when the + * blob data or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param contentLanguage + * A {@link String} containing the Content-Language + * header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setContentLanguage(String contentLanguage) { + this.contentLanguage = contentLanguage; + return this; + } + + /** + * Gets the Content-MD5 header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the Content-MD5 header + * value set, if any. + */ + public String getContentMD5() { + return contentMD5; + } + + /** + * Sets the optional Content-MD5 header value for the blob + * content. Use this value to specify an MD5 hash of the blob content. This + * hash is used to verify the integrity of the blob during transport. When + * this header is specified, the storage service checks the hash that has + * arrived with the one that was sent. If the two hashes do not match, the + * operation will fail with error code 400 (Bad Request). This value will be + * returned to clients in the headers of the response when the blob data or + * blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param contentMD5 + * A {@link String} containing the Content-MD5 + * header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setContentMD5(String contentMD5) { + this.contentMD5 = contentMD5; + return this; + } + + /** + * Gets the Cache-Control header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the Cache-Control header + * value set, if any. + */ + public String getCacheControl() { + return cacheControl; + } + + /** + * Sets the optional Cache-Control header value for the blob + * content. The Blob service stores this value but does not use or modify + * it. This value will be returned to clients in the headers of the response + * when the blob data or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param cacheControl + * A {@link String} containing the Cache-Control + * header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setCacheControl(String cacheControl) { + this.cacheControl = cacheControl; + return this; + } + + /** + * Gets the x-ms-blob-content-type header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the + * x-ms-blob-content-type header value set, if any. + */ + public String getBlobContentType() { + return blobContentType; + } + + /** + * Sets the optional x-ms-blob-content-type header value for + * the blob content. This value will be returned to clients in the headers + * of the response when the blob data or blob properties are requested. If + * no content type is specified, the default content type is + * application/octet-stream. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param blobContentType + * A {@link String} containing the + * x-ms-blob-content-type header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setBlobContentType(String blobContentType) { + this.blobContentType = blobContentType; + return this; + } + + /** + * Gets the x-ms-blob-content-encoding header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the + * x-ms-blob-content-encoding header value set, if any. + */ + public String getBlobContentEncoding() { + return blobContentEncoding; + } + + /** + * Sets the optional x-ms-blob-content-encoding header value + * for the blob content. Use this value to specify the content encodings + * applied to the blob. This value will be returned to clients in the + * headers of the response when the blob data or blob properties are + * requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param blobContentEncoding + * A {@link String} containing the + * x-ms-blob-content-encoding header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setBlobContentEncoding(String blobContentEncoding) { + this.blobContentEncoding = blobContentEncoding; + return this; + } + + /** + * Gets the x-ms-blob-content-language header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the + * x-ms-blob-content-language header value set, if any. + */ + public String getBlobContentLanguage() { + return blobContentLanguage; + } + + /** + * Sets the optional x-ms-blob-content-language header value + * for the blob content. Use this value to specify the content language of + * the blob. This value will be returned to clients in the headers of the + * response when the blob data or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param blobContentLanguage + * A {@link String} containing the + * x-ms-blob-content-language header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setBlobContentLanguage(String blobContentLanguage) { + this.blobContentLanguage = blobContentLanguage; + return this; + } + + /** + * Gets the x-ms-blob-content-md5 header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the + * x-ms-blob-content-md5 header value set, if any. + */ + public String getBlobContentMD5() { + return blobContentMD5; + } + + /** + * Sets the optional MD5 hash value for the blob content. This value will be + * returned to clients in the x-ms-blob-content-md5 header + * value of the response when the blob data or blob properties are + * requested. This hash is used to verify the integrity of the blob during + * transport. When this header is specified, the storage service checks the + * hash of the content that has arrived with the one that was sent. If the + * two hashes do not match, the operation will fail with error code 400 (Bad + * Request), which will cause a ServiceException to be thrown. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param blobContentMD5 + * A {@link String} containing the + * x-ms-blob-content-md5 header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setBlobContentMD5(String blobContentMD5) { + this.blobContentMD5 = blobContentMD5; + return this; + } + + /** + * Gets the x-ms-blob-cache-control header value set in this + * {@link CreateBlobOptions} instance. + * + * @return A {@link String} containing the + * x-ms-blob-cache-control header value set, if any. + */ + public String getBlobCacheControl() { + return blobCacheControl; + } + + /** + * Sets the optional x-ms-blob-cache-control header value for + * the blob content. The Blob service stores this value but does not use or + * modify it. This value will be returned to clients in the headers of the + * response when the blob data or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param blobCacheControl + * A {@link String} containing the + * x-ms-blob-cache-control header value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setBlobCacheControl(String blobCacheControl) { + this.blobCacheControl = blobCacheControl; + return this; + } + + /** + * Gets the blob metadata collection set in this {@link CreateBlobOptions} + * instance. + * + * @return A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata set, if any. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Sets the blob metadata collection to associate with the created blob. + * Metadata is a collection of name-value {@link String} pairs for client + * use and is opaque to the server. Metadata names must adhere to the naming + * rules for C# + * identifiers. + *

+ * The metadata value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param metadata + * A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setMetadata(HashMap metadata) { + this.metadata = metadata; + return this; + } + + /** + * Adds a name-value pair to the blob metadata collection associated with + * this {@link CreateBlobOptions} instance. + * + * @param key + * A {@link String} containing the name portion of the name-value + * pair to add to the metadata collection. + * @param value + * A {@link String} containing the value portion of the + * name-value pair to add to the metadata collection. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions addMetadata(String key, String value) { + this.getMetadata().put(key, value); + return this; + } + + /** + * Gets the lease ID for the blob set in this {@link CreateBlobOptions} + * instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets a lease ID value to match when updating the blob. This value is not + * used when creating a blob. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the sequence number set in this {@link CreateBlobOptions} instance. + * + * @return The page blob sequence number value set. + */ + public Long getSequenceNumber() { + return sequenceNumber; + } + + /** + * Sets the optional sequence number for a page blob in this + * {@link CreateBlobOptions} instance. This value is not used for block + * blobs. The sequence number is a user-controlled value that you can use to + * track requests. The value of the sequence number must be between 0 and + * 2^63 - 1. The default value is 0. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobOptions} instance is passed as a parameter. + * + * @param sequenceNumber + * The page blob sequence number value to set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setSequenceNumber(Long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + return this; + } + + /** + * Gets the access conditions set in this {@link CreateBlobOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions for updating a blob. This value is not used + * when creating a blob. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link CreateBlobOptions} instance. + */ + public CreateBlobOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesOptions.java new file mode 100644 index 0000000000000..49a601b6b8ab7 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesOptions.java @@ -0,0 +1,135 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobPages(String, String, PageRange, long, java.io.InputStream, CreateBlobPagesOptions)} + * request. These options include an optional server timeout for the operation, + * a blob lease ID to create pages in a blob with an active lease, an optional + * MD5 hash for the content, and any access conditions to satisfy. + */ +public class CreateBlobPagesOptions extends BlobServiceOptions { + private String leaseId; + private String contentMD5; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link CreateBlobPagesOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CreateBlobPagesOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CreateBlobPagesOptions} instance. + */ + @Override + public CreateBlobPagesOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link CreateBlobPagesOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets an optional lease ID value to match when getting the blob. If set, + * the lease must be active and the value must match the lease ID set on the + * leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobPagesOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link CreateBlobPagesOptions} instance. + */ + public CreateBlobPagesOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the MD5 hash value for the page content set in this + * {@link CreateBlobPagesOptions} instance. + * + * @return A {@link String} containing the MD5 hash value for the block + * content set, if any. + */ + public String getContentMD5() { + return contentMD5; + } + + /** + * Sets the optional MD5 hash value for the page content. This hash is used + * to verify the integrity of the blob during transport. When this value is + * specified, the storage service checks the hash of the content that has + * arrived with the one that was sent. If the two hashes do not match, the + * operation will fail with error code 400 (Bad Request), which will cause a + * ServiceException to be thrown. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobPagesOptions} instance is passed as a parameter. + * + * @param contentMD5 + * A {@link String} containing the MD5 hash value for the block + * content to set. + * @return A reference to this {@link CreateBlobPagesOptions} instance. + */ + public CreateBlobPagesOptions setContentMD5(String contentMD5) { + this.contentMD5 = contentMD5; + return this; + } + + /** + * Gets the access conditions set in this {@link CreateBlobPagesOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets optional access conditions for getting the blob. The operation will + * return an error if the access conditions are not met. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobPagesOptions} instance is passed as a parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link CreateBlobPagesOptions} instance. + */ + public CreateBlobPagesOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesResult.java new file mode 100644 index 0000000000000..2b24f46acb488 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesResult.java @@ -0,0 +1,151 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; + +/** + * A wrapper class for the response returned from a Blob Service REST API Put + * Page operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#clearBlobPages(String, String, PageRange)}, + * {@link com.microsoft.windowsazure.services.blob.BlobContract#clearBlobPages(String, String, PageRange, CreateBlobPagesOptions)} + * , + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobPages(String, String, PageRange, long, java.io.InputStream)} + * and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobPages(String, String, PageRange, long, java.io.InputStream, CreateBlobPagesOptions)} + * . + *

+ * See the Put + * Page documentation on MSDN for details of the underlying Blob Service + * REST API operation. + */ +public class CreateBlobPagesResult { + private String etag; + private Date lastModified; + private String contentMD5; + private long sequenceNumber; + + /** + * Gets the ETag of the blob. + *

+ * This value can be used in an access condition when updating or deleting a + * blob to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the blob from the + * ETag element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modified time of the blob. + *

+ * Any operation that modifies the blob, including updates to the blob's + * metadata or properties, changes the last modified time of the blob. This + * value can be used in an access condition when updating or deleting a blob + * to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * page blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the blob from + * the Last-Modified element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the MD5 hash value of the page blob. This value can be used to + * determine if the blob content has been corrupted in transmission. + * + * @return A {@link String} containing the MD5 hash value of the page blob. + */ + public String getContentMD5() { + return contentMD5; + } + + /** + * Reserved for internal use. Sets the MD5 hash value of the page blob from + * the Content-MD5 element returned in the response. + * + * @param contentMD5 + * A {@link String} containing the MD5 hash value of the page + * blob. + */ + public void setContentMD5(String contentMD5) { + this.contentMD5 = contentMD5; + } + + /** + * Gets the sequence number of the page blob. This value can be used when + * updating or deleting a page blob using an optimistic concurrency model to + * prevent the client from modifying data that has been changed by another + * client. + * + * @return A {@link String} containing the client-assigned sequence number + * value for the page blob. + */ + public long getSequenceNumber() { + return sequenceNumber; + } + + /** + * Reserved for internal use. Sets the sequence number of the page blob from + * the x-ms-blob-sequence-number element returned in the + * response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param sequenceNumber + * A {@link String} containing the client-assigned sequence + * number value for the page blob. + */ + public void setSequenceNumber(long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobResult.java new file mode 100644 index 0000000000000..a4db1f50702ba --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobResult.java @@ -0,0 +1,85 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; + +/** + * A wrapper class for the response returned from a Blob Service REST API Create + * Blob operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createPageBlob(String, String, long, CreateBlobOptions)} + * and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlockBlob(String, String, java.io.InputStream, CreateBlobOptions)} + * . + *

+ * See the Put + * Blob documentation on MSDN for details of the underlying Blob Service + * REST API operation. + */ +public class CreateBlobResult { + private String etag; + private Date lastModified; + + /** + * Gets the ETag of the blob. + * + * @return A {@link String} containing the server-assigned ETag value for + * the snapshot. + */ + public String getEtag() { + return etag; + } + + /** + * Sets the ETag of the snapshot from the ETag header returned + * in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modified time of the snapshot. + * + * @return A {@link java.util.Date} containing the last modified time of the + * blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the snapshot + * from the Last-Modified header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the snapshot. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotOptions.java new file mode 100644 index 0000000000000..9086a0cc6e083 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotOptions.java @@ -0,0 +1,156 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.HashMap; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobSnapshot(String, String, CreateBlobSnapshotOptions) + * createBlobSnapshot} request. These options include an optional server timeout + * for the operation, blob metadata to set on the snapshot, a blob lease ID to + * get a blob with an active lease, an optional start and end range for blob + * content to return, and any access conditions to satisfy. + */ +public class CreateBlobSnapshotOptions extends BlobServiceOptions { + private HashMap metadata = new HashMap(); + private String leaseId; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link CreateBlobSnapshotOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CreateBlobSnapshotOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CreateBlobSnapshotOptions} instance. + */ + @Override + public CreateBlobSnapshotOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the metadata collection set in this + * {@link CreateBlobSnapshotOptions} instance. + * + * @return A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata set, if any. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Sets the metadata collection to associate with a snapshot. Metadata is a + * collection of name-value {@link String} pairs for client use and is + * opaque to the server. Metadata names must adhere to the naming rules for + * C# + * identifiers. + *

+ * The metadata value only affects calls made on methods where this + * {@link CreateBlobSnapshotOptions} instance is passed as a parameter. + * + * @param metadata + * A {@link java.util.HashMap} of name-value pairs of + * {@link String} containing the names and values of the metadata + * to set. + * @return A reference to this {@link CreateBlobSnapshotOptions} instance. + */ + public CreateBlobSnapshotOptions setMetadata( + HashMap metadata) { + this.metadata = metadata; + return this; + } + + /** + * Adds a name-value pair to the metadata collection associated with this + * {@link CreateBlobSnapshotOptions} instance. + * + * @param key + * A {@link String} containing the name portion of the name-value + * pair to add to the metadata collection. + * @param value + * A {@link String} containing the value portion of the + * name-value pair to add to the metadata collection. + * @return A reference to this {@link CreateBlobSnapshotOptions} instance. + */ + public CreateBlobSnapshotOptions addMetadata(String key, String value) { + this.getMetadata().put(key, value); + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link CreateBlobSnapshotOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets an optional lease ID value to match when creating a snapshot of the + * blob. If set, the lease must be active and the value must match the lease + * ID set on the leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobSnapshotOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link CreateBlobSnapshotOptions} instance. + */ + public CreateBlobSnapshotOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the access conditions set in this {@link CreateBlobSnapshotOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets optional access conditions for creating a snapshot of the blob. The + * operation will return an error if the access conditions are not met. + *

+ * Note that this value only affects calls made on methods where this + * {@link CreateBlobSnapshotOptions} instance is passed as a parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link CreateBlobSnapshotOptions} instance. + */ + public CreateBlobSnapshotOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotResult.java new file mode 100644 index 0000000000000..e70741c58ff6c --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotResult.java @@ -0,0 +1,130 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; + +/** + * A wrapper class for the response returned from a Blob Service REST API + * Snapshot Blob operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobSnapshot(String, String)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createBlobSnapshot(String, String, CreateBlobSnapshotOptions)} + * . + *

+ * See the Snapshot Blob documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class CreateBlobSnapshotResult { + private String snapshot; + private String etag; + private Date lastModified; + + /** + * Gets the snapshot timestamp value returned by the server to uniquely + * identify the newly created snapshot. + *

+ * The snapshot timestamp value is an opaque value returned by the server to + * uniquely identify a snapshot version, and may be used in subsequent + * requests to access the snapshot. + *

+ * + * @return A {@link String} containing the snapshot timestamp value of the + * newly created snapshot. + */ + public String getSnapshot() { + return snapshot; + } + + /** + * Reserved for internal use. Sets the snapshot timestamp value from the + * x-ms-snapshot header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp value of + * the newly created snapshot. + */ + public void setSnapshot(String snapshot) { + this.snapshot = snapshot; + } + + /** + * Gets the ETag of the snapshot. + *

+ * Note that a snapshot cannot be written to, so the ETag of a given + * snapshot will never change. However, the ETag of the snapshot will differ + * from that of the base blob if new metadata was supplied with the create + * blob snapshot request. If no metadata was specified with the request, the + * ETag of the snapshot will be identical to that of the base blob at the + * time the snapshot was taken. + * + * @return A {@link String} containing the server-assigned ETag value for + * the snapshot. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the snapshot from the + * ETag header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modified time of the snapshot. + *

+ * Note that a snapshot cannot be written to, so the last modified time of a + * given snapshot will never change. However, the last modified time of the + * snapshot will differ from that of the base blob if new metadata was + * supplied with the create blob snapshot request. If no metadata was + * specified with the request, the last modified time of the snapshot will + * be identical to that of the base blob at the time the snapshot was taken. + * + * @return A {@link java.util.Date} containing the last modified time of the + * snapshot. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the snapshot + * from the Last-Modified header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the snapshot. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateContainerOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateContainerOptions.java new file mode 100644 index 0000000000000..ba74a2c16d30e --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateContainerOptions.java @@ -0,0 +1,154 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.HashMap; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#createContainer(String, CreateContainerOptions) + * createContainer} request. These options include a server response timeout for + * the request, metadata to set on the container, and the public access level + * for container and blob data. Options that are not set will not be passed to + * the server with a request. + */ +public class CreateContainerOptions extends BlobServiceOptions { + private String publicAccess; + private HashMap metadata = new HashMap(); + + /** + * Sets the server request timeout value associated with this + * {@link CreateContainerOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CreateContainerOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CreateContainerOptions} instance. + */ + @Override + public CreateContainerOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the metadata collection associated with this + * {@link CreateContainerOptions} instance. + * + * @return A {@link java.util.HashMap} of name-value pairs of {@link String} + * containing the names and values of the container metadata to set. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Sets the metadata collection associated with this + * {@link CreateContainerOptions} instance. Metadata is a collection of + * name-value {@link String} pairs for client use and is opaque to the + * server. Metadata names must adhere to the naming rules for C# + * identifiers. + *

+ * The metadata value only affects calls made on methods where this + * {@link CreateContainerOptions} instance is passed as a parameter. + * + * @param metadata + * A {@link java.util.HashMap} of name-value pairs of + * {@link String} containing the names and values of the + * container metadata to set. + * @return A reference to this {@link CreateContainerOptions} instance. + */ + public CreateContainerOptions setMetadata(HashMap metadata) { + this.metadata = metadata; + return this; + } + + /** + * Adds a metadata name-value pair to the metadata collection associated + * with this {@link CreateContainerOptions} instance. + * + * @param key + * A {@link String} containing the name portion of the name-value + * pair to add to the metadata collection. + * @param value + * A {@link String} containing the value portion of the + * name-value pair to add to the metadata collection. + * @return A reference to this {@link CreateContainerOptions} instance. + */ + public CreateContainerOptions addMetadata(String key, String value) { + this.getMetadata().put(key, value); + return this; + } + + /** + * Gets the public access level value associated with this + * {@link CreateContainerOptions} instance. The public access level + * specifies whether data in the container may be accessed publicly and the + * level of access. Possible values include: + *

    + *
  • container  Specifies full public read access for + * container and blob data. Clients can enumerate blobs within the container + * via anonymous request, but cannot enumerate containers within the storage + * account.
  • + *
  • blob  Specifies public read access for blobs. Blob + * data within this container can be read via anonymous request, but + * container data is not available. Clients cannot enumerate blobs within + * the container via anonymous request.
  • + *
+ * The default value of null sets the container data private to + * the storage account owner. + * + * @return A {@link String} containing the public access level value to set, + * or null. + */ + public String getPublicAccess() { + return publicAccess; + } + + /** + * Sets the public access level value associated with this + * {@link CreateContainerOptions} instance. The public access level + * specifies whether data in the container may be accessed publicly and the + * level of access. Possible values include: + *
    + *
  • container  Specifies full public read access for + * container and blob data. Clients can enumerate blobs within the container + * via anonymous request, but cannot enumerate containers within the storage + * account.
  • + *
  • blob  Specifies public read access for blobs. Blob + * data within this container can be read via anonymous request, but + * container data is not available. Clients cannot enumerate blobs within + * the container via anonymous request.
  • + *
+ * The default value of null sets the container data private to + * the storage account owner. + *

+ * The publicAccess value only affects calls made on methods where + * this {@link CreateContainerOptions} instance is passed as a parameter. + * + * @param publicAccess + * A {@link String} containing the public access level value to + * set, or null to set the container data private to + * the storage account owner. + * @return A reference to this {@link CreateContainerOptions} instance. + */ + public CreateContainerOptions setPublicAccess(String publicAccess) { + this.publicAccess = publicAccess; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteBlobOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteBlobOptions.java new file mode 100644 index 0000000000000..066093601c5fd --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteBlobOptions.java @@ -0,0 +1,180 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#deleteBlob(String, String, DeleteBlobOptions) deleteBlob} + * request. These options include an optional server timeout for the operation, + * a snapshot timestamp to specify an individual snapshot to delete, a blob + * lease ID to delete a blob with an active lease, a flag indicating whether to + * delete all snapshots but not the blob, or both the blob and all snapshots, + * and any access conditions to satisfy. + */ +public class DeleteBlobOptions extends BlobServiceOptions { + private String snapshot; + private String leaseId; + private Boolean deleteSnaphotsOnly; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link DeleteBlobOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link DeleteBlobOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link DeleteBlobOptions} instance. + */ + @Override + public DeleteBlobOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the snapshot timestamp value set in this {@link DeleteBlobOptions} + * instance. + * + * @return A {@link String} containing the snapshot timestamp value of the + * blob snapshot to get. + */ + public String getSnapshot() { + return snapshot; + } + + /** + * Reserved for future use. Sets an optional snapshot timestamp value used + * to identify the particular snapshot of the blob to delete. + *

+ * The snapshot timestamp value is an opaque value returned by the server to + * identify a snapshot. This option cannot be set if the delete snapshots + * only option is set to true or false. + *

+ * Note that this value only affects calls made on methods where this + * {@link DeleteBlobOptions} instance is passed as a parameter. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp value of + * the blob snapshot to get. + * @return A reference to this {@link DeleteBlobOptions} instance. + */ + public DeleteBlobOptions setSnapshot(String snapshot) { + this.snapshot = snapshot; + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link DeleteBlobOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets an optional lease ID value to match when deleting the blob. If set, + * the lease must be active and the value must match the lease ID set on the + * leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link DeleteBlobOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link DeleteBlobOptions} instance. + */ + public DeleteBlobOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the flag indicating whether to delete only snapshots of the blob, or + * both the blob and all its snapshots set in this {@link DeleteBlobOptions} + * instance. + * + * @return A value of true to delete only the snapshots, or + * false to delete both snapshots and the blob. When + * the value null is set, x-ms-delete-snapshots in the + * header will not be set. + */ + public Boolean getDeleteSnaphotsOnly() { + return deleteSnaphotsOnly; + } + + /** + * Sets a flag indicating whether to delete only snapshots of the blob, or + * both the blob and all its snapshots. + *

+ * If the deleteSnaphotsOnly parameter is set to true, + * only the snapshots of the blob are deleted by the operation. If the + * parameter is set to false, both the blob and all its + * snapshots are deleted by the operation. If this option is not set on a + * request, and the blob has associated snapshots, the Blob service returns + * a 409 (Conflict) status code and a {@link com.microsoft.windowsazure.exception.ServiceException} is thrown. + *

+ * This option is not compatible with the snapshot option; if both are set + * the Blob service returns status code 400 (Bad Request) and a + * {@link StorageException} is thrown. + *

+ * Note that this value only affects calls made on methods where this + * {@link DeleteBlobOptions} instance is passed as a parameter. + * + * @param deleteSnaphotsOnly + * Set to true to delete only the snapshots, or + * false to delete both snapshots and the blob. + * @return A reference to this {@link DeleteBlobOptions} instance. + */ + public DeleteBlobOptions setDeleteSnaphotsOnly(boolean deleteSnaphotsOnly) { + this.deleteSnaphotsOnly = deleteSnaphotsOnly; + return this; + } + + /** + * Gets the access conditions set in this {@link DeleteBlobOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets optional access conditions for getting the blob. The operation will + * return an error if the access conditions are not met. + *

+ * Note that this value only affects calls made on methods where this + * {@link DeleteBlobOptions} instance is passed as a parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link DeleteBlobOptions} instance. + */ + public DeleteBlobOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteContainerOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteContainerOptions.java new file mode 100644 index 0000000000000..f4768f2943952 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteContainerOptions.java @@ -0,0 +1,83 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#deleteContainer(String, DeleteContainerOptions) + * deleteContainer} request. These options include a server response timeout for + * the request and access conditions that specify whether to perform the + * operation or not depending on the values of the Etag or last modified time of + * the container. Options that are not set will not be passed to the server with + * a request. + */ +public class DeleteContainerOptions extends BlobServiceOptions { + private AccessConditionHeader accessCondition; + + /** + * Sets the server request timeout value associated with this + * {@link DeleteContainerOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link DeleteContainerOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link DeleteContainerOptions} instance. + */ + @Override + public DeleteContainerOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the access conditions associated with this + * {@link DeleteContainerOptions} instance. + * + * @return An {@link AccessCondition} reference containing the Etag and last + * modified time conditions for performing the delete container + * operation, or null if not set. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions associated with this + * {@link DeleteContainerOptions} instance. By default, the delete container + * operation will delete the container unconditionally. Use this method to + * specify conditions on the Etag or last modified time value for performing + * the delete container operation. + *

+ * The accessCondition value only affects calls made on methods + * where this {@link DeleteContainerOptions} instance is passed as a + * parameter. + * + * @param accessCondition + * An {@link AccessCondition} reference containing the Etag and + * last modified time conditions for performing the delete + * container operation. Specify null to make the + * operation unconditional. + * @return A reference to this {@link DeleteContainerOptions} instance. + */ + public DeleteContainerOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataOptions.java new file mode 100644 index 0000000000000..e12b211523355 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataOptions.java @@ -0,0 +1,131 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlobMetadata(String, String, GetBlobMetadataOptions) + * getBlobMetadata} request. These options include an optional server timeout + * for the operation, the lease ID if the blob has an active lease, the snapshot + * timestamp to get the properties of a snapshot, and any access conditions for + * the request. + */ +public class GetBlobMetadataOptions extends BlobServiceOptions { + private String snapshot; + private String leaseId; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link GetBlobMetadataOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link GetBlobMetadataOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link GetBlobMetadataOptions} instance. + */ + @Override + public GetBlobMetadataOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the snapshot timestamp value set in this + * {@link GetBlobMetadataOptions} instance. + * + * @return A {@link String} containing the snapshot timestamp value of the + * blob snapshot to get metadata for. + */ + public String getSnapshot() { + return snapshot; + } + + /** + * Sets the snapshot timestamp value used to identify the particular + * snapshot of the blob to get metadata for. The snapshot timestamp value is + * an opaque value returned by the server to identify a snapshot. When this + * option is set, only the metadata of the snapshot is returned. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobMetadataOptions} instance is passed as a parameter. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp value of + * the blob snapshot to get metadata for. + * @return A reference to this {@link GetBlobMetadataOptions} instance. + */ + public GetBlobMetadataOptions setSnapshot(String snapshot) { + this.snapshot = snapshot; + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link GetBlobMetadataOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets a lease ID value to match when getting the metadata of the blob. If + * set, the lease must be active and the value must match the lease ID set + * on the leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobMetadataOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link GetBlobMetadataOptions} instance. + */ + public GetBlobMetadataOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the access conditions set in this {@link GetBlobMetadataOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions for getting the metadata of the blob. The + * operation will return an error if the access conditions are not met. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link GetBlobMetadataOptions} instance. + */ + public GetBlobMetadataOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataResult.java new file mode 100644 index 0000000000000..c1fb178df9886 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataResult.java @@ -0,0 +1,125 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; +import java.util.HashMap; + +/** + * A wrapper class for the response returned from a Blob Service REST API Get + * Blob Metadata operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlobMetadata(String, String)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlobMetadata(String, String, GetBlobMetadataOptions)}. + *

+ * See the Get + * Blob Metadata documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class GetBlobMetadataResult { + private String etag; + private Date lastModified; + private HashMap metadata; + + /** + * Gets the ETag of the blob. For block blobs, this value is returned only + * if the blob has committed blocks. + *

+ * This value can be used in an access condition when updating or deleting a + * blob to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the blob from the + * ETag header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modified time of the block blob. For block blobs, this + * value is returned only if the blob has committed blocks. + *

+ * Any operation that modifies the blob, including updates to the blob's + * metadata or properties, changes the last modified time of the blob. This + * value can be used in an access condition when updating or deleting a blob + * to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the blob from + * the Last-Modified header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the user-defined blob metadata as a map of name and value pairs. The + * metadata is for client use and is opaque to the server. + * + * @return A {@link java.util.HashMap} of name-value pairs of {@link String} + * containing the names and values of the blob metadata. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. Sets the blob metadata from the + * x-ms-meta-name:value headers returned in the + * response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of name-value pairs of + * {@link String} containing the names and values of the blob + * metadata. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobOptions.java new file mode 100644 index 0000000000000..c56df960828fb --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobOptions.java @@ -0,0 +1,236 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlob(String, String, GetBlobOptions) getBlob} request. + * These options include an optional server timeout for the operation, a + * snapshot timestamp to specify a snapshot, a blob lease ID to get a blob with + * an active lease, an optional start and end range for blob content to return, + * and any access conditions to satisfy. + */ +public class GetBlobOptions extends BlobServiceOptions { + private String snapshot; + private String leaseId; + private boolean computeRangeMD5; + private Long rangeStart; + private Long rangeEnd; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link GetBlobOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link GetBlobOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link GetBlobOptions} instance. + */ + @Override + public GetBlobOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the snapshot timestamp value set in this {@link GetBlobOptions} + * instance. + * + * @return A {@link String} containing the snapshot timestamp value of the + * blob snapshot to get. + */ + public String getSnapshot() { + return snapshot; + } + + /** + * Sets an optional snapshot timestamp value used to identify the particular + * snapshot of the blob to get properties, metadata, and content for. The + * snapshot timestamp value is an opaque value returned by the server to + * identify a snapshot. When this option is set, only the properties, + * metadata, and content of the snapshot are returned. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobOptions} instance is passed as a parameter. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp value of + * the blob snapshot to get. + * @return A reference to this {@link GetBlobOptions} instance. + */ + public GetBlobOptions setSnapshot(String snapshot) { + this.snapshot = snapshot; + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link GetBlobOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets an optional lease ID value to match when getting the blob. If set, + * the lease must be active and the value must match the lease ID set on the + * leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link GetBlobOptions} instance. + */ + public GetBlobOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Reserved for future use. Gets a flag indicating whether to return an MD5 + * hash for the specified range of blob content set in this + * {@link GetBlobOptions} instance. + * + * @return A flag value of true to get the MD5 hash value for + * the specified range, otherwise false. + */ + public boolean isComputeRangeMD5() { + return computeRangeMD5; + } + + /** + * Reserved for future use. Sets a flag indicating whether to return an MD5 + * hash for the specified range of blob content. + *

+ * When the computeRangeMD5 parameter is set to true + * and specified together with a range less than or equal to 4 MB in size, + * the get blob operation response includes the MD5 hash for the range. If + * the computeRangeMD5 parameter is set to true and no + * range is specified or the range exceeds 4 MB in size, a + * {@link com.microsoft.windowsazure.exception.ServiceException} is thrown. + * + * @param computeRangeMD5 + * Reserved for future use. Set a flag value of true + * to get the MD5 hash value for the specified range, otherwise + * false. + * @return A reference to this {@link GetBlobOptions} instance. + */ + public GetBlobOptions setComputeRangeMD5(boolean computeRangeMD5) { + this.computeRangeMD5 = computeRangeMD5; + return this; + } + + /** + * Gets the beginning byte offset value of the blob content range to return + * set in this {@link GetBlobOptions} instance. + * + * @return The beginning offset value in bytes for the blob content range to + * return. + */ + public Long getRangeStart() { + return rangeStart; + } + + /** + * Sets an optional beginning byte offset value of the blob content range to + * return for the request, inclusive. + *

+ * When this value is set, the blob content beginning at the byte offset + * specified by the rangeStart value and ending at the range end + * value, inclusive, is returned in the server response to the get blob + * operation. If the range end is not set, the response includes blob + * content from the rangeStart value to the end of the blob. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobOptions} instance is passed as a parameter. + * + * @param rangeStart + * The beginning offset value in bytes for the blob content range + * to return, inclusive. + * @return A reference to this {@link GetBlobOptions} instance. + */ + public GetBlobOptions setRangeStart(Long rangeStart) { + this.rangeStart = rangeStart; + return this; + } + + /** + * Gets the ending byte offset value for the blob content range to return + * set in this {@link GetBlobOptions} instance. + * + * @return The ending offset value in bytes for the blob content range to + * return. + */ + public Long getRangeEnd() { + return rangeEnd; + } + + /** + * Sets an optional ending byte offset value of the blob content range to + * return for the request, inclusive. + *

+ * If the range start is not set, this value is ignored and the response + * includes content from the entire blob. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobOptions} instance is passed as a parameter. + * + * @param rangeEnd + * The ending offset value in bytes for the blob content range to + * return, inclusive. + * @return A reference to this {@link GetBlobOptions} instance. + */ + public GetBlobOptions setRangeEnd(Long rangeEnd) { + this.rangeEnd = rangeEnd; + return this; + } + + /** + * Gets the access conditions set in this {@link GetBlobOptions} instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets optional access conditions for getting the blob. The operation will + * return an error if the access conditions are not met. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobOptions} instance is passed as a parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link GetBlobOptions} instance. + */ + public GetBlobOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesOptions.java new file mode 100644 index 0000000000000..f2aa5a0c673a8 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesOptions.java @@ -0,0 +1,131 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlobProperties(String, String, GetBlobPropertiesOptions) + * getBlobProperties} request. These options include an optional server timeout + * for the operation, the lease ID if the blob has an active lease, the snapshot + * timestamp to get the properties of a snapshot, and any access conditions for + * the request. + */ +public class GetBlobPropertiesOptions extends BlobServiceOptions { + private String snapshot; + private String leaseId; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link GetBlobPropertiesOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link GetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link GetBlobPropertiesOptions} instance. + */ + @Override + public GetBlobPropertiesOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the snapshot timestamp value set in this + * {@link GetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the snapshot timestamp value of the + * blob snapshot to get properties for. + */ + public String getSnapshot() { + return snapshot; + } + + /** + * Sets the snapshot timestamp value used to identify the particular + * snapshot of the blob to get properties for. The snapshot timestamp value + * is an opaque value returned by the server to identify a snapshot. When + * this option is set, only the properties of the snapshot are returned. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp value of + * the blob snapshot to get properties for. + * @return A reference to this {@link GetBlobPropertiesOptions} instance. + */ + public GetBlobPropertiesOptions setSnapshot(String snapshot) { + this.snapshot = snapshot; + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link GetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets a lease ID value to match when getting the properties of the blob. + * If set, the lease must be active and the value must match the lease ID + * set on the leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link GetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link GetBlobPropertiesOptions} instance. + */ + public GetBlobPropertiesOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the access conditions set in this {@link GetBlobPropertiesOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions for getting the properties of the blob. The + * operation will return an error if the access conditions are not met. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link GetBlobPropertiesOptions} instance. + */ + public GetBlobPropertiesOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesResult.java new file mode 100644 index 0000000000000..c0ec8117c6780 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesResult.java @@ -0,0 +1,87 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.HashMap; + +/** + * A wrapper class for the response returned from a Blob Service REST API Get + * Blob Properties operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlobProperties(String, String)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlobProperties(String, String, GetBlobPropertiesOptions)} + * . + *

+ * See the Get + * Blob Properties documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class GetBlobPropertiesResult { + private BlobProperties properties; + private HashMap metadata = new HashMap(); + + /** + * Gets the standard HTTP properties and system properties of the blob. + * + * @return A {@link BlobProperties} instance containing the properties of + * the blob. + */ + public BlobProperties getProperties() { + return properties; + } + + /** + * Reserved for internal use. Sets the blob properties from the headers + * returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param properties + * A {@link BlobProperties} instance containing the properties of + * the blob. + */ + public void setProperties(BlobProperties properties) { + this.properties = properties; + } + + /** + * Gets the user-defined blob metadata as a map of name and value pairs. The + * metadata is for client use and is opaque to the server. + * + * @return A {@link java.util.HashMap} of key-value pairs of {@link String} + * containing the names and values of the blob metadata. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. Sets the blob metadata from the + * x-ms-meta-name:value headers returned in the + * response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of key-value pairs of + * {@link String} containing the names and values of the blob + * metadata. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobResult.java new file mode 100644 index 0000000000000..6650d0ac80791 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobResult.java @@ -0,0 +1,112 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.io.InputStream; +import java.util.HashMap; + +/** + * A wrapper class for the response returned from a Blob Service REST API Get + * Blob operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getBlob(String, String, GetBlobOptions)}. + *

+ * See the Get + * Blob documentation on MSDN for details of the underlying Blob Service + * REST API operation. + */ +public class GetBlobResult { + private InputStream contentStream; + private BlobProperties properties; + private HashMap metadata; + + /** + * Gets the content of the blob. + * + * @return An {@link InputStream} instance containing the content of the + * blob. + */ + public InputStream getContentStream() { + return contentStream; + } + + /** + * Reserved for internal use. Sets the blob content from the body returned + * in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param contentStream + * An {@link InputStream} instance containing the content of the + * blob. + */ + public void setContentStream(InputStream contentStream) { + this.contentStream = contentStream; + } + + /** + * Gets the standard HTTP properties and system properties of the blob. + * + * @return A {@link BlobProperties} instance containing the properties of + * the blob. + */ + public BlobProperties getProperties() { + return properties; + } + + /** + * Reserved for internal use. Sets the blob properties from the headers + * returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param properties + * A {@link BlobProperties} instance containing the properties of + * the blob. + */ + public void setProperties(BlobProperties properties) { + this.properties = properties; + } + + /** + * Gets the user-defined blob metadata as a map of name and value pairs. The + * metadata is for client use and is opaque to the server. + * + * @return A {@link java.util.HashMap} of key-value pairs of {@link String} + * containing the names and values of the blob metadata. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. Sets the blob metadata from the + * x-ms-meta-name:value headers returned in the + * response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of key-value pairs of + * {@link String} containing the names and values of the blob + * metadata. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerACLResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerACLResult.java new file mode 100644 index 0000000000000..2098b14faa2b4 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerACLResult.java @@ -0,0 +1,60 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * A wrapper class for the response returned from a Blob Service REST API Get + * Container ACL operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerACL(String)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerACL(String, BlobServiceOptions)}. + *

+ * See the Get + * Container ACL documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class GetContainerACLResult { + private ContainerACL containerACL; + + /** + * Gets the container's public access level and container-level access + * policies from the headers and body returned in the response. + * + * @return A {@link ContainerACL} instance representing the public access + * level and container-level access policies returned by the + * request. + */ + public ContainerACL getContainerACL() { + return containerACL; + } + + /** + * Reserved for internal use. Sets the container's public access level and + * container-level access policies from the headers and body returned in the + * response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param containerACL + * A {@link ContainerACL} instance representing the public access + * level and container-level access policies returned by the + * request. + */ + public void setValue(ContainerACL containerACL) { + this.containerACL = containerACL; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerPropertiesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerPropertiesResult.java new file mode 100644 index 0000000000000..1bc06b7e5ba70 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerPropertiesResult.java @@ -0,0 +1,122 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; +import java.util.HashMap; + +/** + * A wrapper class for the response returned from a Blob Service REST API Get + * Container Properties and Get Container Metadata operations. This is returned + * by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerProperties(String)}, + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerProperties(String, BlobServiceOptions)}, + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerMetadata(String)}, and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getContainerMetadata(String, BlobServiceOptions)}. + *

+ * See the Get + * Container Properties and Get + * Container Metadata documentation on MSDN for details of the underlying + * Blob Service REST API operations. + */ +public class GetContainerPropertiesResult { + private String etag; + private Date lastModified; + private HashMap metadata; + + /** + * Gets the Etag of the container. This value can be used when updating or + * deleting a container using an optimistic concurrency model to prevent the + * client from modifying data that has been changed by another client. + * + * @return A {@link String} containing the server-assigned Etag value for + * the container. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the Etag of the container from the + * ETag header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned Etag value for + * the container. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modifed time of the container. This value can be used when + * updating or deleting a container using an optimistic concurrency model to + * prevent the client from modifying data that has been changed by another + * client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * container. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the container + * from the Last-Modified header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the container. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the container metadata as a map of name and value pairs. The + * container metadata is for client use and is opaque to the server. + * + * @return A {@link java.util.HashMap} of key-value pairs of {@link String} + * containing the names and values of the container metadata. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. Sets the container metadata from the + * x-ms-meta-name headers returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of key-value pairs of + * {@link String} containing the names and values of the + * container metadata. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetServicePropertiesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetServicePropertiesResult.java new file mode 100644 index 0000000000000..d4441781c4840 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/GetServicePropertiesResult.java @@ -0,0 +1,63 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * A wrapper class for the service properties returned in response to Blob + * Service REST API operations. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getServiceProperties()} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getServiceProperties(BlobServiceOptions)}. + *

+ * See the Get + * Blob Service Properties documentation on MSDN for details of the + * underlying Blob Service REST API operation. + */ +public class GetServicePropertiesResult { + private ServiceProperties value; + + /** + * Gets a {@link ServiceProperties} instance containing the service property + * values associated with the storage account. + *

+ * Modifying the values in the {@link ServiceProperties} instance returned + * does not affect the values associated with the storage account. To change + * the values in the storage account, call the + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setServiceProperties} method and pass the modified + * {@link ServiceProperties} instance as a parameter. + * + * @return A {@link ServiceProperties} instance containing the property + * values associated with the storage account. + */ + public ServiceProperties getValue() { + return value; + } + + /** + * Reserved for internal use. Sets the value of the + * {@link ServiceProperties} instance associated with a storage service call + * result. This method is invoked by the API to store service properties + * returned by a call to a REST operation and is not intended for public + * use. + * + * @param value + * A {@link ServiceProperties} instance containing the property + * values associated with the storage account. + */ + public void setValue(ServiceProperties value) { + this.value = value; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksOptions.java new file mode 100644 index 0000000000000..4833d2cfd0af1 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksOptions.java @@ -0,0 +1,162 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobBlocks(String, String, ListBlobBlocksOptions) + * listBlobBlocks} request. These options include an optional server timeout for + * the operation, the lease ID if the blob has an active lease, the snapshot + * timestamp to get the committed blocks of a snapshot, whether to return the + * committed block list, and whether to return the uncommitted block list. + */ +public class ListBlobBlocksOptions extends BlobServiceOptions { + private String leaseId; + private String snapshot; + private boolean committedList; + private boolean uncommittedList; + + /** + * Sets the optional server request timeout value associated with this + * {@link ListBlobBlocksOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link ListBlobBlocksOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link ListBlobBlocksOptions} instance. + */ + @Override + public ListBlobBlocksOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link ListBlobBlocksOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets a lease ID value to match when listing the blocks of the blob. If + * set, the lease must be active and the value must match the lease ID set + * on the leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobBlocksOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link ListBlobBlocksOptions} instance. + */ + public ListBlobBlocksOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the snapshot timestamp value set in this + * {@link ListBlobBlocksOptions} instance. + * + * @return A {@link String} containing the snapshot timestamp value of the + * blob snapshot to list. + */ + public String getSnapshot() { + return snapshot; + } + + /** + * Sets the snapshot timestamp value used to identify the particular + * snapshot of the blob to list blocks for. The snapshot timestamp value is + * an opaque value returned by the server to identify a snapshot. When this + * option is set, only the list of committed blocks of the snapshot is + * returned. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobBlocksOptions} instance is passed as a parameter. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp value of + * the blob snapshot to list. + * @return A reference to this {@link ListBlobBlocksOptions} instance. + */ + public ListBlobBlocksOptions setSnapshot(String snapshot) { + this.snapshot = snapshot; + return this; + } + + /** + * Gets the flag value indicating whether to return the committed blocks of + * the blob set in this {@link ListBlobBlocksOptions} instance. + * + * @return A boolean flag value indicating whether to return + * the committed blocks of the blob. + */ + public boolean isCommittedList() { + return committedList; + } + + /** + * Sets a flag indicating whether to return the committed blocks of the blob + * in the response to the list blob blocks request. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobBlocksOptions} instance is passed as a parameter. + * + * @param committedList + * Set to true to return the committed blocks of the + * blob; otherwise, false. + * @return A reference to this {@link ListBlobBlocksOptions} instance. + */ + public ListBlobBlocksOptions setCommittedList(boolean committedList) { + this.committedList = committedList; + return this; + } + + /** + * Gets the flag value indicating whether to return the uncommitted blocks + * of the blob set in this {@link ListBlobBlocksOptions} instance. + * + * @return A boolean flag value indicating whether to return + * the uncommitted blocks of the blob. + */ + public boolean isUncommittedList() { + return uncommittedList; + } + + /** + * Sets a flag indicating whether to return the uncommitted blocks of the + * blob in the response to the list blob blocks request. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobBlocksOptions} instance is passed as a parameter. + * + * @param uncommittedList + * Set to true to return the uncommitted blocks of + * the blob; otherwise, false. + * @return A reference to this {@link ListBlobBlocksOptions} instance. + */ + public ListBlobBlocksOptions setUncommittedList(boolean uncommittedList) { + this.uncommittedList = uncommittedList; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksResult.java new file mode 100644 index 0000000000000..2c025b6cd2f20 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksResult.java @@ -0,0 +1,280 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.core.pipeline.Base64StringAdapter; + +/** + * A wrapper class for the response returned from a Blob Service REST API Get + * Block List operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobBlocks(String, String)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobBlocks(String, String, ListBlobBlocksOptions)}. + *

+ * See the Get + * Block List documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +@XmlRootElement(name = "BlockList") +public class ListBlobBlocksResult { + private Date lastModified; + private String etag; + private String contentType; + private long contentLength; + private List committedBlocks = new ArrayList(); + private List uncommittedBlocks = new ArrayList(); + + /** + * Gets the last modified time of the block blob. This value is returned + * only if the blob has committed blocks. + *

+ * Any operation that modifies the blob, including updates to the blob's + * metadata or properties, changes the last modified time of the blob. This + * value can be used in an access condition when updating or deleting a blob + * to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the blob from + * the Last-Modified header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the ETag of the blob. This value is returned only if the blob has + * committed blocks. + *

+ * This value can be used in an access condition when updating or deleting a + * blob to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the blob from the + * ETag header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the MIME content type of the blob. This value defaults to + * application/xml. + * + * @return A {@link String} containing the MIME content type value for the + * blob. + */ + public String getContentType() { + return contentType; + } + + /** + * Reserved for internal use. Sets the MIME content type of the blob from + * the Content-Type header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param contentType + * A {@link String} containing the MIME content type value for + * the blob. + */ + public void setContentType(String contentType) { + this.contentType = contentType; + } + + /** + * Gets the size of the blob in bytes. For blobs with no committed blocks, + * this value is 0. + * + * @return The size of the blob in bytes. + */ + public long getContentLength() { + return contentLength; + } + + /** + * Reserved for internal use. Sets the content length of the blob from the + * x-ms-blob-content-length header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param contentLength + * The size of the blob in bytes. + */ + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + /** + * Gets a list of the committed blocks of the blob. This list may be empty + * if no blocks have been committed or if committed blocks were not + * specified in the request. + * + * @return A {@link List} of {@link Entry} instances representing the + * committed blocks of the blob. + */ + @XmlElementWrapper(name = "CommittedBlocks") + @XmlElement(name = "Block") + public List getCommittedBlocks() { + return committedBlocks; + } + + /** + * Reserved for internal use. Sets the list of the committed blocks of the + * blob from the Block elements in the + * CommittedBlocks element of the + * BlockList element in the response body returned by the + * server. + * + * @param committedBlocks + * A {@link List} of {@link Entry} instances representing the + * committed blocks of the blob. + */ + public void setCommittedBlocks(List committedBlocks) { + this.committedBlocks = committedBlocks; + } + + /** + * Gets a list of the uncommitted blocks of the blob. This list may be empty + * if no uncommitted blocks are associated with the blob, or if uncommitted + * blocks were not specified in the {@link ListBlobBlocksOptions options} + * parameter of the request. + * + * @return A {@link List} of {@link Entry} instances representing the + * uncommitted blocks of the blob. + */ + @XmlElementWrapper(name = "UncommittedBlocks") + @XmlElement(name = "Block") + public List getUncommittedBlocks() { + return uncommittedBlocks; + } + + /** + * Reserved for internal use. Sets the list of the uncommitted blocks of the + * blob from the Block elements in the + * UncommittedBlocks element of the + * BlockList element in the response body returned by the + * server. + * + * @param uncommittedBlocks + * A {@link List} of {@link Entry} instances representing the + * uncommitted blocks of the blob. + */ + public void setUncommittedBlocks(List uncommittedBlocks) { + this.uncommittedBlocks = uncommittedBlocks; + } + + /** + * The class for an entry in a list of blocks, representing a committed or + * uncommitted block. + */ + public static class Entry { + private String blockId; + private long blockLength; + + /** + * Gets the client-specified block ID for a block list entry. + * + * @return A {@link String} containing the client-specified block ID for + * a block. + */ + @XmlElement(name = "Name") + @XmlJavaTypeAdapter(Base64StringAdapter.class) + public String getBlockId() { + return blockId; + } + + /** + * Reserved for internal use. Sets the client-specified block ID for a + * block list entry from the Name element in the + * Block element in the list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param blockId + * A {@link String} containing the client-specified block ID + * for the block. + */ + public void setBlockId(String blockId) { + this.blockId = blockId; + } + + /** + * Gets the length in bytes of a block list entry. + * + * @return The length of the block in bytes. + */ + @XmlElement(name = "Size") + public long getBlockLength() { + return blockLength; + } + + /** + * Reserved for internal use. Sets the length in bytes of a block list + * entry from the Size element in the + * Block element in the list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param blockLength + * The length of the block in bytes. + */ + public void setBlockLength(long blockLength) { + this.blockLength = blockLength; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsOptions.java new file mode 100644 index 0000000000000..b928d33abfd06 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsOptions.java @@ -0,0 +1,201 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobRegions(String, String, ListBlobRegionsOptions) + * listBlobRegions} request. These options include an optional server timeout + * for the operation, the lease ID if the blob has an active lease, the snapshot + * timestamp to get the valid page ranges of a snapshot, the start offset and/or + * end offset to use to narrow the returned valid page range results, and any + * access conditions for the request. + */ +public class ListBlobRegionsOptions extends BlobServiceOptions { + private String leaseId; + private String snapshot; + private Long rangeStart; + private Long rangeEnd; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link ListBlobRegionsOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link ListBlobRegionsOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link ListBlobRegionsOptions} instance. + */ + @Override + public ListBlobRegionsOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link ListBlobRegionsOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets an optional lease ID value to match when getting the valid page + * ranges of the blob. If set, the lease must be active and the value must + * match the lease ID set on the leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobRegionsOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link ListBlobRegionsOptions} instance. + */ + public ListBlobRegionsOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the snapshot timestamp value set in this + * {@link ListBlobRegionsOptions} instance. + * + * @return A {@link String} containing the snapshot timestamp value of the + * blob snapshot to get valid page ranges for. + */ + public String getSnapshot() { + return snapshot; + } + + /** + * Sets an optional snapshot timestamp value used to identify the particular + * snapshot of the blob to get valid page ranges for. The snapshot timestamp + * value is an opaque value returned by the server to identify a snapshot. + * When this option is set, only the valid page ranges of the snapshot are + * returned. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobRegionsOptions} instance is passed as a parameter. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp value of + * the blob snapshot to get valid page ranges for. + * @return A reference to this {@link ListBlobRegionsOptions} instance. + */ + public ListBlobRegionsOptions setSnapshot(String snapshot) { + this.snapshot = snapshot; + return this; + } + + /** + * Gets the beginning byte offset value of the valid page ranges to return + * set in this {@link ListBlobRegionsOptions} instance. + * + * @return The beginning offset value in bytes for the valid page ranges to + * return. + */ + public Long getRangeStart() { + return rangeStart; + } + + /** + * Sets an optional beginning byte offset value of the valid page ranges to + * return for the request, inclusive. + *

+ * If the range end is not set, the response includes valid page ranges from + * the rangeStart value to the end of the blob. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobRegionsOptions} instance is passed as a parameter. + * + * @param rangeStart + * The beginning offset value in bytes for the valid page ranges + * to return, inclusive. + * @return A reference to this {@link ListBlobRegionsOptions} instance. + */ + public ListBlobRegionsOptions setRangeStart(Long rangeStart) { + this.rangeStart = rangeStart; + return this; + } + + /** + * Gets the ending byte offset value for the valid page ranges to return set + * in this {@link ListBlobRegionsOptions} instance. + * + * @return The ending offset value in bytes for the valid page ranges to + * return. + */ + public Long getRangeEnd() { + return rangeEnd; + } + + /** + * Sets an optional ending byte offset value of the valid page ranges to + * return for the request, inclusive. + *

+ * If the range start is not set, this value is ignored and the response + * includes valid page ranges from the entire blob. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobRegionsOptions} instance is passed as a parameter. + * + * @param rangeEnd + * The ending offset value in bytes for the valid page ranges to + * return, inclusive. + * @return A reference to this {@link ListBlobRegionsOptions} instance. + */ + public ListBlobRegionsOptions setRangeEnd(Long rangeEnd) { + this.rangeEnd = rangeEnd; + return this; + } + + /** + * Gets the access conditions set in this {@link ListBlobRegionsOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets optional access conditions for getting the valid page ranges of the + * blob. The operation will return an error if the access conditions are not + * met. + *

+ * Note that this value only affects calls made on methods where this + * {@link ListBlobRegionsOptions} instance is passed as a parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link ListBlobRegionsOptions} instance. + */ + public ListBlobRegionsOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsResult.java new file mode 100644 index 0000000000000..8cd8a58cd8603 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsResult.java @@ -0,0 +1,151 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * A wrapper class for the response returned from a Blob Service REST API Get + * Page Ranges operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobRegions(String, String, ListBlobRegionsOptions)}. + *

+ * See the Get + * Page Ranges documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +@XmlRootElement(name = "PageList") +public class ListBlobRegionsResult { + private Date lastModified; + private String etag; + private long contentLength; + private List pageRanges; + + /** + * Gets the last modified time of the blob. + *

+ * Any operation that modifies the blob, including updates to the blob's + * metadata or properties, changes the last modified time of the blob. This + * value can be used in an access condition when updating or deleting a blob + * to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the blob from + * the Last-Modified header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the ETag of the blob. + *

+ * This value can be used in an access condition when updating or deleting a + * blob to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the blob from the + * ETag header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the size of the blob in bytes. + * + * @return The size of the blob in bytes. + */ + public long getContentLength() { + return contentLength; + } + + /** + * Reserved for internal use. Sets the content length of the blob from the + * x-ms-blob-content-length header returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param contentLength + * The size of the blob in bytes. + */ + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + /** + * Gets the list of non-overlapping valid page ranges in the blob that match + * the parameters of the request, sorted by increasing address page range. + * + * @return A {@link List} of {@link PageRange} instances containing the + * valid page ranges for the blob. + */ + @XmlElement(name = "PageRange") + public List getPageRanges() { + return pageRanges; + } + + /** + * Reserved for internal use. Sets the list of valid page ranges in the blob + * that match the parameters of the request from the + * PageRange elements of the PageList + * element returned by the server in the response body. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param pageRanges + * A {@link List} of {@link PageRange} instances containing the + * valid page ranges for the blob. + */ + public void setPageRanges(List pageRanges) { + this.pageRanges = pageRanges; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsOptions.java new file mode 100644 index 0000000000000..19cfc8e1a0f0c --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsOptions.java @@ -0,0 +1,316 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String, ListBlobsOptions)} request. These + * options include a server response timeout for the request, a prefix for blobs + * to match, a marker to continue a list operation, a maximum number of results + * to return with one list operation, a delimiter for structuring virtual blob + * hierarchies, and whether to include blob metadata, blob snapshots, and + * uncommitted blobs in the results. + */ +public class ListBlobsOptions extends BlobServiceOptions { + private String prefix; + private String marker; + private int maxResults; + private String delimiter; + private boolean includeMetadata; + private boolean includeSnapshots; + private boolean includeUncommittedBlobs; + + /** + * Sets the optional server request timeout value associated with this + * {@link ListBlobsOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link ListBlobsOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link ListBlobsOptions} instance. + */ + @Override + public ListBlobsOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the prefix filter associated with this {@link ListBlobsOptions} + * instance. This value is used to return only blobs beginning with the + * prefix from the container in methods where this {@link ListBlobsOptions} + * instance is passed as a parameter. + * + * @return A {@link String} containing the prefix used to filter the blob + * names returned, if any. + */ + public String getPrefix() { + return prefix; + } + + /** + * Sets the optional blob name prefix filter value to use in a request. If + * this value is set, the server will return only blob names that match the + * prefix value in the response. + *

+ * The prefix value only affects calls made on methods where this + * {@link ListBlobsOptions} instance is passed as a parameter. + * + * @param prefix + * A {@link String} containing a prefix to use to filter the blob + * names returned. + */ + public ListBlobsOptions setPrefix(String prefix) { + this.prefix = prefix; + return this; + } + + /** + * Gets the marker value set in this {@link ListBlobsOptions} instance. If + * this value is set, the server will return blob names beginning at the + * specified marker in the response. + * + * @return A {@link String} containing the marker value to use to specify + * the beginning of the request results, if any. + */ + public String getMarker() { + return marker; + } + + /** + * Sets the optional marker value to use in a request. If this value is set, + * the server will return blob names beginning at the specified marker in + * the response. Leave this value unset for an initial request. + *

+ * The List Blobs operation returns a marker value in a + * NextMarker element if the blob list returned is not + * complete. The marker value may then be used in a subsequent call to + * request the next set of blob list items. The marker value is opaque to + * the client. + *

+ * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method on a + * {@link ListBlobsResult} instance to get the marker value to set on a + * {@link ListBlobsOptions} instance using a call to this method. Pass the + * {@link ListBlobsOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String, ListBlobsOptions)} call to get the + * next portion of the blob list. + *

+ * The marker value only affects calls made on methods where this + * {@link ListBlobsOptions} instance is passed as a parameter. + * + * @param marker + * A {@link String} containing the marker value to use to specify + * the beginning of the request results. + * @return A reference to this {@link ListBlobsOptions} instance. + */ + public ListBlobsOptions setMarker(String marker) { + this.marker = marker; + return this; + } + + /** + * Gets the value of the maximum number of results to return set in this + * {@link ListBlobsOptions} instance. + * + * @return The maximum number of results to return. If the value is zero, + * the server will return up to 5,000 items. + */ + public int getMaxResults() { + return maxResults; + } + + /** + * Sets the optional maximum number of results to return for a request. If + * this value is set, the server will return up to this number of blob and + * blob prefix results in the response. If a value is not specified, or a + * value greater than 5,000 is specified, the server will return up to 5,000 + * items. + *

+ * If there are more blobs and blob prefixes that can be returned than this + * maximum, the server returns a marker value in a + * NextMarker element in the response. The marker value may + * then be used in a subsequent call to request the next set of blob list + * items. The marker value is opaque to the client. + *

+ * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method on a + * {@link ListBlobsResult} instance to get the marker value to set on a + * {@link ListBlobsOptions} instance using a call to + * {@link ListBlobsOptions#setMarker(String)}. Pass the + * {@link ListBlobsOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String, ListBlobsOptions)} call to get the + * next portion of the blob list. + *

+ * The maxResults value only affects calls made on methods where + * this {@link ListBlobsOptions} instance is passed as a parameter. + * + * @param maxResults + * The maximum number of results to return. + * @return A reference to this {@link ListBlobsOptions} instance. + */ + public ListBlobsOptions setMaxResults(int maxResults) { + this.maxResults = maxResults; + return this; + } + + /** + * Gets the value of the delimiter to use for grouping virtual blob + * hierarchy set in this {@link ListBlobsOptions} instance. + * + * @return A {@link String} containing the delimiter value, if any. + */ + public String getDelimiter() { + return delimiter; + } + + /** + * Sets the value of the optional delimiter to use for grouping in a virtual + * blob hierarchy. + *

+ * When the request includes this optional parameter, the operation returns + * a blob prefix in a BlobPrefix element in the response + * that acts as a placeholder for all blobs whose names begin with the same + * substring up to the appearance of the delimiter character. The delimiter + * may be a single character or a string. + *

+ * The delimiter parameter enables the caller to traverse the blob + * namespace by using a user-configured delimiter. In this way, you can + * traverse a virtual hierarchy of blobs as though it were a file system. + * The delimiter is a string that may be one or more characters long. When + * the request includes this parameter, the operation response includes one + * BlobPrefix element for each set of blobs whose names + * begin with a common substring up to the first appearance of the delimiter + * string that comes after any prefix specified for the request. The value + * of the BlobPrefix element is + * substring+delimiter, where substring is the + * common substring that begins one or more blob names, and + * delimiter is the value of the delimiter parameter. + *

+ * The BlobPrefix elements in the response are accessed + * with the {@link ListBlobsResult#getBlobPrefixes()} method. You can use + * each value in the list returned to make a list blobs request for the + * blobs that begin with that blob prefix value, by specifying the value as + * the prefix option with a call to the + * {@link ListBlobsOptions#setPrefix(String) setPrefix} method on a + * {@link ListBlobsOptions} instance passed as a parameter to the request. + *

+ * Note that each blob prefix returned in the response counts toward the + * maximum number of blob results, just as each blob does. + *

+ * Note that if a delimiter is set, you cannot include snapshots. A request + * that includes both returns an InvalidQueryParameter error (HTTP status + * code 400 - Bad Request), which causes a {@link com.microsoft.windowsazure.exception.ServiceException} to be + * thrown. + *

+ * The delimiter value only affects calls made on methods where + * this {@link ListBlobsOptions} instance is passed as a parameter. + * + * @param delimiter + * A {@link String} containing the delimiter value to use for + * grouping virtual blob hierarchy. + * @return A reference to this {@link ListBlobsOptions} instance. + */ + public ListBlobsOptions setDelimiter(String delimiter) { + this.delimiter = delimiter; + return this; + } + + /** + * Gets the value of a flag indicating whether to include blob metadata with + * a response set in this {@link ListBlobsOptions} instance. + * + * @return A value of true to include blob metadata with a + * response, otherwise, false. + */ + public boolean isIncludeMetadata() { + return includeMetadata; + } + + /** + * Sets the value of an optional flag indicating whether to include blob + * metadata with a response. + * + * @param includeMetadata + * Set a value of true to include blob metadata with + * a response, otherwise, false. + * @return A reference to this {@link ListBlobsOptions} instance. + */ + public ListBlobsOptions setIncludeMetadata(boolean includeMetadata) { + this.includeMetadata = includeMetadata; + return this; + } + + /** + * Gets the value of a flag indicating whether to include blob snapshots + * with a response set in this {@link ListBlobsOptions} instance. + * + * @return A value of true to include blob metadata with a + * response, otherwise, false. + */ + public boolean isIncludeSnapshots() { + return includeSnapshots; + } + + /** + * Sets the value of an optional flag indicating whether to include blob + * snapshots with a response. + *

+ * Note that if this flag is set, you cannot set a delimiter. A request that + * includes both returns an InvalidQueryParameter error (HTTP status code + * 400 - Bad Request), which causes a {@link com.microsoft.windowsazure.exception.ServiceException} to be thrown. + * + * @param includeSnapshots + * Set a value of true to include blob metadata with + * a response, otherwise, false. + * @return A reference to this {@link ListBlobsOptions} instance. + */ + public ListBlobsOptions setIncludeSnapshots(boolean includeSnapshots) { + this.includeSnapshots = includeSnapshots; + return this; + } + + /** + * Gets the value of a flag indicating whether to include uncommitted blobs + * with a response set in this {@link ListBlobsOptions} instance. + * + * @return A value of true to include uncommitted blobs with a + * response, otherwise, false. + */ + public boolean isIncludeUncommittedBlobs() { + return includeUncommittedBlobs; + } + + /** + * Sets the value of an optional flag indicating whether to include + * uncommitted blobs with a response. Uncommitted blobs are blobs for which + * blocks have been uploaded, but which have not been committed with a + * request to + * {@link com.microsoft.windowsazure.services.blob.BlobContract#commitBlobBlocks(String, String, BlockList)} or + * {@link com.microsoft.windowsazure.services.blob.BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions)} + * . + * + * @param includeUncommittedBlobs + * Set a value of true to include uncommitted blobs + * with a response, otherwise, false. + * @return A reference to this {@link ListBlobsOptions} instance. + */ + public ListBlobsOptions setIncludeUncommittedBlobs( + boolean includeUncommittedBlobs) { + this.includeUncommittedBlobs = includeUncommittedBlobs; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsResult.java new file mode 100644 index 0000000000000..0a967a92b342b --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsResult.java @@ -0,0 +1,590 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlElementRefs; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.services.blob.implementation.MetadataAdapter; + +/** + * A wrapper class for the response returned from a Blob Service REST API List + * Blobs operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String, ListBlobsOptions)}. + *

+ * See the List Blobs documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +@XmlRootElement(name = "EnumerationResults") +public class ListBlobsResult { + private List blobPrefixes = new ArrayList(); + private List blobs = new ArrayList(); + private String containerName; + private String prefix; + private String marker; + private String nextMarker; + private String delimiter; + private int maxResults; + + /** + * Gets the list of ListBlobsEntry entries generated from the + * server response to the list blobs request. + * + * @return The {@link List} of {@link ListBlobsEntry} entries generated from + * the server response to the list blobs request. + */ + @XmlElementWrapper(name = "Blobs") + @XmlElementRefs({ + @XmlElementRef(name = "BlobPrefix", type = BlobPrefixEntry.class), + @XmlElementRef(name = "Blob", type = BlobEntry.class) }) + public List getEntries() { + ArrayList result = new ArrayList(); + result.addAll(this.blobPrefixes); + result.addAll(this.blobs); + return result; + } + + /** + * Sets the lists of blob entries and blob prefix entries from a common list + * of ListBlobsEntry entries generated from the server response + * to the list blobs request. + * + * @param entries + * The {@link List} of {@link ListBlobsEntry} entries to set the + * lists of blob entries and blob prefix entries from. + */ + public void setEntries(List entries) { + // Split collection into "blobs" and "blobPrefixes" collections + this.blobPrefixes = new ArrayList(); + this.blobs = new ArrayList(); + + for (ListBlobsEntry entry : entries) { + if (entry instanceof BlobPrefixEntry) { + this.blobPrefixes.add((BlobPrefixEntry) entry); + } else if (entry instanceof BlobEntry) { + this.blobs.add((BlobEntry) entry); + } + } + } + + /** + * Gets the list of blob prefix entries that satisfied the request. Each + * BlobPrefixEntry represents one or more blobs that have a + * common substring up to the delimiter specified in the request options. + *

+ * This list may contain only a portion of the blob prefix entries that + * satisfy the request, limited by a server timeout or a maximum results + * parameter. If there are more blob entries and blob prefix entries that + * could satisfy the result, the server returns a + * NextMarker element with the response. + *

+ * The delimiter option enables the caller to traverse the blob namespace by + * using a user-configured delimiter. In this way, you can traverse a + * virtual hierarchy of blobs as though it were a file system. The delimiter + * may be a single character or a string. When the request includes the + * delimiter option, the response includes a BlobPrefixEntry in + * place of all blobs whose names begin with the same substring up to the + * appearance of the delimiter string. The value of + * {@link BlobPrefixEntry#getName()} is substring+ + * delimiter , where substring is the common substring + * that begins one or more blob names, and delimiter is the value + * of the delimiter option. + *

+ * To move down a level in the virtual hierarchy, you can use the + * {@link BlobPrefixEntry#getName()} method to get the prefix value to use + * to make a subsequent call to list blobs that begin with this prefix. + *

+ * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to + * get this value and pass it as a marker option to a subsequent list blobs + * request to get the next set of blob results. + *

+ * Blobs are listed in alphabetical order in the response body, with + * upper-case letters listed first. + * + * @return A {@link List} of {@link BlobEntry} instances for the blobs that + * satisfied the request. + */ + public List getBlobPrefixes() { + return this.blobPrefixes; + } + + /** + * Gets the list of blobs that satisfied the request from the response. This + * list may contain only a portion of the blobs that satisfy the request, + * limited by a server timeout or a maximum results parameter. If there are + * more blobs or blob prefixes that could satisfy the result, the server + * returns a NextMarker element with the response. + *

+ * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to + * get this value and pass it as a marker option to a subsequent list blobs + * request to get the next set of blob results. + *

+ * Blobs are listed in alphabetical order in the response body, with + * upper-case letters listed first. + * + * @return A {@link List} of {@link BlobEntry} instances for the blobs that + * satisfied the request. + */ + public List getBlobs() { + return this.blobs; + } + + /** + * Gets the value of the filter used to return only blobs beginning with the + * prefix. This value is not set if a prefix was not specified in the list + * blobs request. + * + * @return A {@link String} containing the prefix used to filter the blob + * names returned, if any. + */ + @XmlElement(name = "Prefix") + public String getPrefix() { + return prefix; + } + + /** + * Reserved for internal use. Sets the filter used to return only blobs + * beginning with the prefix from the Prefix element + * returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param prefix + * A {@link String} containing the prefix used to filter the blob + * names returned, if any. + */ + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + /** + * Gets the value of the marker that was used to specify the beginning of + * the container list to return with the request. This value is not set if a + * marker was not specified in the request. + *

+ * The list blobs operation returns a marker value in a + * NextMarker element if the blob list returned is not + * complete. The marker value may then be used in a subsequent call to + * request the next set of blob list items. The marker value is opaque to + * the client. + *

+ * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to + * get the marker value to set on a {@link ListBlobsOptions} instance using + * a call to {@link ListBlobsOptions#setMarker(String)}. Pass the + * {@link ListBlobsOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String, ListBlobsOptions) listBlobs} call + * to get the next portion of the blob list. + * + * @return A {@link String} containing the marker used to specify the + * beginning of the blob list returned, if any. + */ + @XmlElement(name = "Marker") + public String getMarker() { + return marker; + } + + /** + * Reserved for internal use. Sets the marker used to specify the beginning + * of the blob list to return from the Marker element + * returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param marker + * A {@link String} containing the marker used to specify the + * beginning of the blob list returned. + */ + public void setMarker(String marker) { + this.marker = marker; + } + + /** + * Gets the next marker value needed to specify the beginning of the next + * portion of the blob list to return, if any was set in the response from + * the server. + *

+ * The list blobs operation returns a marker value in a + * NextMarker element if the blob list returned is not + * complete. The marker value may then be used in a subsequent call to + * request the next set of blob list items. The marker value is opaque to + * the client. + *

+ * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to + * get the marker value to set on a {@link ListBlobsOptions} instance using + * a call to {@link ListBlobsOptions#setMarker(String)}. Pass the + * {@link ListBlobsOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String, ListBlobsOptions) listBlobs} call + * to get the next portion of the blob list. + * + * @return A {@link String} containing the next marker value needed to + * specify the beginning of the next portion of the blob list to + * return, if any was set in the response from the server. + */ + @XmlElement(name = "NextMarker") + public String getNextMarker() { + return nextMarker; + } + + /** + * Reserved for internal use. Sets the next marker value needed to specify + * the beginning of the next portion of the blob list to return from the + * NextMarker element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param nextMarker + * A {@link String} containing the next marker value needed to + * specify the beginning of the next portion of the blob list to + * return. + */ + public void setNextMarker(String nextMarker) { + this.nextMarker = nextMarker; + } + + /** + * Gets the maximum results to return used to generate the response, if + * present. The number of entries returned in the response will not exceed + * this number, including all BlobPrefix elements. This + * value is not set if a maximum number was not specified in the request. If + * the request does not specify this parameter or specifies a value greater + * than 5,000, the server will return up to 5,000 items. If there are more + * blobs or blob prefixes that satisfy the request than this maximum value, + * the server will include a next marker value in the response, which can be + * used to get the remaining blobs with a subsequent request. + *

+ * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to + * get the marker value to set on a {@link ListBlobsOptions} instance using + * a call to {@link ListBlobsOptions#setMarker(String)}. Pass the + * {@link ListBlobsOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listBlobs(String, ListBlobsOptions) listBlobs} call + * to get the next portion of the blob list. + * + * @return The maximum results to return value in the response, if any. + */ + @XmlElement(name = "MaxResults") + public int getMaxResults() { + return maxResults; + } + + /** + * Reserved for internal use. Sets the maximum results to return value from + * the MaxResults element of the + * EnumerationResults element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param maxResults + * The maximum results to return value in the response, if any. + */ + public void setMaxResults(int maxResults) { + this.maxResults = maxResults; + } + + /** + * Gets the delimiter value used to generate the response, if present. When + * the request includes this parameter, the operation returns + * BlobPrefix elements in the response body that act as a + * placeholder for all blobs whose names begin with the same substring up to + * the appearance of the delimiter character. + * + * @return A {@link String} containing the delimiter value used as a request + * parameter. + */ + @XmlElement(name = "Delimiter") + public String getDelimiter() { + return delimiter; + } + + /** + * Reserved for internal use. Sets the delimiter value from the + * Delimiter element of the + * EnumerationResults element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param delimiter + * A {@link String} containing the delimiter value in the + * response, if any. + */ + public void setDelimiter(String delimiter) { + this.delimiter = delimiter; + } + + /** + * Gets the container URI. This value is returned in the + * ContainerName attribute of the + * EnumerationResults element returned in the response. + * + * @return A {@link String} containing the container URI. + */ + @XmlAttribute(name = "ContainerName") + public String getContainerName() { + return containerName; + } + + /** + * Reserved for internal use. Sets the container URI value from the + * ContainerName attribute of the + * EnumerationResults element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param containerName + * A {@link String} containing the container URI. + */ + public void setContainerName(String containerName) { + this.containerName = containerName; + } + + /** + * The abstract base class for Blob and BlobPrefix + * entries in the list of results returned in the response. + */ + public abstract static class ListBlobsEntry { + + } + + /** + * Represents a BlobPrefix element returned in the + * response. When the request includes a delimiter parameter, a single + * BlobPrefix element is returned in place of all blobs + * whose names begin with the same substring up to the appearance of the + * delimiter character. + */ + @XmlRootElement(name = "BlobPrefix") + public static class BlobPrefixEntry extends ListBlobsEntry { + private String name; + + /** + * Gets the value of the Name element within a + * BlobPrefix element returned in the response. The + * value of the element is substring+delimiter, where + * substring is the common substring that begins one or more + * blob names, and delimiter is the value of the delimiter + * parameter. + * + * @return A {@link String} containing the common substring that begins + * one or more blob names up to and including the delimiter + * specified in the request. + */ + @XmlElement(name = "Name") + public String getName() { + return name; + } + + /** + * Reserved for internal use. Sets the blob prefix name from the + * Name element in the BlobPrefix + * element in the Blobs list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param name + * A {@link String} containing the value of the + * Name element within a + * BlobPrefix element. + */ + public void setName(String name) { + this.name = name; + } + } + + /** + * Represents a Blob element returned in the response. A + * BlobEntry includes committed blobs, and can optionally + * include blob metadata, blob snapshots, and uncommitted blobs, depending + * on the request options set. + */ + @XmlRootElement(name = "Blob") + public static class BlobEntry extends ListBlobsEntry { + private String name; + private String url; + private String snapshot; + private HashMap metadata = new HashMap(); + private BlobProperties properties; + + /** + * Gets the value of the Name element within a + * Blob element returned in the response. The value of + * the element is the complete name of the blob, including any virtual + * hierarchy. + * + * @return A {@link String} containing the complete blob name. + */ + @XmlElement(name = "Name") + public String getName() { + return name; + } + + /** + * Reserved for internal use. Sets the blob name from the + * Name element in the Blob element in + * the Blobs list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param name + * A {@link String} containing the value of the + * Name element within a + * Blob element. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the value of the Url element within a + * Blob element returned in the response. The value of + * the element is the complete URI address of the blob, including any + * virtual hierarchy. + * + * @return A {@link String} containing the complete URI address of the + * blob. + */ + @XmlElement(name = "Url") + public String getUrl() { + return url; + } + + /** + * Reserved for internal use. Sets the blob URI address from the + * Uri element in the Blob element in + * the Blobs list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param url + * A {@link String} containing the complete URI address of + * the blob. + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * Gets a {@link BlobProperties} instance with the blob properties + * returned in the response. + * + * @return A {@link BlobProperties} instance with the blob properties + * returned in the response. + */ + @XmlElement(name = "Properties") + public BlobProperties getProperties() { + return properties; + } + + /** + * Reserved for internal use. Sets the blob properties from the + * Uri element in the Blob element in + * the Blobs list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param properties + * A {@link BlobProperties} instance with the blob properties + * returned in the response. + */ + public void setProperties(BlobProperties properties) { + this.properties = properties; + } + + /** + * Gets the snapshot timestamp value for a blob snapshot returned in the + * response. The value is set from the Snapshot element + * in the Blob element in the Blobs + * list in the response. Snapshots are included in the enumeration only + * if specified in the request options. Snapshots are listed from oldest + * to newest in the response. + * + * @return A {@link String} containing the snapshot timestamp of the + * blob snapshot. + */ + @XmlElement(name = "Snapshot") + public String getSnapshot() { + return snapshot; + } + + /** + * Reserved for internal use. Sets the blob snapshot timestamp from the + * Snapshot element in the Blob + * element in the Blobs list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param snapshot + * A {@link String} containing the snapshot timestamp of the + * blob snapshot. + */ + public void setSnapshot(String snapshot) { + this.snapshot = snapshot; + } + + /** + * Gets the blob's metadata collection set in the + * Metadata element in the Blob + * element in the Blobs list in the response. Metadata + * is included in the enumeration only if specified in the request + * options. + * + * @return A {@link HashMap} of name-value pairs of {@link String} + * containing the blob metadata set, if any. + */ + @XmlElement(name = "Metadata") + @XmlJavaTypeAdapter(MetadataAdapter.class) + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. Sets the blob metadata from the + * Metadata element in the Blob + * element in the Blobs list in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of name-value pairs of + * {@link String} containing the names and values of the blob + * metadata, if present. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersOptions.java new file mode 100644 index 0000000000000..624ed98828837 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersOptions.java @@ -0,0 +1,191 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers(ListContainersOptions) listContainers} + * request. These options include a server response timeout for the request, a + * container name prefix filter, a marker for continuing requests, the maximum + * number of results to return in a request, and whether to include container + * metadata in the results. Options that are not set will not be passed to the + * server with a request. + */ +public class ListContainersOptions extends BlobServiceOptions { + private String prefix; + private String marker; + private int maxResults; + private boolean includeMetadata; + + /** + * Sets the optional server request timeout value associated with this + * {@link ListContainersOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link ListContainersOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link ListContainersOptions} instance. + */ + @Override + public ListContainersOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the container name prefix filter value set in this + * {@link ListContainersOptions} instance. + * + * @return A {@link String} containing the container name prefix value, if + * any. + */ + public String getPrefix() { + return prefix; + } + + /** + * Sets the optional container name prefix filter value to use in a request. + * If this value is set, the server will return only container names that + * match the prefix value in the response. + *

+ * The prefix value only affects calls made on methods where this + * {@link ListContainersOptions} instance is passed as a parameter. + * + * @param prefix + * A {@link String} containing the container name prefix value to + * use to filter the request results. + * @return A reference to this {@link ListContainersOptions} instance. + */ + public ListContainersOptions setPrefix(String prefix) { + this.prefix = prefix; + return this; + } + + /** + * Gets the marker value set in this {@link ListContainersOptions} instance. + * + * @return A {@link String} containing the marker value to use to specify + * the beginning of the request results. + */ + public String getMarker() { + return marker; + } + + /** + * Sets the optional marker value to use in a request. If this value is set, + * the server will return container names beginning at the specified marker + * in the response. + *

+ * The List Containers operation returns a marker value in a + * NextMarker element if the container list returned is not + * complete. The marker value may then be used in a subsequent call to + * request the next set of container list items. The marker value is opaque + * to the client. + *

+ * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method + * on a {@link ListContainersResult} instance to get the marker value to set + * on a {@link ListContainersOptions} instance using a call to this method. + * Pass the {@link ListContainersOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers(ListContainersOptions)} call to get + * the next portion of the container list. + *

+ * The marker value only affects calls made on methods where this + * {@link ListContainersOptions} instance is passed as a parameter. + * + * @param marker + * A {@link String} containing the marker value to use to specify + * the beginning of the request results. + * @return A reference to this {@link ListContainersOptions} instance. + */ + public ListContainersOptions setMarker(String marker) { + this.marker = marker; + return this; + } + + /** + * Gets the value of the maximum number of results to return set in this + * {@link ListContainersOptions} instance. + * + * @return The maximum number of results to return. + */ + public int getMaxResults() { + return maxResults; + } + + /** + * Sets the optional maximum number of results to return for a request. If + * this value is set, the server will return up to this number of results in + * the response. If a value is not specified, or a value greater than 5,000 + * is specified, the server will return up to 5,000 items. + *

+ * If there are more containers than this value that can be returned, the + * server returns a marker value in a NextMarker element in + * the response. The marker value may then be used in a subsequent call to + * request the next set of container list items. The marker value is opaque + * to the client. + *

+ * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method + * on a {@link ListContainersResult} instance to get the marker value to set + * on a {@link ListContainersOptions} instance using a call to + * {@link ListContainersOptions#setMarker(String)}. Pass the + * {@link ListContainersOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers(ListContainersOptions)} call to get + * the next portion of the container list. + *

+ * The maxResults value only affects calls made on methods where + * this {@link ListContainersOptions} instance is passed as a parameter. + * + * @param maxResults + * The maximum number of results to return. + * @return A reference to this {@link ListContainersOptions} instance. + */ + public ListContainersOptions setMaxResults(int maxResults) { + this.maxResults = maxResults; + return this; + } + + /** + * Gets the value of a flag set in this {@link ListContainersOptions} + * instance indicating whether to include container metadata in the response + * to the request. + * + * @return true to include container metadata in the response + * to the request. + */ + public boolean isIncludeMetadata() { + return includeMetadata; + } + + /** + * Sets the value of an optional flag indicating whether to include + * container metadata with the response to the request. + *

+ * The includeMetadata value only affects calls made on methods + * where this {@link ListContainersOptions} instance is passed as a + * parameter. + * + * @param includeMetadata + * Set to true to include container metadata in the + * response to the request. + * @return A reference to this {@link ListContainersOptions} instance. + */ + public ListContainersOptions setIncludeMetadata(boolean includeMetadata) { + this.includeMetadata = includeMetadata; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersResult.java new file mode 100644 index 0000000000000..17421846bb3e4 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersResult.java @@ -0,0 +1,449 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.core.RFC1123DateAdapter; +import com.microsoft.windowsazure.services.blob.implementation.MetadataAdapter; + +/** + * A wrapper class for the response returned from a Blob Service REST API List + * Containers operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers(ListContainersOptions)}. + *

+ * See the List Containers documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +@XmlRootElement(name = "EnumerationResults") +public class ListContainersResult { + private List containers; + private String accountName; + private String prefix; + private String marker; + private String nextMarker; + private int maxResults; + + /** + * Gets the container list returned in the response. + * + * @return A {@link List} of {@link Container} instances representing the + * blob containers returned by the request. + */ + @XmlElementWrapper(name = "Containers") + @XmlElement(name = "Container") + public List getContainers() { + return containers; + } + + /** + * Reserved for internal use. Sets the container list from the + * Containers element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param value + * A {@link List} of {@link Container} instances representing the + * blob containers returned by the request. + */ + public void setContainers(List value) { + this.containers = value; + } + + /** + * Gets the base URI for invoking Blob Service REST API operations on the + * storage account. + * + * @return A {@link String} containing the base URI for Blob Service REST + * API operations on the storage account. + */ + @XmlAttribute(name = "AccountName") + public String getAccountName() { + return accountName; + } + + /** + * Reserved for internal use. Sets the base URI for invoking Blob Service + * REST API operations on the storage account from the value of the + * AccountName attribute of the + * EnumerationResults element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param accountName + * A {@link String} containing the base URI for Blob Service REST + * API operations on the storage account. + */ + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + /** + * Gets the value of the filter used to return only containers beginning + * with the prefix. This value is not set if a prefix was not specified in + * the list containers request. + * + * @return A {@link String} containing the prefix used to filter the + * container names returned, if any. + */ + @XmlElement(name = "Prefix") + public String getPrefix() { + return prefix; + } + + /** + * Reserved for internal use. Sets the filter used to return only containers + * beginning with the prefix from the Prefix element + * returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param prefix + * A {@link String} containing the prefix used to filter the + * container names returned, if any. + */ + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + /** + * Gets the value of the marker that was used to specify the beginning of + * the container list to return with the request. This value is not set if a + * marker was not specified in the request. + *

+ * The List Containers operation returns a marker value in a + * NextMarker element if the container list returned is not + * complete. The marker value may then be used in a subsequent call to + * request the next set of container list items. The marker value is opaque + * to the client. + *

+ * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method + * to get the marker value to set on a {@link ListContainersOptions} + * instance using a call to {@link ListContainersOptions#setMarker(String)}. + * Pass the {@link ListContainersOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers(ListContainersOptions)} call to get + * the next portion of the container list. + * + * @return A {@link String} containing the marker used to specify the + * beginning of the container list returned, if any. + */ + @XmlElement(name = "Marker") + public String getMarker() { + return marker; + } + + /** + * Reserved for internal use. Sets the marker used to specify the beginning + * of the container list to return from the Marker element + * returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param marker + * A {@link String} containing the marker used to specify the + * beginning of the container list returned. + */ + public void setMarker(String marker) { + this.marker = marker; + } + + /** + * Gets the next marker value needed to specify the beginning of the next + * portion of the container list to return, if any was set in the response + * from the server. + *

+ * The List Containers operation returns a marker value in a + * NextMarker element if the container list returned is not + * complete. The marker value may then be used in a subsequent call to + * request the next set of container list items. The marker value is opaque + * to the client. + *

+ * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method + * to get the marker value to set on a {@link ListContainersOptions} + * instance using a call to {@link ListContainersOptions#setMarker(String)}. + * Pass the {@link ListContainersOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers(ListContainersOptions)} call to get + * the next portion of the container list. + * + * @return A {@link String} containing the next marker value needed to + * specify the beginning of the next portion of the container list + * to return, if any was set in the response from the server. + */ + @XmlElement(name = "NextMarker") + public String getNextMarker() { + return nextMarker; + } + + /** + * Reserved for internal use. Sets the next marker value needed to specify + * the beginning of the next portion of the container list to return from + * the NextMarker element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param nextMarker + * A {@link String} containing the next marker value needed to + * specify the beginning of the next portion of the container + * list to return. + */ + public void setNextMarker(String nextMarker) { + this.nextMarker = nextMarker; + } + + /** + * Gets the maximum number of container list items to return that was + * specified in the request. The number of containers returned in a single + * response will not exceed this value. This value is not set if a maximum + * number was not specified in the request. If there are more containers + * that satisfy the request than this maximum value, the server will include + * a next marker value in the response, which can be used to get the + * remaining containers with a subsequent request. + *

+ * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method + * to get the marker value to set on a {@link ListContainersOptions} + * instance using a call to {@link ListContainersOptions#setMarker(String)}. + * Pass the {@link ListContainersOptions} instance as a parameter to a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#listContainers(ListContainersOptions)} call to get + * the next portion of the container list. + * + * @return The maximum number of container list items to return that was + * specified in the request, if any. + */ + @XmlElement(name = "MaxResults") + public int getMaxResults() { + return maxResults; + } + + /** + * Reserved for internal use. Sets the maximum number of container list + * items to return that was specified in the request from the + * MaxResults element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param maxResults + * The maximum number of container list items to return that was + * specified in the request, if any. + */ + public void setMaxResults(int maxResults) { + this.maxResults = maxResults; + } + + /** + * Represents a container for blob storage returned by the server. A + * {@link Container} instance contains a copy of the container properties + * and metadata in the storage service as of the time the container list was + * requested. + */ + public static class Container { + private String name; + private String url; + private HashMap metadata = new HashMap(); + private ContainerProperties properties; + + /** + * Gets the name of the container. + * + * @return A {@link String} containing the name of the container. + */ + @XmlElement(name = "Name") + public String getName() { + return name; + } + + /** + * Reserved for internal use. Sets the name of the container from the + * Name element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param name + * A {@link String} containing the name of the container. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the URI of the container. + * + * @return A {@link String} containing the URI of the container. + */ + @XmlElement(name = "Url") + public String getUrl() { + return url; + } + + /** + * Reserved for internal use. Sets the URI of the container from the + * Url element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param url + * A {@link String} containing the URI of the container. + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * Gets the container properties. The container properties include the + * last modified time and an ETag value. + * + * @return A {@link ContainerProperties} instance containing the + * properties associated with the container. + */ + @XmlElement(name = "Properties") + public ContainerProperties getProperties() { + return properties; + } + + /** + * Reserved for internal use. Sets the container properties from the + * Properties element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param properties + * A {@link ContainerProperties} instance containing the + * properties associated with the container. + */ + public void setProperties(ContainerProperties properties) { + this.properties = properties; + } + + /** + * Gets the container metadata as a map of name and value pairs. The + * container metadata is for client use and is opaque to the server. + * + * @return A {@link java.util.HashMap} of key-value pairs of + * {@link String} containing the names and values of the + * container metadata. + */ + @XmlElement(name = "Metadata") + @XmlJavaTypeAdapter(MetadataAdapter.class) + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. Sets the container metadata from the + * Metadata element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of key-value pairs of + * {@link String} containing the names and values of the + * container metadata. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } + } + + /** + * Represents the properties of a container for blob storage returned by the + * server. A {@link ContainerProperties} instance contains a copy of the + * container properties in the storage service as of the time the container + * list was requested. + */ + public static class ContainerProperties { + private Date lastModified; + private String etag; + + /** + * Gets the last modifed time of the container. This value can be used + * when updating or deleting a container using an optimistic concurrency + * model to prevent the client from modifying data that has been changed + * by another client. + * + * @return A {@link java.util.Date} containing the last modified time of + * the container. + */ + @XmlElement(name = "Last-Modified") + @XmlJavaTypeAdapter(RFC1123DateAdapter.class) + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the + * container from the Last-Modified element returned in + * the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time + * of the container. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the ETag of the container. This value can be used when updating + * or deleting a container using an optimistic concurrency model to + * prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value + * for the container. + */ + @XmlElement(name = "Etag") + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the container from the + * ETag element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob + * Service REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value + * for the container. + */ + public void setEtag(String etag) { + this.etag = etag; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/PageRange.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/PageRange.java new file mode 100644 index 0000000000000..044b44cffb292 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/PageRange.java @@ -0,0 +1,152 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import javax.xml.bind.annotation.XmlElement; + +/** + * Represents the range of bytes in a single page within a page blob. + *

+ * For a page update operation, the page range can be up to 4 MB in size. For a + * page clear operation, the page range can be up to the value of the blob's + * full size. + *

+ * Pages are aligned with 512-byte boundaries. When specifying a page range, the + * start offset must be a modulus of 512 and the end offset must be a modulus of + * 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. + */ +public class PageRange { + private long start; + private long end; + + /** + * Default constructor. The start and end values must be set for this + * {@link PageRange} instance to be valid. + */ + public PageRange() { + } + + /** + * Creates a page range from the specified start and end byte offsets, + * inclusive. + *

+ * Pages are aligned with 512-byte boundaries. When specifying a page range, + * the start offset must be a modulus of 512 and the end offset must be a + * modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, + * etc. + * + * @param start + * The beginning offset value in bytes for the page range, + * inclusive. + * @param end + * The ending offset value in bytes for the page range, + * inclusive. + */ + public PageRange(long start, long end) { + this.start = start; + this.end = end; + } + + /** + * Gets the byte offset of the start of the page range within the blob, + * inclusive. + * + * @return The beginning offset value in bytes for the page range, + * inclusive. + */ + @XmlElement(name = "Start") + public long getStart() { + return start; + } + + /** + * Sets the byte offset of the start of the page range within the blob, + * inclusive. + *

+ * Pages are aligned with 512-byte boundaries. When specifying a page range, + * the start offset must be a modulus of 512 and the end offset must be a + * modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, + * etc. + * + * @param start + * The beginning offset value in bytes for the page range, + * inclusive. + * @return A reference to this {@link PageRange} instance. + */ + public PageRange setStart(long start) { + this.start = start; + return this; + } + + /** + * Gets the byte offset of the end of the page range within the blob, + * inclusive. + * + * @return The ending offset value in bytes for the page range, inclusive. + */ + @XmlElement(name = "End") + public long getEnd() { + return end; + } + + /** + * Sets the byte offset of the end of the page range within the blob, + * inclusive. + *

+ * Pages are aligned with 512-byte boundaries. When specifying a page range, + * the start offset must be a modulus of 512 and the end offset must be a + * modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, + * etc. + * + * @param end + * The ending offset value in bytes for the page range, + * inclusive. + * @return A reference to this {@link PageRange} instance. + */ + public PageRange setEnd(long end) { + this.end = end; + return this; + } + + /** + * Gets the size of the page range in bytes. + * + * @return The size of the page range in bytes. + */ + public long getLength() { + return end - start + 1; + } + + /** + * Sets the length of the page range in bytes. This updates the byte offset + * of the end of the page range to the start value plus the length specified + * by the value parameter. The length must be a positive multiple + * of 512 bytes. + *

+ * Pages are aligned with 512-byte boundaries. When specifying a page range, + * the start offset must be a modulus of 512 and the end offset must be a + * modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, + * etc. + * + * @param value + * The ending offset value in bytes for the page range, + * inclusive. + * @return A reference to this {@link PageRange} instance. + */ + public PageRange setLength(long value) { + this.end = this.start + value - 1; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ServiceProperties.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ServiceProperties.java new file mode 100644 index 0000000000000..778e5051ae6f1 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/ServiceProperties.java @@ -0,0 +1,419 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Represents the Blob service properties that can be set on a storage account, + * including Windows Azure Storage Analytics. This class is used by the + * {@link com.microsoft.windowsazure.services.blob.BlobContract#getServiceProperties()} method to return the service + * property values set on the storage account, and by the + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setServiceProperties(ServiceProperties)} and + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setServiceProperties(ServiceProperties, BlobServiceOptions)} + * methods to set the values of the service properties. + */ +@XmlRootElement(name = "StorageServiceProperties") +public class ServiceProperties { + private Logging logging = new Logging(); + private Metrics metrics = new Metrics(); + private String defaultServiceVersion; + + /** + * Gets the value of the logging options on the storage account. + * + * @return A {@link Logging} instance containing the logging options. + */ + @XmlElement(name = "Logging") + public Logging getLogging() { + return logging; + } + + /** + * Sets the value of the logging options on the storage account. + * + * @param logging + * A {@link Logging} instance containing the logging options. + * @return A reference to this {@link ServiceProperties} instance. + */ + public ServiceProperties setLogging(Logging logging) { + this.logging = logging; + return this; + } + + /** + * Gets the value of the metrics options on the storage account. + * + * @return A {@link Metrics} instance containing the metrics options. + */ + @XmlElement(name = "Metrics") + public Metrics getMetrics() { + return metrics; + } + + /** + * Sets the value of the metrics options on the storage account. + * + * @param metrics + * A {@link Metrics} instance containing the metrics options. + * @return A reference to this {@link ServiceProperties} instance. + */ + public ServiceProperties setMetrics(Metrics metrics) { + this.metrics = metrics; + return this; + } + + /** + * Gets the default service version string used for operations on the + * storage account. + * + * @return A {@link String} containing the default service version string + * used for operations on the storage account. + */ + @XmlElement(name = "DefaultServiceVersion") + public String getDefaultServiceVersion() { + return defaultServiceVersion; + } + + /** + * Sets the default service version string used for operations on the + * storage account. This value is optional for a set service properties + * request. Allowed values include version 2009-09-19 and more recent + * versions. + *

+ * See Storage Services Versioning on MSDN for more information on + * applicable versions. + * + * @param defaultServiceVersion + * A {@link String} containing the default service version string + * used for operations on the storage account. + * @return A reference to this {@link ServiceProperties} instance. + */ + public ServiceProperties setDefaultServiceVersion( + String defaultServiceVersion) { + this.defaultServiceVersion = defaultServiceVersion; + return this; + } + + /** + * Represents the logging options that can be set on a storage account. + */ + public static class Logging { + private String version; + private Boolean delete; + private Boolean read; + private Boolean write; + private RetentionPolicy retentionPolicy; + + /** + * Gets the retention policy for logging data set on the storage + * account. + * + * @return The {@link RetentionPolicy} set on the storage account. + */ + @XmlElement(name = "RetentionPolicy") + public RetentionPolicy getRetentionPolicy() { + return retentionPolicy; + } + + /** + * Sets the retention policy to use for logging data on the storage + * account. + * + * @param retentionPolicy + * The {@link RetentionPolicy} to set on the storage account. + * @return A reference to this {@link Logging} instance. + */ + public Logging setRetentionPolicy(RetentionPolicy retentionPolicy) { + this.retentionPolicy = retentionPolicy; + return this; + } + + /** + * Gets a flag indicating whether all write requests are logged. + * + * @return A flag value of true if all write operations are + * logged; otherwise, false. + */ + @XmlElement(name = "Write") + public boolean isWrite() { + return write; + } + + /** + * Sets a flag indicating whether all write requests should be logged. + * + * @param write + * Set a flag value of true to log all write + * operations; otherwise, false. + * @return A reference to this {@link Logging} instance. + */ + public Logging setWrite(boolean write) { + this.write = write; + return this; + } + + /** + * Gets a flag indicating whether all read requests are logged. + * + * @return A flag value of true if all read operations are + * logged; otherwise, false. + */ + @XmlElement(name = "Read") + public boolean isRead() { + return read; + } + + /** + * Sets a flag indicating whether all read requests should be logged. + * + * @param read + * Set a flag value of true to log all read + * operations; otherwise, false. + * @return A reference to this {@link Logging} instance. + */ + public Logging setRead(boolean read) { + this.read = read; + return this; + } + + /** + * Gets a flag indicating whether all delete requests are logged. + * + * @return A flag value of true if all delete operations + * are logged; otherwise, false. + */ + @XmlElement(name = "Delete") + public boolean isDelete() { + return delete; + } + + /** + * Sets a flag indicating whether all delete requests should be logged. + * + * @param delete + * Set a flag value of true to log all delete + * operations; otherwise, false. + * @return A reference to this {@link Logging} instance. + */ + public Logging setDelete(boolean delete) { + this.delete = delete; + return this; + } + + /** + * Gets the version of logging configured on the storage account. + * + * @return A {@link String} containing the version of logging configured + * on the storage account. + */ + @XmlElement(name = "Version") + public String getVersion() { + return version; + } + + /** + * Sets the version of logging configured on the storage account. + * + * @param version + * A {@link String} containing the version of logging + * configured on the storage account. + * @return A reference to this {@link Logging} instance. + */ + public Logging setVersion(String version) { + this.version = version; + return this; + } + } + + /** + * Represents the metrics options that can be set on a storage account. + */ + public static class Metrics { + private String version; + private boolean enabled; + private Boolean includeAPIs; + private RetentionPolicy retentionPolicy; + + /** + * Gets the retention policy for metrics data set on the storage + * account. + * + * @return The {@link RetentionPolicy} set on the storage account. + */ + @XmlElement(name = "RetentionPolicy") + public RetentionPolicy getRetentionPolicy() { + return retentionPolicy; + } + + /** + * Sets the retention policy to use for metrics data on the storage + * account. + * + * @param retentionPolicy + * The {@link RetentionPolicy} to set on the storage account. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setRetentionPolicy(RetentionPolicy retentionPolicy) { + this.retentionPolicy = retentionPolicy; + return this; + } + + /** + * Gets a flag indicating whether metrics generates summary statistics + * for called API operations. + * + * @return A flag value of true if metrics generates + * summary statistics for called API operations; otherwise, + * false. + */ + @XmlElement(name = "IncludeAPIs") + public Boolean isIncludeAPIs() { + return includeAPIs; + } + + /** + * Sets a flag indicating whether metrics should generate summary + * statistics for called API operations. This flag is optional if + * metrics is not enabled. + * + * @param includeAPIs + * Set a flag value of true to generate summary + * statistics for called API operations; otherwise, + * false. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setIncludeAPIs(Boolean includeAPIs) { + this.includeAPIs = includeAPIs; + return this; + } + + /** + * Gets a flag indicating whether metrics is enabled for the storage + * account. + * + * @return A flag value of true if metrics is enabled for + * the storage account; otherwise, false. + */ + @XmlElement(name = "Enabled") + public boolean isEnabled() { + return enabled; + } + + /** + * Sets a flag indicating whether to enable metrics for the storage + * account. + * + * @param enabled + * Set a flag value of true to enable metrics + * for the storage account; otherwise, false. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Gets the version of Storage Analytics configured on the storage + * account. + * + * @return A {@link String} containing the version of Storage Analytics + * configured on the storage account. + */ + @XmlElement(name = "Version") + public String getVersion() { + return version; + } + + /** + * Sets the version of Storage Analytics configured on the storage + * account. + * + * @param version + * A {@link String} containing the version of Storage + * Analytics configured on the storage account. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setVersion(String version) { + this.version = version; + return this; + } + } + + /** + * Represents the optional retention policy that can be applied to logging + * or metrics on the storage account. + */ + public static class RetentionPolicy { + private boolean enabled; + private Integer days; // nullable, because optional if "enabled" is + // false + + /** + * Gets the number of days that metrics or logging data should be + * retained, if logging is enabled. + * + * @return The number of days to retain logging or metrics data if + * logging is enabled, or null. + */ + @XmlElement(name = "Days") + public Integer getDays() { + return days; + } + + /** + * Sets the number of days that metrics or logging data should be + * retained. The minimum value you can specify is 1; the largest value + * is 365 (one year). This value must be specified even if the enabled + * flag is set to false. + * + * @param days + * The number of days to retain logging or metrics data. + * @return A reference to this {@link RetentionPolicy} instance. + */ + public RetentionPolicy setDays(Integer days) { + this.days = days; + return this; + } + + /** + * Gets a flag indicating whether a retention policy is enabled. + * + * @return A flag value of true if a retention policy is + * enabled; otherwise, false. + */ + @XmlElement(name = "Enabled") + public boolean isEnabled() { + return enabled; + } + + /** + * Sets a flag indicating whether to enable a retention policy. + * + * @param enabled + * Set a flag value of true to enable a + * retention policy; otherwise, false. + * @return A reference to this {@link RetentionPolicy} instance. + */ + public RetentionPolicy setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataOptions.java new file mode 100644 index 0000000000000..0d7f5f24b2ec8 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataOptions.java @@ -0,0 +1,105 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setBlobMetadata(String, String, java.util.HashMap, SetBlobMetadataOptions) + * setBlobMetadata} request. These options include an optional server timeout + * for the operation, a blob lease ID, and any access conditions for the + * operation. + */ +public class SetBlobMetadataOptions extends BlobServiceOptions { + private String leaseId; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link SetBlobMetadataOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link SetBlobMetadataOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link SetBlobMetadataOptions} instance. + */ + @Override + public SetBlobMetadataOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link SetBlobMetadataOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets an optional lease ID value to match when setting metadata of the + * blob. If set, the lease must be active and the value must match the lease + * ID set on the leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobMetadataOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link SetBlobMetadataOptions} instance. + */ + public SetBlobMetadataOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the access conditions set in this {@link SetBlobMetadataOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions for setting the metadata of a blob. By + * default, the set blob metadata operation will set the metadata + * unconditionally. Use this method to specify conditions on the ETag or + * last modified time value for performing the operation. + *

+ * The accessCondition value only affects calls made on methods + * where this {@link SetBlobMetadataOptions} instance is passed as a + * parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link SetBlobMetadataOptions} instance. + */ + public SetBlobMetadataOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataResult.java new file mode 100644 index 0000000000000..a75d488f8ab41 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataResult.java @@ -0,0 +1,93 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; + +/** + * A wrapper class for the response returned from a Blob Service REST API Set + * Blob Metadata operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setBlobMetadata(String, String, java.util.HashMap, SetBlobMetadataOptions)} + * . + *

+ * See the Set + * Blob Metadata documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class SetBlobMetadataResult { + private String etag; + private Date lastModified; + + /** + * Gets the ETag of the blob. + *

+ * This value can be used in an access condition when updating or deleting a + * blob to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the blob from the + * ETag element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modified time of the blob. + *

+ * Any operation that modifies the blob, including updates to the blob's + * metadata or properties, changes the last modified time of the blob. This + * value can be used in an access condition when updating or deleting a blob + * to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * page blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the blob from + * the Last-Modified element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesOptions.java new file mode 100644 index 0000000000000..12efe7b7055c6 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesOptions.java @@ -0,0 +1,388 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setBlobProperties(String, String, SetBlobPropertiesOptions) + * setBlobProperties} request. These options include an optional server timeout + * for the operation, the MIME content type and content encoding for the blob, + * the content length, the content language, the MD5 hash, a cache control + * value, a blob lease ID, a sequence number and sequence number action value, + * and any access conditions for the operation. + */ +public class SetBlobPropertiesOptions extends BlobServiceOptions { + private String leaseId; + private String contentType; + private Long contentLength; + private String contentEncoding; + private String contentLanguage; + private String contentMD5; + private String cacheControl; + private String sequenceNumberAction; + private Long sequenceNumber; + private AccessConditionHeader accessCondition; + + /** + * Sets the optional server request timeout value associated with this + * {@link SetBlobPropertiesOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + @Override + public SetBlobPropertiesOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the MIME content type value set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the MIME content type value set, if + * any. + */ + public String getContentType() { + return contentType; + } + + /** + * Sets the optional MIME content type for the blob content. This value will + * be returned to clients in the Content-Type header of the + * response when the blob data or blob properties are requested. If no + * content type is specified, the default content type is + * application/octet-stream. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param contentType + * A {@link String} containing the MIME content type value to + * set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setContentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Gets the new page blob size set in this {@link SetBlobPropertiesOptions} + * instance. + * + * @return The new size to set for a page blob. + */ + public Long getContentLength() { + return contentLength; + } + + /** + * Sets the size of a page blob to the specified size. If the specified + * contentLength value is less than the current size of the blob, + * then all pages above the specified value are cleared. + *

+ * This property cannot be used to change the size of a block blob. Setting + * this property for a block blob causes a {@link com.microsoft.windowsazure.exception.ServiceException} to be + * thrown. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param contentLength + * The new size to set for a page blob. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setContentLength(Long contentLength) { + this.contentLength = contentLength; + return this; + } + + /** + * Gets the HTTP content encoding value set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the HTTP content encoding value set, + * if any. + */ + public String getContentEncoding() { + return contentEncoding; + } + + /** + * Sets the optional HTML content encoding value for the blob content. Use + * this value to specify any HTTP content encodings applied to the blob, + * passed as a x-ms-blob-content-encoding header value to the + * server. This value will be returned to clients in the headers of the + * response when the blob data or blob properties are requested. Pass an + * empty value to update a blob to the default value, which will cause no + * content encoding header to be returned with the blob. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param contentEncoding + * A {@link String} containing the + * x-ms-blob-content-encoding header value to set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setContentEncoding(String contentEncoding) { + this.contentEncoding = contentEncoding; + return this; + } + + /** + * Gets the HTTP content language header value set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the HTTP content language header + * value set, if any. + */ + public String getContentLanguage() { + return contentLanguage; + } + + /** + * Sets the optional HTTP content language header value for the blob + * content. Use this value to specify the content language of the blob. This + * value will be returned to clients in the + * x-ms-blob-content-language header of the response when the + * blob data or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param contentLanguage + * A {@link String} containing the + * x-ms-blob-content-language header value to set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setContentLanguage(String contentLanguage) { + this.contentLanguage = contentLanguage; + return this; + } + + /** + * Gets the MD5 hash value for the blob content set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the MD5 hash value for the blob + * content set, if any. + */ + public String getContentMD5() { + return contentMD5; + } + + /** + * Sets the optional MD5 hash value for the blob content. This value will be + * returned to clients in the x-ms-blob-content-md5 header + * value of the response when the blob data or blob properties are + * requested. This hash is used to verify the integrity of the blob during + * transport. When this header is specified, the storage service checks the + * hash of the content that has arrived with the one that was sent. If the + * two hashes do not match, the operation will fail with error code 400 (Bad + * Request), which will cause a ServiceException to be thrown. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param contentMD5 + * A {@link String} containing the MD5 hash value for the blob + * content to set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setContentMD5(String contentMD5) { + this.contentMD5 = contentMD5; + return this; + } + + /** + * Gets the HTTP cache control value set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the HTTP cache control value set, if + * any. + */ + public String getCacheControl() { + return cacheControl; + } + + /** + * Sets the optional HTTP cache control value for the blob content. The Blob + * service stores this value but does not use or modify it. This value will + * be returned to clients in the headers of the response when the blob data + * or blob properties are requested. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param cacheControl + * A {@link String} containing the HTTP cache control value to + * set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setCacheControl(String cacheControl) { + this.cacheControl = cacheControl; + return this; + } + + /** + * Gets the sequence number value set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return The sequence number to set, if any. + */ + public Long getSequenceNumber() { + return sequenceNumber; + } + + /** + * Sets the page blob sequence number. The sequence number is a + * user-controlled property that you can use to track requests and manage + * concurrency issues. This value is optional, but is required if the + * sequence number action value is set to max or + * update. + *

+ * Use the sequenceNumber parameter together with the sequence + * number action to update the blob's sequence number, either to the + * specified value or to the higher of the values specified with the request + * or currently stored with the blob. This header should not be specified if + * the sequence number action is set to increment; in this case + * the service automatically increments the sequence number by one. + *

+ * To set the sequence number to a value of your choosing, this property + * must be specified on the request together with a sequence number action + * value of update. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param sequenceNumber + * The sequence number to set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setSequenceNumber(Long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + return this; + } + + /** + * Gets the lease ID to match for the blob set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the lease ID set, if any. + */ + public String getLeaseId() { + return leaseId; + } + + /** + * Sets an optional lease ID value to match when setting properties of the + * blob. If set, the lease must be active and the value must match the lease + * ID set on the leased blob for the operation to succeed. + *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param leaseId + * A {@link String} containing the lease ID to set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setLeaseId(String leaseId) { + this.leaseId = leaseId; + return this; + } + + /** + * Gets the sequence number action set in this + * {@link SetBlobPropertiesOptions} instance. + * + * @return A {@link String} containing the sequence number action set, if + * any. + */ + public String getSequenceNumberAction() { + return sequenceNumberAction; + } + + /** + * Sets an optional sequence number action for a page blob. This value is + * required if a sequence number is set for the request. + *

+ * The sequenceNumberAction parameter indicates how the service + * should modify the page blob's sequence number. Specify one of the + * following strings for this parameter: + *

    + *
  • max - Sets the sequence number to be the higher of the + * value included with the request and the value currently stored for the + * blob.
  • + *
  • update - Sets the sequence number to the value included + * with the request.
  • + *
  • increment - Increments the value of the sequence number + * by 1. If specifying this option, do not set the sequence number value; + * doing so will cause a {@link com.microsoft.windowsazure.exception.ServiceException} to be thrown.
  • + *
+ *

+ * Note that this value only affects calls made on methods where this + * {@link SetBlobPropertiesOptions} instance is passed as a parameter. + * + * @param sequenceNumberAction + * A {@link String} containing the sequence number action to set + * on the page blob. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setSequenceNumberAction( + String sequenceNumberAction) { + this.sequenceNumberAction = sequenceNumberAction; + return this; + } + + /** + * Gets the access conditions set in this {@link SetBlobPropertiesOptions} + * instance. + * + * @return An {@link AccessCondition} containing the access conditions set, + * if any. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions for setting the properties of a blob. By + * default, the set blob properties operation will set the properties + * unconditionally. Use this method to specify conditions on the ETag or + * last modified time value for performing the operation. + *

+ * The accessCondition value only affects calls made on methods + * where this {@link SetBlobPropertiesOptions} instance is passed as a + * parameter. + * + * @param accessCondition + * An {@link AccessCondition} containing the access conditions to + * set. + * @return A reference to this {@link SetBlobPropertiesOptions} instance. + */ + public SetBlobPropertiesOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesResult.java new file mode 100644 index 0000000000000..3a98e2ffcf220 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesResult.java @@ -0,0 +1,123 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import java.util.Date; + +/** + * A wrapper class for the response returned from a Blob Service REST API Set + * Blob Properties operation. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setBlobProperties(String, String, SetBlobPropertiesOptions)} + * . + *

+ * See the Set + * Blob Properties documentation on MSDN for details of the underlying Blob + * Service REST API operation. + */ +public class SetBlobPropertiesResult { + private String etag; + private Date lastModified; + private Long sequenceNumber; + + /** + * Gets the ETag of the blob. + *

+ * This value can be used in an access condition when updating or deleting a + * blob to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public String getEtag() { + return etag; + } + + /** + * Reserved for internal use. Sets the ETag of the blob from the + * ETag element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param etag + * A {@link String} containing the server-assigned ETag value for + * the blob. + */ + public void setEtag(String etag) { + this.etag = etag; + } + + /** + * Gets the last modified time of the blob. + *

+ * Any operation that modifies the blob, including updates to the blob's + * metadata or properties, changes the last modified time of the blob. This + * value can be used in an access condition when updating or deleting a blob + * to prevent the client from modifying data that has been changed by + * another client. + * + * @return A {@link java.util.Date} containing the last modified time of the + * page blob. + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Reserved for internal use. Sets the last modified time of the blob from + * the Last-Modified element returned in the response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param lastModified + * A {@link java.util.Date} containing the last modified time of + * the blob. + */ + public void setLastModified(Date lastModified) { + this.lastModified = lastModified; + } + + /** + * Gets the sequence number of the page blob. This value can be used when + * updating or deleting a page blob using an optimistic concurrency model to + * prevent the client from modifying data that has been changed by another + * client. + * + * @return A {@link String} containing the client-assigned sequence number + * value for the page blob. + */ + public Long getSequenceNumber() { + return sequenceNumber; + } + + /** + * Reserved for internal use. Sets the sequence number of the page blob from + * the x-ms-blob-sequence-number element returned in the + * response. + *

+ * This method is invoked by the API to set the value from the Blob Service + * REST API operation response returned by the server. + * + * @param sequenceNumber + * A {@link String} containing the client-assigned sequence + * number value for the page blob. + */ + public void setSequenceNumber(Long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetContainerMetadataOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetContainerMetadataOptions.java new file mode 100644 index 0000000000000..66ed029c84dc9 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/SetContainerMetadataOptions.java @@ -0,0 +1,83 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob.models; + +import com.microsoft.windowsazure.core.utils.AccessConditionHeader; + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.blob.BlobContract#setContainerMetadata(String, java.util.HashMap, SetContainerMetadataOptions)} + * request. These options include a server response timeout for the request and + * access conditions that specify whether to perform the operation or not + * depending on the values of the Etag or last modified time of the container. + * Options that are not set will not be passed to the server with a request. + */ +public class SetContainerMetadataOptions extends BlobServiceOptions { + private AccessConditionHeader accessCondition; + + /** + * Sets the server request timeout value associated with this + * {@link SetContainerMetadataOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link SetContainerMetadataOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link SetContainerMetadataOptions} instance. + */ + @Override + public SetContainerMetadataOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the access conditions associated with this + * {@link SetContainerMetadataOptions} instance. + * + * @return An {@link AccessCondition} reference containing the Etag and last + * modified time conditions for performing the set container + * metadata operation, or null if not set. + */ + public AccessConditionHeader getAccessCondition() { + return accessCondition; + } + + /** + * Sets the access conditions associated with this + * {@link SetContainerMetadataOptions} instance. By default, the set + * container metadata operation will set the container metadata + * unconditionally. Use this method to specify conditions on the Etag or + * last modified time value for performing the set container metadata + * operation. + *

+ * The accessCondition value only affects calls made on methods + * where this {@link SetContainerMetadataOptions} instance is passed as a + * parameter. + * + * @param accessCondition + * An {@link AccessCondition} reference containing the Etag and + * last modified time conditions for performing the set container + * metadata operation. Specify null to make the + * operation unconditional. + * @return A reference to this {@link SetContainerMetadataOptions} instance. + */ + public SetContainerMetadataOptions setAccessCondition( + AccessConditionHeader accessCondition) { + this.accessCondition = accessCondition; + return this; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/package.html b/media/src/main/java/com/microsoft/windowsazure/services/blob/models/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/blob/models/package.html diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/package.html b/media/src/main/java/com/microsoft/windowsazure/services/blob/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/blob/package.html diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/Exports.java b/media/src/main/java/com/microsoft/windowsazure/services/media/Exports.java new file mode 100644 index 0000000000000..658a361c3c84b --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/Exports.java @@ -0,0 +1,89 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.media; + +import java.util.Map; + +import javax.xml.bind.JAXBException; +import javax.xml.parsers.ParserConfigurationException; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.services.media.implementation.MediaContentProvider; +import com.microsoft.windowsazure.services.media.implementation.MediaExceptionProcessor; +import com.microsoft.windowsazure.services.media.implementation.MediaRestProxy; +import com.microsoft.windowsazure.services.media.implementation.OAuthContract; +import com.microsoft.windowsazure.services.media.implementation.OAuthFilter; +import com.microsoft.windowsazure.services.media.implementation.OAuthRestProxy; +import com.microsoft.windowsazure.services.media.implementation.OAuthTokenManager; +import com.microsoft.windowsazure.services.media.implementation.ODataEntityCollectionProvider; +import com.microsoft.windowsazure.services.media.implementation.ODataEntityProvider; +import com.microsoft.windowsazure.services.media.implementation.RedirectFilter; +import com.microsoft.windowsazure.services.media.implementation.ResourceLocationManager; +import com.microsoft.windowsazure.services.media.implementation.VersionHeadersFilter; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.json.JSONConfiguration; + +public class Exports implements Builder.Exports { + + /** + * register the Media services. + */ + @Override + public void register(Builder.Registry registry) { + registry.add(MediaContract.class, MediaExceptionProcessor.class); + registry.add(MediaRestProxy.class); + registry.add(OAuthContract.class, OAuthRestProxy.class); + registry.add(OAuthTokenManager.class); + registry.add(OAuthFilter.class); + registry.add(ResourceLocationManager.class); + registry.add(RedirectFilter.class); + registry.add(VersionHeadersFilter.class); + registry.add(UserAgentFilter.class); + + registry.alter(MediaContract.class, ClientConfig.class, + new Builder.Alteration() { + @SuppressWarnings("rawtypes") + @Override + public ClientConfig alter(String profile, + ClientConfig instance, Builder builder, + Map properties) { + + instance.getProperties().put( + JSONConfiguration.FEATURE_POJO_MAPPING, true); + + // Turn off auto-follow redirects, because Media + // Services rest calls break if it's on + instance.getProperties().put( + ClientConfig.PROPERTY_FOLLOW_REDIRECTS, false); + + try { + instance.getSingletons().add( + new ODataEntityProvider()); + instance.getSingletons().add( + new ODataEntityCollectionProvider()); + instance.getSingletons().add( + new MediaContentProvider()); + } catch (JAXBException e) { + throw new RuntimeException(e); + } catch (ParserConfigurationException e) { + throw new RuntimeException(e); + } + + return instance; + } + }); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/MediaConfiguration.java b/media/src/main/java/com/microsoft/windowsazure/services/media/MediaConfiguration.java new file mode 100644 index 0000000000000..8d4eaed05d714 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/MediaConfiguration.java @@ -0,0 +1,178 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.media; + +import com.microsoft.windowsazure.Configuration; + +/** + * Provides functionality to create a media services configuration. + * + */ +public final class MediaConfiguration { + + private MediaConfiguration() { + } + + /** + * Defines the media service configuration URI constant. + * + */ + public static final String URI = "media.uri"; + + /** + * Defines the OAUTH configuration URI constant. + * + */ + public static final String OAUTH_URI = "media.oauth.uri"; + + /** + * Defines the OAUTH configuration client ID constant. + * + */ + public static final String OAUTH_CLIENT_ID = "media.oauth.client.id"; + + /** + * Defines the OAUTH configuration client secret constant. + * + */ + public static final String OAUTH_CLIENT_SECRET = "media.oauth.client.secret"; + + /** + * Defines the SCOPE of the media service sent to OAUTH. + */ + public static final String OAUTH_SCOPE = "media.oauth.scope"; + + /** + * Creates a media service configuration using the specified media service + * base URI, OAUTH URI, client ID, and client secret. + * + * @param mediaServiceUri + * A String object that represents the media service + * URI. + * + * @param oAuthUri + * A String object that represents the OAUTH URI. + * + * @param clientId + * A String object that represents the client ID. + * + * @param clientSecret + * A String object that represents the client + * secret. + * + * @param scope + * A String object that represents the scope. + * + * @return A Configuration object that can be used when + * creating an instance of the MediaService class. + * + */ + public static Configuration configureWithOAuthAuthentication( + String mediaServiceUri, String oAuthUri, String clientId, + String clientSecret, String scope) { + return configureWithOAuthAuthentication(null, + Configuration.getInstance(), mediaServiceUri, oAuthUri, + clientId, clientSecret, scope); + } + + /** + * Creates a media service configuration using the specified configuration, + * media service base URI, OAuth URI, client ID, and client secret. + * + * @param configuration + * A previously instantiated Configuration object. + * + * @param mediaServiceUri + * A String object that represents the URI of media + * service. + * + * @param oAuthUri + * A String object that represents the URI of OAuth + * service. + * + * @param clientId + * A String object that represents the client ID. + * + * @param clientSecret + * A String object that represents the client + * secret. + * + * @param scope + * A String object that represents the scope. + * + * @return A Configuration object that can be used when + * creating an instance of the MediaService class. + * + */ + public static Configuration configureWithOAuthAuthentication( + Configuration configuration, String mediaServiceUri, + String oAuthUri, String clientId, String clientSecret, String scope) { + return configureWithOAuthAuthentication(null, configuration, + mediaServiceUri, oAuthUri, clientId, clientSecret, scope); + } + + /** + * Creates a media service configuration using the specified profile, + * configuration, media service base URI, OAuth URI, client ID, and client + * secret. + * + * @param profile + * A String object that represents the profile. + * + * @param configuration + * A previously instantiated Configuration object. + * + * @param mediaServiceUri + * A String object that represents the URI of media + * service. + * + * @param oAuthUri + * A String object that represents the URI of OAUTH + * service. + * + * @param clientId + * A String object that represents the client ID. + * + * @param clientSecret + * A String object that represents the client + * secret. + * + * @param scope + * A String object that represents the scope. + * + * @return A Configuration object that can be used when + * creating an instance of the MediaService class. + * + */ + public static Configuration configureWithOAuthAuthentication( + String profile, Configuration configuration, + String mediaServiceUri, String oAuthUri, String clientId, + String clientSecret, String scope) { + + if (profile == null) { + profile = ""; + } else if (profile.length() != 0 && !profile.endsWith(".")) { + profile = profile + "."; + } + + configuration.setProperty(profile + URI, mediaServiceUri); + configuration.setProperty(profile + OAUTH_URI, oAuthUri); + configuration.setProperty(profile + OAUTH_CLIENT_ID, clientId); + configuration.setProperty(profile + OAUTH_CLIENT_SECRET, clientSecret); + configuration.setProperty(profile + OAUTH_SCOPE, scope); + + return configuration; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaContract.java b/media/src/main/java/com/microsoft/windowsazure/services/media/MediaContract.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaContract.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/MediaContract.java index a6affe44503d3..eebebf03c13a6 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaContract.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/MediaContract.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media; -import com.microsoft.windowsazure.services.core.FilterableService; +import com.microsoft.windowsazure.core.pipeline.jersey.JerseyFilterableService; import com.microsoft.windowsazure.services.media.entityoperations.EntityContract; import com.microsoft.windowsazure.services.media.models.LocatorInfo; @@ -23,14 +23,16 @@ * Contract for interacting with the back end of Media Services * */ -public interface MediaContract extends FilterableService, EntityContract { +public interface MediaContract extends JerseyFilterableService, + EntityContract { /** - * Creates an instance of the WritableBlobContainerContract API that will - * write to the blob container given by the provided locator. + * Creates an instance of the WritableBlobContainerContract API + * that will write to the blob container given by the provided locator. * * @param locator * locator specifying where to upload to * @return the implementation of WritableBlobContainerContract */ WritableBlobContainerContract createBlobWriter(LocatorInfo locator); + } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaService.java b/media/src/main/java/com/microsoft/windowsazure/services/media/MediaService.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaService.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/MediaService.java index 8a90501dc2fe8..df95d2d602c18 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaService.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/MediaService.java @@ -14,15 +14,14 @@ */ package com.microsoft.windowsazure.services.media; -import com.microsoft.windowsazure.services.core.Configuration; +import com.microsoft.windowsazure.Configuration; /** * - * Access media services functionality. This class cannot - * be instantiated. + * Access media services functionality. This class cannot be instantiated. * */ -public class MediaService { +public final class MediaService { private MediaService() { } @@ -36,10 +35,12 @@ public static MediaContract create() { } /** - * Creates an instance of the MediaServicesContract API using the specified configuration. + * Creates an instance of the MediaServicesContract API using + * the specified configuration. * * @param config - * A Configuration object that represents the configuration for the service bus service. + * A Configuration object that represents the + * configuration for the service bus service. * */ public static MediaContract create(Configuration config) { @@ -55,10 +56,12 @@ public static MediaContract create(String profile) { } /** - * Creates an instance of the MediaServicesContract API using the specified configuration. + * Creates an instance of the MediaServicesContract API using + * the specified configuration. * * @param config - * A Configuration object that represents the configuration for the service bus service. + * A Configuration object that represents the + * configuration for the service bus service. * */ public static MediaContract create(String profile, Configuration config) { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/WritableBlobContainerContract.java b/media/src/main/java/com/microsoft/windowsazure/services/media/WritableBlobContainerContract.java similarity index 80% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/WritableBlobContainerContract.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/WritableBlobContainerContract.java index 835cc2ec8954a..64a99599bf1b4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/WritableBlobContainerContract.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/WritableBlobContainerContract.java @@ -17,18 +17,19 @@ import java.io.InputStream; +import com.microsoft.windowsazure.core.pipeline.jersey.JerseyFilterableService; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.blob.models.BlockList; import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; -import com.microsoft.windowsazure.services.core.FilterableService; -import com.microsoft.windowsazure.services.core.ServiceException; /** * The Interface WritableBlobContainerContract. */ -public interface WritableBlobContainerContract extends FilterableService { +public interface WritableBlobContainerContract extends + JerseyFilterableService { /** * Creates the block blob. @@ -41,7 +42,8 @@ public interface WritableBlobContainerContract extends FilterableService queryParameters; + + /** The body parameters. */ + private Map bodyParameters; + + /** + * The default action operation. + * + * @param name + * the name + */ + public DefaultActionOperation(String name) { + this(); + this.name = name; + } + + /** + * Instantiates a new default action operation. + */ + public DefaultActionOperation() { + this.queryParameters = new MultivaluedMapImpl(); + this.bodyParameters = new HashMap(); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #setProxyData(com.microsoft.windowsazure.services.media.entityoperations. + * EntityProxyData) + */ + @Override + public void setProxyData(EntityProxyData proxyData) { + this.proxyData = proxyData; + } + + /** + * Get the current proxy data. + * + * @return the proxy data + */ + protected EntityProxyData getProxyData() { + return proxyData; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getUri() + */ + @Override + public String getUri() { + return name; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getQueryParameters() + */ + @Override + public MultivaluedMap getQueryParameters() { + return this.queryParameters; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#addQueryParameter(java.lang.String, + * java.lang.String) + */ + @Override + public DefaultActionOperation addQueryParameter(String key, String value) { + this.queryParameters.add(key, value); + return this; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getContentType() + */ + @Override + public MediaType getContentType() { + return this.contentType; + } + + /** + * Sets the content type. + * + * @param contentType + * the content type + * @return the default action operation + */ + @Override + public DefaultActionOperation setContentType(MediaType contentType) { + this.contentType = contentType; + return this; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getAcceptType() + */ + @Override + public MediaType getAcceptType() { + return this.acceptType; + } + + /** + * Sets the accept type. + * + * @param acceptType + * the accept type + * @return the default action operation + */ + public DefaultActionOperation setAcceptType(MediaType acceptType) { + this.acceptType = acceptType; + return this; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getVerb() + */ + @Override + public String getVerb() { + return "GET"; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getRequestContents() + */ + @Override + public Object getRequestContents() { + return null; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #processResponse(java.lang.Object) + */ + @Override + public Object processResponse(Object rawResponse) throws ServiceException { + PipelineHelpers.throwIfNotSuccess((ClientResponse) rawResponse); + return rawResponse; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getBodyParameters() + */ + @Override + public Map getBodyParameters() { + return this.bodyParameters; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#addBodyParameter(java.lang.String, + * java.lang.Object) + */ + @Override + public EntityActionOperation addBodyParameter(String key, Object value) { + this.bodyParameters.put(key, value); + return this; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultDeleteOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultDeleteOperation.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultDeleteOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultDeleteOperation.java index 352e4b362d113..7b65fa565c016 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultDeleteOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultDeleteOperation.java @@ -27,11 +27,17 @@ public class DefaultDeleteOperation implements EntityDeleteOperation { * */ public DefaultDeleteOperation(String entityUri, String entityId) { - uriBuilder = new EntityOperationBase.EntityIdUriBuilder(entityUri, entityId); + uriBuilder = new EntityOperationBase.EntityIdUriBuilder(entityUri, + entityId); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityDeleteOperation#setProxyData(com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData) + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityDeleteOperation + * #setProxyData(com.microsoft.windowsazure.services.media + * .entityoperations.EntityProxyData) */ @Override public void setProxyData(EntityProxyData proxyData) { @@ -47,8 +53,12 @@ protected EntityProxyData getProxyData() { return proxyData; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityDeleteOperation#getUri() + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entities.EntityDeleteOperation + * #getUri() */ @Override public String getUri() { diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityActionOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityActionOperation.java new file mode 100644 index 0000000000000..57cc773e4f9f0 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityActionOperation.java @@ -0,0 +1,282 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.entityoperations; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import com.microsoft.windowsazure.core.pipeline.PipelineHelpers; +import com.microsoft.windowsazure.exception.ServiceException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +/** + * Generic implementation of Delete operation usable by most entities. + */ +public class DefaultEntityActionOperation implements EntityActionOperation { + + /** The proxy data. */ + private EntityProxyData proxyData; + + /** The uri builder. */ + private final EntityOperationBase.EntityUriBuilder uriBuilder; + + /** The content type. */ + private MediaType contentType = MediaType.APPLICATION_JSON_TYPE; + + /** The accept type. */ + private MediaType acceptType = MediaType.APPLICATION_ATOM_XML_TYPE; + + /** The query parameters. */ + private MultivaluedMap queryParameters; + + /** The entity name. */ + private final String entityName; + + /** The entity id. */ + private final String entityId; + + /** The action name. */ + private final String actionName; + + /** The body parameters. */ + private Map bodyParameters; + + /** + * The default action operation. + * + * @param entityName + * the entity name + * @param entityId + * the entity id + * @param actionName + * the action name + */ + public DefaultEntityActionOperation(String entityName, String entityId, + String actionName) { + this.queryParameters = new MultivaluedMapImpl(); + this.bodyParameters = new HashMap(); + this.entityName = entityName; + this.entityId = entityId; + this.actionName = actionName; + this.uriBuilder = new EntityOperationBase.EntityIdUriBuilder( + entityName, entityId).setActionName(actionName); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #setProxyData(com.microsoft.windowsazure.services.media.entityoperations. + * EntityProxyData) + */ + @Override + public void setProxyData(EntityProxyData proxyData) { + this.proxyData = proxyData; + } + + /** + * Get the current proxy data. + * + * @return the proxy data + */ + protected EntityProxyData getProxyData() { + return proxyData; + } + + /** + * Gets the entity name. + * + * @return the entity name + */ + public String getEntityName() { + return this.entityName; + } + + /** + * Gets the entity id. + * + * @return the entity id + */ + public String getEntityId() { + return this.entityId; + } + + /** + * Gets the action name. + * + * @return the action name + */ + public String getActionName() { + return this.actionName; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getUri() + */ + @Override + public String getUri() { + return uriBuilder.getUri(); + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getQueryParameters() + */ + @Override + public MultivaluedMap getQueryParameters() { + return this.queryParameters; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#addQueryParameter(java.lang.String, + * java.lang.String) + */ + @Override + public DefaultEntityActionOperation addQueryParameter(String key, + String value) { + this.queryParameters.add(key, value); + return this; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getBodyParameters() + */ + @Override + public Map getBodyParameters() { + return this.bodyParameters; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getContentType() + */ + @Override + public MediaType getContentType() { + return this.contentType; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#setContentType(javax.ws.rs.core.MediaType) + */ + @Override + public DefaultEntityActionOperation setContentType(MediaType contentType) { + this.contentType = contentType; + return this; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getAcceptType() + */ + @Override + public MediaType getAcceptType() { + return this.acceptType; + } + + /** + * Sets the accept type. + * + * @param acceptType + * the accept type + * @return the default action operation + */ + public DefaultEntityActionOperation setAcceptType(MediaType acceptType) { + this.acceptType = acceptType; + return this; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getVerb() + */ + @Override + public String getVerb() { + return "POST"; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#getRequestContents() + */ + @Override + public Object getRequestContents() { + if (this.bodyParameters.size() == 0) { + return ""; + } else { + String jsonString = ""; + EntityActionBodyParameterMapper mapper = new EntityActionBodyParameterMapper(); + jsonString = mapper.toString(this.bodyParameters); + return jsonString; + } + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #processResponse(java.lang.Object) + */ + @Override + public Object processResponse(Object rawResponse) throws ServiceException { + PipelineHelpers.throwIfNotSuccess((ClientResponse) rawResponse); + return rawResponse; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation#addBodyParameter(java.lang.String, + * java.lang.Object) + */ + @Override + public EntityActionOperation addBodyParameter(String key, Object value) { + this.bodyParameters.put(key, value); + return this; + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityTypeActionOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityTypeActionOperation.java new file mode 100644 index 0000000000000..115adeef14276 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityTypeActionOperation.java @@ -0,0 +1,215 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.entityoperations; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +/** + * The Class DefaultTypeActionOperation. + * + * @param + * the generic type + */ +public class DefaultEntityTypeActionOperation implements + EntityTypeActionOperation { + + /** The name. */ + private String name; + + /** The content type. */ + private MediaType contentType = MediaType.APPLICATION_XML_TYPE; + + /** The accept type. */ + private MediaType acceptType = MediaType.APPLICATION_ATOM_XML_TYPE; + + /** The query parameters. */ + private final MultivaluedMap queryParameters; + + /** The proxy data. */ + private EntityProxyData proxyData; + + /** + * Instantiates a new default type action operation. + * + * @param name + * the name + */ + public DefaultEntityTypeActionOperation(String name) { + this(); + this.name = name; + } + + /** + * Instantiates a new default type action operation. + */ + public DefaultEntityTypeActionOperation() { + this.queryParameters = new MultivaluedMapImpl(); + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation + * #processTypeResponse(com.sun.jersey.api.client.ClientResponse) + */ + @Override + public T processTypeResponse(ClientResponse clientResponse) { + return null; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation#getQueryParameters() + */ + @Override + public MultivaluedMap getQueryParameters() { + return this.queryParameters; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation#getVerb() + */ + @Override + public String getVerb() { + return "GET"; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation#getRequestContents() + */ + @Override + public Object getRequestContents() { + return null; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #setProxyData(com.microsoft.windowsazure.services.media.entityoperations. + * EntityProxyData) + */ + @Override + public void setProxyData(EntityProxyData proxyData) { + this.proxyData = proxyData; + } + + public EntityProxyData getProxyData() { + return this.proxyData; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getUri() + */ + @Override + public String getUri() { + return this.name; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getContentType() + */ + @Override + public MediaType getContentType() { + return this.contentType; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #getAcceptType() + */ + @Override + public MediaType getAcceptType() { + return this.acceptType; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #processResponse(java.lang.Object) + */ + @Override + public Object processResponse(Object rawResponse) throws ServiceException { + return null; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation#addQueryParameter(java.lang.String, + * java.lang.String) + */ + @Override + public DefaultEntityTypeActionOperation addQueryParameter(String key, + String value) { + this.queryParameters.add(key, value); + return this; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation#setContentType(javax.ws.rs.core.MediaType) + */ + @Override + public EntityTypeActionOperation setContentType(MediaType contentType) { + this.contentType = contentType; + return this; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation#setAcceptType(javax.ws.rs.core.MediaType) + */ + @Override + public EntityTypeActionOperation setAcceptType(MediaType acceptType) { + this.acceptType = acceptType; + return this; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultGetOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultGetOperation.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultGetOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultGetOperation.java index 29a5f2650207e..34311506cedbc 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultGetOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultGetOperation.java @@ -19,7 +19,8 @@ * Generic implementation of the get operation usable for most entities * */ -public class DefaultGetOperation extends EntityOperationSingleResultBase implements EntityGetOperation { +public class DefaultGetOperation extends EntityOperationSingleResultBase + implements EntityGetOperation { /** * Construct a new DefaultGetOperation to return the given entity id @@ -31,12 +32,15 @@ public class DefaultGetOperation extends EntityOperationSingleResultBase i * @param responseClass * class to return from the get operation */ - public DefaultGetOperation(String entityTypeUri, String entityId, Class responseClass) { - super(new EntityOperationBase.EntityIdUriBuilder(entityTypeUri, entityId), responseClass); + public DefaultGetOperation(String entityTypeUri, String entityId, + Class responseClass) { + super(new EntityOperationBase.EntityIdUriBuilder(entityTypeUri, + entityId), responseClass); } /** - * Construct a new DefaultGetOperation to return the entity from the given uri + * Construct a new DefaultGetOperation to return the entity from the given + * uri * * @param uri * Uri for entity diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultListOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultListOperation.java similarity index 77% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultListOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultListOperation.java index 0aa1ab4eec677..49ae17daf9ac6 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultListOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultListOperation.java @@ -17,7 +17,7 @@ import javax.ws.rs.core.MultivaluedMap; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.models.ListResult; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.core.util.MultivaluedMapImpl; @@ -26,17 +26,20 @@ * Generic implementation of the list operation, usable by most entities * */ -public class DefaultListOperation extends EntityOperationBase implements EntityListOperation { +public class DefaultListOperation extends EntityOperationBase implements + EntityListOperation { private final MultivaluedMap queryParameters; private final GenericType> responseType; - public DefaultListOperation(String entityUri, GenericType> responseType) { + public DefaultListOperation(String entityUri, + GenericType> responseType) { super(entityUri); queryParameters = new MultivaluedMapImpl(); this.responseType = responseType; } - public DefaultListOperation(String entityUri, GenericType> responseType, + public DefaultListOperation(String entityUri, + GenericType> responseType, MultivaluedMap queryParameters) { this(entityUri, responseType); this.queryParameters.putAll(queryParameters); @@ -75,29 +78,41 @@ public DefaultListOperation setSkip(int skipValue) { * value for query parameter * @return this */ - public DefaultListOperation set(String parameterName, String parameterValue) { + public DefaultListOperation set(String parameterName, + String parameterValue) { queryParameters.add(parameterName, parameterValue); return this; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityListOperation#getQueryParameters() + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entities.EntityListOperation + * #getQueryParameters() */ @Override public MultivaluedMap getQueryParameters() { return queryParameters; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityListOperation#getResponseGenericType() + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entities.EntityListOperation + * #getResponseGenericType() */ @Override public GenericType> getResponseGenericType() { return responseType; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperationBase#processResponse(java.lang.Object) + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityOperationBase#processResponse(java.lang.Object) */ @Override public Object processResponse(Object rawResponse) throws ServiceException { diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionBodyParameterMapper.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionBodyParameterMapper.java new file mode 100644 index 0000000000000..105fc2cb909c4 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionBodyParameterMapper.java @@ -0,0 +1,66 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.entityoperations; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Map; + +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.SerializationConfig; + +/** + * The Class entity action body parameter mapper. + */ +public class EntityActionBodyParameterMapper { + + /** The mapper. */ + private ObjectMapper mapper; + + /** + * Instantiates a new entity action body parameter mapper. + */ + public EntityActionBodyParameterMapper() { + mapper = new ObjectMapper(); + mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, + false); + } + + /** + * To string. + * + * @param value + * the value + * @return the string + */ + public String toString(Map value) { + Writer writer = new StringWriter(); + try { + mapper.writeValue(writer, value); + } catch (JsonGenerationException e) { + throw new RuntimeException(e); + } catch (JsonMappingException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + return writer.toString(); + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionOperation.java similarity index 80% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionOperation.java index 25e272ca82699..642d06e73fa2a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityActionOperation.java @@ -15,6 +15,8 @@ package com.microsoft.windowsazure.services.media.entityoperations; +import java.util.Map; + import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -64,4 +66,21 @@ public interface EntityActionOperation extends EntityOperation { */ EntityActionOperation setContentType(MediaType contentType); + /** + * Gets the body parameters. + * + * @return the body parameters + */ + Map getBodyParameters(); + + /** + * Adds the body parameter. + * + * @param key + * the key + * @param value + * the value + * @return the entity action operation + */ + EntityActionOperation addBodyParameter(String key, Object value); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityBatchOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityBatchOperation.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityBatchOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityBatchOperation.java index ec29588bd6495..6cdad409fc913 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityBatchOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityBatchOperation.java @@ -25,8 +25,8 @@ public class EntityBatchOperation { - protected String verb; - protected EntryType entryType; + private String verb; + private EntryType entryType; public EntityBatchOperation() { this.entryType = new EntryType(); @@ -54,24 +54,28 @@ public String getVerb() { public EntityBatchOperation addContentObject(Object contentObject) { ContentType atomContent = new ContentType(); atomContent.setType("application/xml"); - atomContent.getContent().add( - new JAXBElement(new QName(Constants.ODATA_METADATA_NS, "properties"), contentObject.getClass(), - contentObject)); + atomContent + .getContent() + .add(new JAXBElement(new QName(Constants.ODATA_METADATA_NS, + "properties"), contentObject.getClass(), contentObject)); this.entryType.getEntryChildren().add( - new JAXBElement(new QName(Constants.ATOM_NS, "content"), ContentType.class, atomContent)); + new JAXBElement(new QName(Constants.ATOM_NS, "content"), + ContentType.class, atomContent)); return this; } @SuppressWarnings({ "unchecked", "rawtypes" }) - protected EntityBatchOperation addLink(String title, String href, String type, String rel) { + protected EntityBatchOperation addLink(String title, String href, + String type, String rel) { LinkType linkType = new LinkType(); linkType.setTitle(title); linkType.setHref(href); linkType.setType(type); linkType.setRel(rel); this.entryType.getEntryChildren().add( - new JAXBElement(new QName(Constants.ATOM_NS, "link"), LinkType.class, linkType)); + new JAXBElement(new QName(Constants.ATOM_NS, "link"), + LinkType.class, linkType)); return this; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityContract.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityContract.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityContract.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityContract.java index 67c539bfe63ed..5be4a665116be 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityContract.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityContract.java @@ -15,12 +15,12 @@ package com.microsoft.windowsazure.services.media.entityoperations; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.models.ListResult; /** - * Contract for interacting with the back end service - * providing various odata entities. + * Contract for interacting with the back end service providing various odata + * entities. * */ public interface EntityContract { @@ -31,12 +31,10 @@ public interface EntityContract { * @param * the generic type * @param creator - * Object providing the details of the entity to be - * created + * Object providing the details of the entity to be created * @return the t * @throws ServiceException - * the service exception - * The created entity + * the service exception The created entity */ T create(EntityCreateOperation creator) throws ServiceException; @@ -64,7 +62,8 @@ public interface EntityContract { * @throws ServiceException * the service exception */ - ListResult list(EntityListOperation lister) throws ServiceException; + ListResult list(EntityListOperation lister) + throws ServiceException; /** * Update an existing entity. @@ -107,6 +106,7 @@ public interface EntityContract { * @throws ServiceException * the service exception */ - T action(EntityTypeActionOperation entityActionOperation) throws ServiceException; + T action(EntityTypeActionOperation entityActionOperation) + throws ServiceException; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityCreateOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityCreateOperation.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityCreateOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityCreateOperation.java index f4bae23cf56c6..bcb6dec2d74a1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityCreateOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityCreateOperation.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.entityoperations; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; /** * The Interface EntityCreateOperation. @@ -23,11 +23,12 @@ * @param * the generic type */ -public interface EntityCreateOperation extends EntityOperationSingleResult { +public interface EntityCreateOperation extends + EntityOperationSingleResult { /** - * Get the object to be sent to the server containing - * the request data for entity creation. + * Get the object to be sent to the server containing the request data for + * entity creation. * * @return The payload to be marshalled and sent to the server. * @throws ServiceException diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityDeleteOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityDeleteOperation.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityDeleteOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityDeleteOperation.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityGetOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityGetOperation.java similarity index 99% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityGetOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityGetOperation.java index b39759add5f3b..f9a34fce9990f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityGetOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityGetOperation.java @@ -15,7 +15,6 @@ package com.microsoft.windowsazure.services.media.entityoperations; - /** * Get operation for Entities * diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityLinkOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityLinkOperation.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityLinkOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityLinkOperation.java index 19503c49548fb..d0ea4e7ffcc2f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityLinkOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityLinkOperation.java @@ -75,8 +75,8 @@ public class EntityLinkOperation extends DefaultActionOperation { * @param secondaryEntityUri * the secondary entity uri */ - public EntityLinkOperation(String primaryEntitySet, String primaryEntityId, String secondaryEntitySet, - URI secondaryEntityUri) { + public EntityLinkOperation(String primaryEntitySet, String primaryEntityId, + String secondaryEntitySet, URI secondaryEntityUri) { super(); this.primaryEntitySet = primaryEntitySet; this.primaryEntityId = primaryEntityId; @@ -84,64 +84,73 @@ public EntityLinkOperation(String primaryEntitySet, String primaryEntityId, Stri this.secondaryEntityUri = secondaryEntityUri; try { jaxbContext = JAXBContext.newInstance(MediaUriType.class); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); } try { marshaller = jaxbContext.createMarshaller(); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); } documentBuilderFactory = DocumentBuilderFactory.newInstance(); try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); - } - catch (ParserConfigurationException e) { + } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityDeleteOperation#getUri() + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entities.EntityDeleteOperation + * #getUri() */ @Override public String getUri() { String escapedEntityId; try { escapedEntityId = URLEncoder.encode(primaryEntityId, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new InvalidParameterException( + "UTF-8 encoding is not supported."); } - catch (UnsupportedEncodingException e) { - throw new InvalidParameterException("UTF-8 encoding is not supported."); - } - return String.format("%s('%s')/$links/%s", primaryEntitySet, escapedEntityId, secondaryEntitySet); + return String.format("%s('%s')/$links/%s", primaryEntitySet, + escapedEntityId, secondaryEntitySet); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.DefaultActionOperation#getVerb() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * DefaultActionOperation#getVerb() */ @Override public String getVerb() { return "POST"; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.DefaultActionOperation#getRequestContents() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * DefaultActionOperation#getRequestContents() */ @Override public Object getRequestContents() { MediaUriType mediaUriType = new MediaUriType(); - mediaUriType.setUri(getProxyData().getServiceUri().toString() + this.secondaryEntityUri.toString()); - JAXBElement mediaUriTypeElement = new JAXBElement(new QName( - Constants.ODATA_DATA_NS, "uri"), MediaUriType.class, mediaUriType); + mediaUriType.setUri(getProxyData().getServiceUri().toString() + + this.secondaryEntityUri.toString()); + JAXBElement mediaUriTypeElement = new JAXBElement( + new QName(Constants.ODATA_DATA_NS, "uri"), MediaUriType.class, + mediaUriType); Document document = documentBuilder.newDocument(); document.setXmlStandalone(true); try { marshaller.marshal(mediaUriTypeElement, document); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); } return document; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityListOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityListOperation.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityListOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityListOperation.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperation.java similarity index 96% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperation.java index 4317bd39f08d2..7c824905301e5 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperation.java @@ -17,7 +17,7 @@ import javax.ws.rs.core.MediaType; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; public interface EntityOperation { @@ -58,4 +58,5 @@ public interface EntityOperation { * the service exception */ Object processResponse(Object rawResponse) throws ServiceException; + } diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationBase.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationBase.java new file mode 100644 index 0000000000000..da30c9d996216 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationBase.java @@ -0,0 +1,210 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.entityoperations; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.security.InvalidParameterException; + +import javax.ws.rs.core.MediaType; + +import com.microsoft.windowsazure.exception.ServiceException; + +/** + * Default implementation of EntityOperation to provide default values for + * common methods. + * + */ +public abstract class EntityOperationBase implements EntityOperation { + + /** The uri builder. */ + private final EntityUriBuilder uriBuilder; + + /** The proxy data. */ + private EntityProxyData proxyData; + + /** + * Instantiates a new entity operation base. + * + * @param uri + * the uri + */ + protected EntityOperationBase(final String uri) { + this.uriBuilder = new EntityUriBuilder() { + @Override + public String getUri() { + return uri; + } + }; + } + + /** + * Instantiates a new entity operation base. + * + * @param uriBuilder + * the uri builder + */ + protected EntityOperationBase(EntityUriBuilder uriBuilder) { + this.uriBuilder = uriBuilder; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #setProxyData(com.microsoft.windowsazure.services.media.entityoperations. + * EntityProxyData) + */ + @Override + public void setProxyData(EntityProxyData proxyData) { + this.proxyData = proxyData; + } + + /** + * Get the currently set proxy data. + * + * @return the proxy data + */ + protected EntityProxyData getProxyData() { + return proxyData; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entities.EntityOperation#getUri + * () + */ + @Override + public String getUri() { + return uriBuilder.getUri(); + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entities.EntityOperation# + * getContentType() + */ + @Override + public MediaType getContentType() { + return MediaType.APPLICATION_ATOM_XML_TYPE; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entities.EntityOperation# + * getAcceptType() + */ + @Override + public MediaType getAcceptType() { + return MediaType.APPLICATION_ATOM_XML_TYPE; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityOperation + * #processResponse(java.lang.Object) + */ + @Override + public Object processResponse(Object rawResponse) throws ServiceException { + return rawResponse; + } + + /** + * The Interface EntityUriBuilder. + */ + public interface EntityUriBuilder { + + /** + * Gets the uri. + * + * @return the uri + */ + String getUri(); + } + + /** + * The Class EntityIdUriBuilder. + */ + public static class EntityIdUriBuilder implements EntityUriBuilder { + + /** The entity type. */ + private final String entityType; + + /** The entity id. */ + private final String entityId; + + /** The action name. */ + private String actionName; + + /** + * Instantiates a new entity id uri builder. + * + * @param entityName + * the entity name + * @param entityId + * the entity id + */ + public EntityIdUriBuilder(String entityName, String entityId) { + super(); + this.entityType = entityName; + this.entityId = entityId; + } + + /** + * Sets the action name. + * + * @param actionName + * the action name + * @return the entity id uri builder + */ + public EntityIdUriBuilder setActionName(String actionName) { + this.actionName = actionName; + return this; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entities.EntityOperationBase + * .EntityUriBuilder#getUri() + */ + @Override + public String getUri() { + String escapedEntityId; + try { + escapedEntityId = URLEncoder.encode(entityId, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new InvalidParameterException(entityId); + } + String result = null; + if ((this.actionName == null) || this.actionName.isEmpty()) { + result = String.format("%s('%s')", entityType, escapedEntityId); + } else { + result = String.format("%s('%s')/%s", entityType, + escapedEntityId, this.actionName); + } + return result; + } + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResult.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResult.java similarity index 96% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResult.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResult.java index 67586641b5f8b..9ea3312855e36 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResult.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResult.java @@ -17,8 +17,8 @@ public interface EntityOperationSingleResult extends EntityOperation { /** - * Get the Java class object for the type that the response should - * be unmarshalled into. + * Get the Java class object for the type that the response should be + * unmarshalled into. * * @return Class object for response. */ diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResultBase.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResultBase.java new file mode 100644 index 0000000000000..d10c04b1a63fb --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResultBase.java @@ -0,0 +1,57 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.entityoperations; + +import com.microsoft.windowsazure.exception.ServiceException; + +/** + * + * + */ +public class EntityOperationSingleResultBase extends EntityOperationBase + implements EntityOperationSingleResult { + private final Class responseClass; + + /** + * + */ + public EntityOperationSingleResultBase(String uri, Class responseClass) { + super(uri); + this.responseClass = responseClass; + } + + public EntityOperationSingleResultBase( + EntityOperationBase.EntityUriBuilder uriBuilder, + Class responseClass) { + super(uriBuilder); + this.responseClass = responseClass; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entities. + * EntityOperationSingleResult#getResponseClass() + */ + @Override + public Class getResponseClass() { + return responseClass; + } + + public Object processResponse(Object rawResponse) throws ServiceException { + return rawResponse; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityProxyData.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityProxyData.java similarity index 83% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityProxyData.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityProxyData.java index d0c21b9ec01a4..ec5a3c688b03d 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityProxyData.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityProxyData.java @@ -18,14 +18,13 @@ import java.net.URI; /** - * Interface used to communicate details about the proxy to - * the operations, if they need it. + * Interface used to communicate details about the proxy to the operations, if + * they need it. * */ public interface EntityProxyData { /** - * Gets the absolute URI currently being - * used by proxy. + * Gets the absolute URI currently being used by proxy. * * @return The URI */ diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityRestProxy.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityRestProxy.java new file mode 100644 index 0000000000000..8e84dda5df421 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityRestProxy.java @@ -0,0 +1,277 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.entityoperations; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.ws.rs.core.MediaType; + +import com.microsoft.windowsazure.core.pipeline.PipelineHelpers; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; +import com.sun.jersey.api.client.filter.ClientFilter; + +/** + * The Class EntityRestProxy. + */ +public abstract class EntityRestProxy implements EntityContract { + + /** The executor service. */ + private final ExecutorService executorService; + /** The channel. */ + private final Client channel; + /** The filters. */ + private final ClientFilter[] filters; + + /** + * Instantiates a new entity rest proxy. + * + * @param channel + * the channel + * @param filters + * the filters + */ + public EntityRestProxy(Client channel, ClientFilter[] filters) { + this.channel = channel; + this.filters = filters; + this.executorService = Executors.newCachedThreadPool(); + } + + /** + * Gets the channel. + * + * @return the channel + */ + protected Client getChannel() { + return channel; + } + + /** + * Gets the executor service. + * + * @return the executor service + */ + protected ExecutorService getExecutorService() { + return executorService; + } + + /** + * Gets the filters. + * + * @return the filters + */ + protected ClientFilter[] getFilters() { + return filters; + } + + /** + * Get the proxy data to pass to operations. + * + * @return The proxy data. + */ + protected abstract EntityProxyData createProxyData(); + + /** + * Gets the resource. + * + * @param entityName + * the entity name + * @return the resource + */ + private WebResource getResource(String entityName) { + WebResource resource = channel.resource(entityName); + for (ClientFilter filter : filters) { + resource.addFilter(filter); + } + return resource; + } + + /** + * Gets the resource. + * + * @param operation + * the operation + * @return the resource + * @throws ServiceException + * the service exception + */ + private Builder getResource(EntityOperation operation) + throws ServiceException { + return getResource(operation.getUri()).type(operation.getContentType()) + .accept(operation.getAcceptType()); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #create(com.microsoft.windowsazure.services.media.entityoperations. + * EntityCreateOperation) + */ + @SuppressWarnings("unchecked") + @Override + public T create(EntityCreateOperation creator) + throws ServiceException { + creator.setProxyData(createProxyData()); + Object rawResponse = getResource(creator).post( + creator.getResponseClass(), creator.getRequestContents()); + Object processedResponse = creator.processResponse(rawResponse); + return (T) processedResponse; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #get(com.microsoft.windowsazure.services.media.entityoperations. + * EntityGetOperation) + */ + @SuppressWarnings("unchecked") + @Override + public T get(EntityGetOperation getter) throws ServiceException { + getter.setProxyData(createProxyData()); + Object rawResponse = getResource(getter).get(getter.getResponseClass()); + Object processedResponse = getter.processResponse(rawResponse); + return (T) processedResponse; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #list(com.microsoft.windowsazure.services.media.entityoperations. + * EntityListOperation) + */ + @SuppressWarnings("unchecked") + @Override + public ListResult list(EntityListOperation lister) + throws ServiceException { + lister.setProxyData(createProxyData()); + Object rawResponse = getResource(lister.getUri()) + .queryParams(lister.getQueryParameters()) + .type(lister.getContentType()).accept(lister.getAcceptType()) + .get(lister.getResponseGenericType()); + Object processedResponse = lister.processResponse(rawResponse); + return (ListResult) processedResponse; + + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #update(com.microsoft.windowsazure.services.media.entityoperations. + * EntityUpdateOperation) + */ + @Override + public void update(EntityUpdateOperation updater) throws ServiceException { + updater.setProxyData(createProxyData()); + Object rawResponse = getResource(updater).header("X-HTTP-METHOD", + "MERGE").post(ClientResponse.class, + updater.getRequestContents()); + PipelineHelpers.throwIfNotSuccess((ClientResponse) rawResponse); + updater.processResponse(rawResponse); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #delete(com.microsoft.windowsazure.services.media.entityoperations. + * EntityDeleteOperation) + */ + @Override + public void delete(EntityDeleteOperation deleter) throws ServiceException { + deleter.setProxyData(createProxyData()); + getResource(deleter.getUri()).delete(); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #action(com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation) + */ + @Override + public T action(EntityTypeActionOperation entityTypeActionOperation) + throws ServiceException { + entityTypeActionOperation.setProxyData(createProxyData()); + Builder webResource = getResource(entityTypeActionOperation.getUri()) + .queryParams(entityTypeActionOperation.getQueryParameters()) + .accept(entityTypeActionOperation.getAcceptType()) + .accept(MediaType.APPLICATION_XML_TYPE) + .entity(entityTypeActionOperation.getRequestContents(), + MediaType.APPLICATION_XML_TYPE) + .type(MediaType.APPLICATION_XML); + + ClientResponse clientResponse = webResource.method( + entityTypeActionOperation.getVerb(), ClientResponse.class); + return entityTypeActionOperation.processTypeResponse(clientResponse); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #action(com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation) + */ + @Override + public void action(EntityActionOperation entityActionOperation) + throws ServiceException { + entityActionOperation + .processResponse(getActionClientResponse(entityActionOperation)); + } + + /** + * Gets the action client response. + * + * @param entityActionOperation + * the entity action operation + * @return the action client response + */ + private ClientResponse getActionClientResponse( + EntityActionOperation entityActionOperation) { + entityActionOperation.setProxyData(createProxyData()); + Builder webResource = getResource(entityActionOperation.getUri()) + .queryParams(entityActionOperation.getQueryParameters()) + .accept(entityActionOperation.getAcceptType()) + .accept(MediaType.APPLICATION_XML_TYPE) + .type(MediaType.APPLICATION_XML_TYPE); + if (entityActionOperation.getRequestContents() != null) { + webResource = webResource.entity( + entityActionOperation.getRequestContents(), + entityActionOperation.getContentType()); + } else { + webResource = webResource.header("Content-Length", "0"); + } + return webResource.method(entityActionOperation.getVerb(), + ClientResponse.class); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityTypeActionOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityTypeActionOperation.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityTypeActionOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityTypeActionOperation.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityUpdateOperation.java b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityUpdateOperation.java similarity index 90% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityUpdateOperation.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityUpdateOperation.java index 89e474bc8e41a..7917c91a24dd4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityUpdateOperation.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityUpdateOperation.java @@ -21,8 +21,7 @@ */ public interface EntityUpdateOperation extends EntityOperation { /** - * Get the contents of the merge request that will - * be sent to the server. + * Get the contents of the merge request that will be sent to the server. * * @return The payload object */ diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/package.html b/media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/package.html diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ActiveToken.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ActiveToken.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ActiveToken.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ActiveToken.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperations.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperations.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperations.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperations.java index b7e99a44e1012..db382635a597a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperations.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperations.java @@ -43,14 +43,14 @@ import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.core.utils.InputStreamDataSource; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.entityoperations.EntityBatchOperation; import com.microsoft.windowsazure.services.media.implementation.atom.EntryType; import com.microsoft.windowsazure.services.media.models.Job; import com.microsoft.windowsazure.services.media.models.JobInfo; import com.microsoft.windowsazure.services.media.models.Task; import com.microsoft.windowsazure.services.media.models.TaskInfo; -import com.microsoft.windowsazure.services.table.implementation.InputStreamDataSource; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.core.header.InBoundHeaders; @@ -87,9 +87,11 @@ public class MediaBatchOperations { * @throws ParserConfigurationException * @throws JAXBException */ - public MediaBatchOperations(URI serviceURI) throws JAXBException, ParserConfigurationException { + public MediaBatchOperations(URI serviceURI) throws JAXBException, + ParserConfigurationException { if (serviceURI == null) { - throw new IllegalArgumentException("The service URI cannot be null."); + throw new IllegalArgumentException( + "The service URI cannot be null."); } this.serviceURI = serviceURI; this.oDataAtomMarshaller = new ODataAtomMarshaller(); @@ -109,7 +111,8 @@ public MediaBatchOperations(URI serviceURI) throws JAXBException, ParserConfigur * @throws JAXBException * the jAXB exception */ - public MimeMultipart getMimeMultipart() throws MessagingException, IOException, JAXBException { + public MimeMultipart getMimeMultipart() throws MessagingException, + IOException, JAXBException { List bodyPartContents = createRequestBody(); return toMimeMultipart(bodyPartContents); @@ -123,7 +126,8 @@ private List createRequestBody() throws JAXBException { int jobContentId = addJobPart(bodyPartContents, jobURI, contentId); contentId++; - URI taskURI = UriBuilder.fromUri(serviceURI).path(String.format("$%d", jobContentId)).path("Tasks").build(); + URI taskURI = UriBuilder.fromUri(serviceURI) + .path(String.format("$%d", jobContentId)).path("Tasks").build(); addTaskPart(bodyPartContents, taskURI, contentId); return bodyPartContents; @@ -140,7 +144,8 @@ private List createRequestBody() throws JAXBException { * @throws JAXBException * the jAXB exception */ - private int addJobPart(List bodyPartContents, URI jobURI, int contentId) throws JAXBException { + private int addJobPart(List bodyPartContents, URI jobURI, + int contentId) throws JAXBException { int jobContentId = contentId; validateJobOperation(); @@ -149,8 +154,10 @@ private int addJobPart(List bodyPartContents, URI jobURI, int conten if (entityBatchOperation instanceof Job.CreateBatchOperation) { Job.CreateBatchOperation jobCreateBatchOperation = (Job.CreateBatchOperation) entityBatchOperation; jobContentId = contentId; - bodyPartContent = createBatchCreateEntityPart(jobCreateBatchOperation.getVerb(), "Jobs", - jobCreateBatchOperation.getEntryType(), jobURI, contentId); + bodyPartContent = createBatchCreateEntityPart( + jobCreateBatchOperation.getVerb(), "Jobs", + jobCreateBatchOperation.getEntryType(), jobURI, + contentId); contentId++; if (bodyPartContent != null) { bodyPartContents.add(bodyPartContent); @@ -170,8 +177,10 @@ private void validateJobOperation() { } if (jobCount != 1) { - throw new IllegalArgumentException(String.format( - "The Job operation is invalid, expect 1 but get %s job(s). ", jobCount)); + throw new IllegalArgumentException( + String.format( + "The Job operation is invalid, expect 1 but get %s job(s). ", + jobCount)); } } @@ -187,12 +196,14 @@ private void validateJobOperation() { * @throws JAXBException * the jAXB exception */ - private void addTaskPart(List bodyPartContents, URI taskURI, int contentId) throws JAXBException { + private void addTaskPart(List bodyPartContents, URI taskURI, + int contentId) throws JAXBException { for (EntityBatchOperation entityBatchOperation : entityBatchOperations) { DataSource bodyPartContent = null; if (entityBatchOperation instanceof Task.CreateBatchOperation) { Task.CreateBatchOperation createTaskOperation = (Task.CreateBatchOperation) entityBatchOperation; - bodyPartContent = createBatchCreateEntityPart(createTaskOperation.getVerb(), "Tasks", + bodyPartContent = createBatchCreateEntityPart( + createTaskOperation.getVerb(), "Tasks", createTaskOperation.getEntryType(), taskURI, contentId); contentId++; } @@ -214,29 +225,36 @@ private void addTaskPart(List bodyPartContents, URI taskURI, int con * @throws IOException * Signals that an I/O exception has occurred. */ - private MimeMultipart toMimeMultipart(List bodyPartContents) throws MessagingException, IOException { - String changeSetId = String.format("changeset_%s", UUID.randomUUID().toString()); - MimeMultipart changeSets = createChangeSets(bodyPartContents, changeSetId); + private MimeMultipart toMimeMultipart(List bodyPartContents) + throws MessagingException, IOException { + String changeSetId = String.format("changeset_%s", UUID.randomUUID() + .toString()); + MimeMultipart changeSets = createChangeSets(bodyPartContents, + changeSetId); MimeBodyPart mimeBodyPart = createMimeBodyPart(changeSets, changeSetId); - MimeMultipart mimeMultipart = new MimeMultipart(new SetBoundaryMultipartDataSource(batchId)); + MimeMultipart mimeMultipart = new MimeMultipart( + new SetBoundaryMultipartDataSource(batchId)); mimeMultipart.addBodyPart(mimeBodyPart); return mimeMultipart; } - private MimeBodyPart createMimeBodyPart(MimeMultipart changeSets, String changeSetId) throws MessagingException { + private MimeBodyPart createMimeBodyPart(MimeMultipart changeSets, + String changeSetId) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(changeSets); - String contentType = String.format("multipart/mixed; boundary=%s", changeSetId); + String contentType = String.format("multipart/mixed; boundary=%s", + changeSetId); mimeBodyPart.setHeader("Content-Type", contentType); return mimeBodyPart; } - private MimeMultipart createChangeSets(List bodyPartContents, String changeSetId) - throws MessagingException { + private MimeMultipart createChangeSets(List bodyPartContents, + String changeSetId) throws MessagingException { - MimeMultipart changeSets = new MimeMultipart(new SetBoundaryMultipartDataSource(changeSetId)); + MimeMultipart changeSets = new MimeMultipart( + new SetBoundaryMultipartDataSource(changeSetId)); for (DataSource bodyPart : bodyPartContents) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); @@ -266,8 +284,9 @@ private MimeMultipart createChangeSets(List bodyPartContents, String * @throws JAXBException * the jAXB exception */ - private DataSource createBatchCreateEntityPart(String verb, String entityName, EntryType entryType, URI uri, - int contentId) throws JAXBException { + private DataSource createBatchCreateEntityPart(String verb, + String entityName, EntryType entryType, URI uri, int contentId) + throws JAXBException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); this.oDataAtomMarshaller.marshalEntryType(entryType, stream); byte[] bytes = stream.toByteArray(); @@ -286,7 +305,8 @@ private DataSource createBatchCreateEntityPart(String verb, String entityName, E appendHeaders(httpRequest, headers); appendEntity(httpRequest, new ByteArrayInputStream(bytes)); - DataSource bodyPartContent = new InputStreamDataSource(new ByteArrayInputStream(httpRequest.toByteArray()), + DataSource bodyPartContent = new InputStreamDataSource( + new ByteArrayInputStream(httpRequest.toByteArray()), "application/http"); return bodyPartContent; } @@ -303,11 +323,13 @@ private DataSource createBatchCreateEntityPart(String verb, String entityName, E * @throws ServiceException * the service exception */ - public void parseBatchResult(ClientResponse response) throws IOException, ServiceException { + public void parseBatchResult(ClientResponse response) throws IOException, + ServiceException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); InputStream inputStream = response.getEntityInputStream(); ReaderWriter.writeTo(inputStream, byteArrayOutputStream); - response.setEntityInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); + response.setEntityInputStream(new ByteArrayInputStream( + byteArrayOutputStream.toByteArray())); JobInfo jobInfo; List parts = parseParts(response.getEntityInputStream(), @@ -316,13 +338,14 @@ public void parseBatchResult(ClientResponse response) throws IOException, Servic if (parts.size() == 0 || parts.size() > entityBatchOperations.size()) { throw new UniformInterfaceException(String.format( "Batch response from server does not contain the correct amount " - + "of parts (expecting %d, received %d instead)", parts.size(), - entityBatchOperations.size()), response); + + "of parts (expecting %d, received %d instead)", + parts.size(), entityBatchOperations.size()), response); } for (int i = 0; i < parts.size(); i++) { DataSource ds = parts.get(i); - EntityBatchOperation entityBatchOperation = entityBatchOperations.get(i); + EntityBatchOperation entityBatchOperation = entityBatchOperations + .get(i); StatusLine status = StatusLine.create(ds); InternetHeaders headers = parseHeaders(ds); @@ -335,30 +358,31 @@ public void parseBatchResult(ClientResponse response) throws IOException, Servic Enumeration

e = headers.getAllHeaders(); while (e.hasMoreElements()) { Header header = e.nextElement(); - inBoundHeaders.putSingle(header.getName(), header.getValue()); + inBoundHeaders.putSingle(header.getName(), + header.getValue()); } - ClientResponse clientResponse = new ClientResponse(status.getStatus(), inBoundHeaders, content, null); + ClientResponse clientResponse = new ClientResponse( + status.getStatus(), inBoundHeaders, content, null); - UniformInterfaceException uniformInterfaceException = new UniformInterfaceException(clientResponse); + UniformInterfaceException uniformInterfaceException = new UniformInterfaceException( + clientResponse); throw uniformInterfaceException; - } - else if (entityBatchOperation instanceof Job.CreateBatchOperation) { + } else if (entityBatchOperation instanceof Job.CreateBatchOperation) { try { - jobInfo = oDataAtomUnmarshaller.unmarshalEntry(content, JobInfo.class); + jobInfo = oDataAtomUnmarshaller.unmarshalEntry(content, + JobInfo.class); Job.CreateBatchOperation jobCreateBatchOperation = (Job.CreateBatchOperation) entityBatchOperation; jobCreateBatchOperation.setJobInfo(jobInfo); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new ServiceException(e); } - } - else if (entityBatchOperation instanceof Task.CreateBatchOperation) { + } else if (entityBatchOperation instanceof Task.CreateBatchOperation) { try { - oDataAtomUnmarshaller.unmarshalEntry(content, TaskInfo.class); - } - catch (JAXBException e) { + oDataAtomUnmarshaller.unmarshalEntry(content, + TaskInfo.class); + } catch (JAXBException e) { throw new ServiceException(e); } } @@ -375,11 +399,9 @@ else if (entityBatchOperation instanceof Task.CreateBatchOperation) { private InternetHeaders parseHeaders(DataSource ds) { try { return new InternetHeaders(ds.getInputStream()); - } - catch (MessagingException e) { + } catch (MessagingException e) { throw new RuntimeException(e); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } @@ -394,8 +416,7 @@ private InternetHeaders parseHeaders(DataSource ds) { private InputStream parseEntity(DataSource ds) { try { return ds.getInputStream(); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } @@ -409,14 +430,13 @@ private InputStream parseEntity(DataSource ds) { * the content type * @return the list */ - private List parseParts(final InputStream entityInputStream, final String contentType) { + private List parseParts(final InputStream entityInputStream, + final String contentType) { try { return parsePartsCore(entityInputStream, contentType); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); - } - catch (MessagingException e) { + } catch (MessagingException e) { throw new RuntimeException(e); } } @@ -434,19 +454,22 @@ private List parseParts(final InputStream entityInputStream, final S * @throws IOException * Signals that an I/O exception has occurred. */ - private List parsePartsCore(InputStream entityInputStream, String contentType) - throws MessagingException, IOException { - DataSource dataSource = new InputStreamDataSource(entityInputStream, contentType); + private List parsePartsCore(InputStream entityInputStream, + String contentType) throws MessagingException, IOException { + DataSource dataSource = new InputStreamDataSource(entityInputStream, + contentType); MimeMultipart batch = new MimeMultipart(dataSource); MimeBodyPart batchBody = (MimeBodyPart) batch.getBodyPart(0); - MimeMultipart changeSets = new MimeMultipart(new MimePartDataSource(batchBody)); + MimeMultipart changeSets = new MimeMultipart(new MimePartDataSource( + batchBody)); List result = new ArrayList(); for (int i = 0; i < changeSets.getCount(); i++) { BodyPart part = changeSets.getBodyPart(i); - result.add(new InputStreamDataSource(part.getInputStream(), part.getContentType())); + result.add(new InputStreamDataSource(part.getInputStream(), part + .getContentType())); } return result; } @@ -471,15 +494,14 @@ public void addOperation(EntityBatchOperation entityBatchOperation) { * @param uri * the uri */ - private void addHttpMethod(ByteArrayOutputStream outputStream, String verb, URI uri) { + private void addHttpMethod(ByteArrayOutputStream outputStream, String verb, + URI uri) { try { String method = String.format("%s %s HTTP/1.1\r\n", verb, uri); outputStream.write(method.getBytes("UTF-8")); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } @@ -492,24 +514,24 @@ private void addHttpMethod(ByteArrayOutputStream outputStream, String verb, URI * @param internetHeaders * the internet headers */ - private void appendHeaders(OutputStream outputStream, InternetHeaders internetHeaders) { + private void appendHeaders(OutputStream outputStream, + InternetHeaders internetHeaders) { try { // Headers @SuppressWarnings("unchecked") Enumeration
headers = internetHeaders.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); - String headerLine = String.format("%s: %s\r\n", header.getName(), header.getValue()); + String headerLine = String.format("%s: %s\r\n", + header.getName(), header.getValue()); outputStream.write(headerLine.getBytes("UTF-8")); } // Empty line outputStream.write("\r\n".getBytes("UTF-8")); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } @@ -522,7 +544,8 @@ private void appendHeaders(OutputStream outputStream, InternetHeaders internetHe * @param byteArrayInputStream * the byte array input stream */ - private void appendEntity(OutputStream outputStream, ByteArrayInputStream byteArrayInputStream) { + private void appendEntity(OutputStream outputStream, + ByteArrayInputStream byteArrayInputStream) { try { byte[] buffer = new byte[BUFFER_SIZE]; while (true) { @@ -532,8 +555,7 @@ private void appendEntity(OutputStream outputStream, ByteArrayInputStream byteAr } outputStream.write(buffer, 0, bytesRead); } - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobContainerWriter.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobContainerWriter.java new file mode 100644 index 0000000000000..7adaed6ad3ed6 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobContainerWriter.java @@ -0,0 +1,248 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import java.io.InputStream; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.blob.BlobContract; +import com.microsoft.windowsazure.services.blob.implementation.BlobExceptionProcessor; +import com.microsoft.windowsazure.services.blob.models.BlockList; +import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; +import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; +import com.sun.jersey.api.client.Client; + +/** + * Implementation of WritableBlobContainerContract, used to upload blobs to the + * Media Services storage. + * + */ +public class MediaBlobContainerWriter implements WritableBlobContainerContract { + + private final BlobContract blobService; + private BlobContract restProxy; + + public BlobContract getBlobContract() { + return this.restProxy; + } + + public void setBlobContract(BlobContract blobContract) { + this.restProxy = blobContract; + } + + private final String containerName; + + public MediaBlobContainerWriter(Client client, String accountName, + String blobServiceUri, String containerName, String sasToken) { + this.containerName = containerName; + this.restProxy = new MediaBlobRestProxy(client, accountName, + blobServiceUri, new SASTokenFilter(sasToken)); + this.blobService = new BlobExceptionProcessor(this.restProxy); + } + + private MediaBlobContainerWriter(MediaBlobContainerWriter baseWriter, + ServiceFilter filter) { + this.containerName = baseWriter.containerName; + this.restProxy = baseWriter.restProxy.withFilter(filter); + this.blobService = new BlobExceptionProcessor(this.restProxy); + } + + private MediaBlobContainerWriter(MediaBlobContainerWriter baseWriter) { + this.containerName = baseWriter.containerName; + this.restProxy = baseWriter.restProxy; + this.blobService = new BlobExceptionProcessor(this.restProxy); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.core.JerseyFilterableService#withFilter + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public WritableBlobContainerContract withFilter(ServiceFilter filter) { + MediaBlobContainerWriter mediaBlobContainerWriter = new MediaBlobContainerWriter( + this, filter); + return mediaBlobContainerWriter; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withRequestFilterFirst + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public WritableBlobContainerContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + MediaBlobContainerWriter mediaBlobContainerWriter = new MediaBlobContainerWriter( + this); + mediaBlobContainerWriter + .setBlobContract(mediaBlobContainerWriter.getBlobContract() + .withRequestFilterFirst(serviceRequestFilter)); + return mediaBlobContainerWriter; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withRequestFilterLast + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public WritableBlobContainerContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + MediaBlobContainerWriter mediaBlobContainerWriter = new MediaBlobContainerWriter( + this); + mediaBlobContainerWriter.setBlobContract(mediaBlobContainerWriter + .getBlobContract().withRequestFilterLast(serviceRequestFilter)); + return mediaBlobContainerWriter; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withResponseFilterFirst + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public WritableBlobContainerContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + MediaBlobContainerWriter mediaBlobContainerWriter = new MediaBlobContainerWriter( + this); + mediaBlobContainerWriter.setBlobContract(mediaBlobContainerWriter + .getBlobContract().withResponseFilterFirst( + serviceResponseFilter)); + return mediaBlobContainerWriter; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withResponseFilterLast + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public WritableBlobContainerContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + MediaBlobContainerWriter mediaBlobContainerWriter = new MediaBlobContainerWriter( + this); + mediaBlobContainerWriter.setBlobContract(mediaBlobContainerWriter + .getBlobContract() + .withResponseFilterLast(serviceResponseFilter)); + return mediaBlobContainerWriter; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.WritableBlobContainerContract + * #createBlockBlob(java.lang.String, java.io.InputStream) + */ + @Override + public CreateBlobResult createBlockBlob(String blob, + InputStream contentStream) throws ServiceException { + return blobService.createBlockBlob(containerName, blob, contentStream); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.WritableBlobContainerContract + * #createBlockBlob(java.lang.String, java.io.InputStream, + * com.microsoft.windowsazure.services.blob.models.CreateBlobOptions) + */ + @Override + public CreateBlobResult createBlockBlob(String blob, + InputStream contentStream, CreateBlobOptions options) + throws ServiceException { + return blobService.createBlockBlob(containerName, blob, contentStream, + options); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.WritableBlobContainerContract + * #createBlobBlock(java.lang.String, java.lang.String, java.io.InputStream) + */ + @Override + public void createBlobBlock(String blob, String blockId, + InputStream contentStream) throws ServiceException { + blobService + .createBlobBlock(containerName, blob, blockId, contentStream); + + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.WritableBlobContainerContract + * #createBlobBlock(java.lang.String, java.lang.String, java.io.InputStream, + * com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions) + */ + @Override + public void createBlobBlock(String blob, String blockId, + InputStream contentStream, CreateBlobBlockOptions options) + throws ServiceException { + blobService.createBlobBlock(containerName, blob, blockId, + contentStream, options); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.WritableBlobContainerContract + * #commitBlobBlocks(java.lang.String, + * com.microsoft.windowsazure.services.blob.models.BlockList) + */ + @Override + public void commitBlobBlocks(String blob, BlockList blockList) + throws ServiceException { + blobService.commitBlobBlocks(containerName, blob, blockList); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.WritableBlobContainerContract + * #commitBlobBlocks(java.lang.String, + * com.microsoft.windowsazure.services.blob.models.BlockList, + * com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions) + */ + @Override + public void commitBlobBlocks(String blob, BlockList blockList, + CommitBlobBlocksOptions options) throws ServiceException { + blobService.commitBlobBlocks(containerName, blob, blockList, options); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobRestProxy.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobRestProxy.java new file mode 100644 index 0000000000000..d6ddadfae219e --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobRestProxy.java @@ -0,0 +1,147 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import java.util.Arrays; + +import com.microsoft.windowsazure.core.RFC1123DateConverter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterRequestAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterResponseAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.services.blob.BlobContract; +import com.microsoft.windowsazure.services.blob.implementation.BlobOperationRestProxy; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.filter.ClientFilter; + +/** + * Rest proxy for blob operations that's specialized for working with the blobs + * created by and for Media Services storage. + * + */ +class MediaBlobRestProxy extends BlobOperationRestProxy { + private final SASTokenFilter tokenFilter; + + /** + * Construct instance of MediaBlobRestProxy with given parameters. + * + * @param channel + * Jersey Client object used to communicate with blob service + * @param accountName + * Account name for blob storage + * @param url + * URL for blob storage + * @param tokenFilter + * filter used to add SAS tokens to requests. + */ + public MediaBlobRestProxy(Client channel, String accountName, String url, + SASTokenFilter tokenFilter) { + super(channel, accountName, url); + + this.tokenFilter = tokenFilter; + channel.addFilter(tokenFilter); + } + + /** + * Construct instance of MediaBlobRestProxy with given parameters. + * + * @param channel + * Jersey Client object used to communicate with blob service + * @param filters + * Additional ServiceFilters to manipulate requests and responses + * @param accountName + * Account name for blob storage + * @param url + * URL for blob storage + * @param dateMapper + * date conversion helper object + */ + public MediaBlobRestProxy(Client channel, ClientFilter[] filters, + String accountName, String url, SASTokenFilter tokenFilter, + RFC1123DateConverter dateMapper) { + super(channel, filters, accountName, url, dateMapper); + + this.tokenFilter = tokenFilter; + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.blob.implementation. + * BlobOperationRestProxy + * #withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public BlobContract withFilter(ServiceFilter filter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterAdapter(filter); + return new MediaBlobRestProxy(getChannel(), newFilters, + getAccountName(), getUrl(), this.tokenFilter, getDateMapper()); + } + + @Override + public BlobContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterRequestAdapter(serviceRequestFilter); + return new MediaBlobRestProxy(getChannel(), newFilters, + getAccountName(), getUrl(), this.tokenFilter, getDateMapper()); + } + + @Override + public BlobContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterRequestAdapter( + serviceRequestFilter); + return new MediaBlobRestProxy(getChannel(), newFilters, + getAccountName(), getUrl(), this.tokenFilter, getDateMapper()); + } + + @Override + public BlobContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterResponseAdapter(serviceResponseFilter); + return new MediaBlobRestProxy(getChannel(), newFilters, + getAccountName(), getUrl(), this.tokenFilter, getDateMapper()); + } + + @Override + public BlobContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterResponseAdapter( + serviceResponseFilter); + return new MediaBlobRestProxy(getChannel(), newFilters, + getAccountName(), getUrl(), this.tokenFilter, getDateMapper()); + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaContentProvider.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaContentProvider.java new file mode 100644 index 0000000000000..e9601e2efa90e --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaContentProvider.java @@ -0,0 +1,83 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.ParserConfigurationException; + +import com.microsoft.windowsazure.services.media.implementation.content.MediaServiceDTO; +import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; + +/** + * Class to plug into Jersey to properly serialize raw Media Services DTO types. + * + */ +public class MediaContentProvider extends + AbstractMessageReaderWriterProvider { + private final ODataAtomMarshaller marshaller; + + /** + * Creates the instance + * + * @throws JAXBException + * @throws ParserConfigurationException + */ + public MediaContentProvider() throws JAXBException, + ParserConfigurationException { + marshaller = new ODataAtomMarshaller(); + } + + @Override + public boolean isReadable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + // This class only does marshalling, not unmarshalling. + return false; + } + + @Override + public T readFrom(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) + throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isWriteable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return MediaServiceDTO.class.isAssignableFrom(type); + } + + @Override + public void writeTo(T t, Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, + OutputStream entityStream) throws IOException { + try { + marshaller.marshalEntry(t, entityStream); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaExceptionProcessor.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaExceptionProcessor.java new file mode 100644 index 0000000000000..5348bf1cfad00 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaExceptionProcessor.java @@ -0,0 +1,278 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import javax.inject.Inject; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import com.microsoft.windowsazure.services.media.MediaContract; +import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; +import com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityDeleteOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityGetOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.UniformInterfaceException; + +/** + * /** Wrapper implementation of MediaEntityContract that + * translates exceptions into ServiceExceptions. + * + */ +public class MediaExceptionProcessor implements MediaContract { + + /** The service. */ + private final MediaContract service; + + /** The log. */ + private static Log log = LogFactory.getLog(MediaContract.class); + + /** + * Instantiates a new media exception processor. + * + * @param service + * the service + */ + public MediaExceptionProcessor(MediaContract service) { + this.service = service; + } + + /** + * Instantiates a new media exception processor. + * + * @param service + * the service + */ + @Inject + public MediaExceptionProcessor(MediaRestProxy service) { + this.service = service; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.core.FilterableService#withFilter + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public MediaContract withFilter(ServiceFilter filter) { + return new MediaExceptionProcessor(service.withFilter(filter)); + } + + @Override + public MediaContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + return new MediaExceptionProcessor( + service.withRequestFilterFirst(serviceRequestFilter)); + } + + @Override + public MediaContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + return new MediaExceptionProcessor( + service.withRequestFilterLast(serviceRequestFilter)); + } + + @Override + public MediaContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + return new MediaExceptionProcessor( + service.withResponseFilterFirst(serviceResponseFilter)); + } + + @Override + public MediaContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + return new MediaExceptionProcessor( + service.withResponseFilterLast(serviceResponseFilter)); + } + + /** + * Process a catch. + * + * @param e + * the e + * @return the service exception + */ + private ServiceException processCatch(ServiceException e) { + log.warn(e.getMessage(), e.getCause()); + return ServiceExceptionFactory.process("MediaServices", e); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #create(com.microsoft.windowsazure.services.media.entityoperations. + * EntityCreateOperation) + */ + @Override + public T create(EntityCreateOperation creator) + throws ServiceException { + try { + return service.create(creator); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #get(com.microsoft.windowsazure.services.media.entityoperations. + * EntityGetOperation) + */ + @Override + public T get(EntityGetOperation getter) throws ServiceException { + try { + return service.get(getter); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #list(com.microsoft.windowsazure.services.media.entityoperations. + * EntityListOperation) + */ + @Override + public ListResult list(EntityListOperation lister) + throws ServiceException { + try { + return service.list(lister); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #update(com.microsoft.windowsazure.services.media.entityoperations. + * EntityUpdateOperation) + */ + @Override + public void update(EntityUpdateOperation updater) throws ServiceException { + try { + service.update(updater); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #delete(com.microsoft.windowsazure.services.media.entityoperations. + * EntityDeleteOperation) + */ + @Override + public void delete(EntityDeleteOperation deleter) throws ServiceException { + try { + service.delete(deleter); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #action(com.microsoft.windowsazure.services.media.entityoperations. + * EntityActionOperation) + */ + @Override + public void action(EntityActionOperation entityActionOperation) + throws ServiceException { + try { + service.action(entityActionOperation); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityContract + * #action(com.microsoft.windowsazure.services.media.entityoperations. + * EntityTypeActionOperation) + */ + @Override + public T action(EntityTypeActionOperation entityTypeActionOperation) + throws ServiceException { + try { + return service.action(entityTypeActionOperation); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.MediaContract#createBlobWriter + * (com.microsoft.windowsazure.services.media.models.LocatorInfo) + */ + @Override + public WritableBlobContainerContract createBlobWriter(LocatorInfo locator) { + return service.createBlobWriter(locator); + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaRestProxy.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaRestProxy.java new file mode 100644 index 0000000000000..ca6bce4fe599d --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaRestProxy.java @@ -0,0 +1,230 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import java.net.URI; +import java.util.Arrays; + +import javax.inject.Inject; + +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientConfigSettings; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterRequestAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterResponseAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.services.media.MediaContract; +import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; +import com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData; +import com.microsoft.windowsazure.services.media.entityoperations.EntityRestProxy; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; +import com.microsoft.windowsazure.services.media.models.LocatorType; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.ClientFilter; + +/** + * The Class MediaRestProxy. + */ +public class MediaRestProxy extends EntityRestProxy implements MediaContract { + /** The redirect filter. */ + private RedirectFilter redirectFilter; + + private final ClientConfigSettings clientConfigSettings; + + /** + * Instantiates a new media rest proxy. + * + * @param channel + * the channel + * @param authFilter + * the auth filter + * @param redirectFilter + * the redirect filter + * @param versionHeadersFilter + * the version headers filter + * @param userAgentFilter + * the user agent filter + * @param clientConfigSettings + * Currently configured HTTP client settings + * + */ + @Inject + public MediaRestProxy(Client channel, OAuthFilter authFilter, + RedirectFilter redirectFilter, + VersionHeadersFilter versionHeadersFilter, + UserAgentFilter userAgentFilter, + ClientConfigSettings clientConfigSettings) { + super(channel, new ClientFilter[0]); + + this.clientConfigSettings = clientConfigSettings; + this.redirectFilter = redirectFilter; + channel.addFilter(redirectFilter); + channel.addFilter(authFilter); + channel.addFilter(versionHeadersFilter); + channel.addFilter(new ClientFilterRequestAdapter(userAgentFilter)); + } + + /** + * Instantiates a new media rest proxy. + * + * @param channel + * the channel + * @param filters + * the filters + * @param clientConfigSettings + * currently configured HTTP client settings + */ + private MediaRestProxy(Client channel, ClientFilter[] filters, + ClientConfigSettings clientConfigSettings) { + super(channel, filters); + this.clientConfigSettings = clientConfigSettings; + } + + @Override + public MediaContract withFilter(ServiceFilter filter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterAdapter(filter); + return new MediaRestProxy(getChannel(), newFilters, + clientConfigSettings); + } + + @Override + public MediaContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterRequestAdapter(serviceRequestFilter); + return new MediaRestProxy(getChannel(), newFilters, + clientConfigSettings); + } + + @Override + public MediaContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterRequestAdapter( + serviceRequestFilter); + return new MediaRestProxy(getChannel(), newFilters, + clientConfigSettings); + } + + @Override + public MediaContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterResponseAdapter(serviceResponseFilter); + return new MediaRestProxy(getChannel(), newFilters, + clientConfigSettings); + } + + @Override + public MediaContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = getFilters(); + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterResponseAdapter( + serviceResponseFilter); + return new MediaRestProxy(getChannel(), newFilters, + clientConfigSettings); + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.entityoperations.EntityRestProxy + * #createProxyData() + */ + @Override + protected EntityProxyData createProxyData() { + return new EntityProxyData() { + @Override + public URI getServiceUri() { + return redirectFilter.getBaseURI(); + } + }; + } + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.media.MediaContract#createBlobWriter + * (com.microsoft.windowsazure.services.media.models.LocatorInfo) + */ + @Override + public WritableBlobContainerContract createBlobWriter(LocatorInfo locator) { + if (locator.getLocatorType() != LocatorType.SAS) { + throw new IllegalArgumentException("Can only write to SAS locators"); + } + + LocatorParser p = new LocatorParser(locator); + + return new MediaBlobContainerWriter(createUploaderClient(), + p.getAccountName(), p.getStorageUri(), p.getContainer(), + p.getSASToken()); + } + + /** + * Helper class to encapsulate pulling information out of the locator. + */ + private static class LocatorParser { + private URI locatorPath; + + public LocatorParser(LocatorInfo locator) { + locatorPath = URI.create(locator.getPath()); + } + + public String getAccountName() { + return locatorPath.getHost().split("\\.")[0]; + } + + public String getStorageUri() { + return locatorPath.getScheme() + "://" + locatorPath.getAuthority(); + } + + public String getContainer() { + return locatorPath.getPath().substring(1); + } + + public String getSASToken() { + return locatorPath.getRawQuery(); + } + } + + private Client createUploaderClient() { + ClientConfig clientConfig = new DefaultClientConfig(); + clientConfigSettings.applyConfig(clientConfig); + Client client = Client.create(clientConfig); + clientConfigSettings.applyConfig(client); + return client; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthContract.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthContract.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthContract.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthContract.java index 603e9b0caeb11..1b570cdc5a2f1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthContract.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthContract.java @@ -17,11 +17,12 @@ import java.net.URI; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; public interface OAuthContract { /** - * Gets an OAuth access token with specified OAUTH URI, client ID, client secret, and scope. + * Gets an OAuth access token with specified OAUTH URI, client ID, client + * secret, and scope. * * @param oAuthUri * A URI object which represents an OAUTH URI. @@ -38,7 +39,7 @@ public interface OAuthContract { * @return OAuthTokenResponse * @throws ServiceException */ - OAuthTokenResponse getAccessToken(URI oAuthUri, String clientId, String clientSecret, String scope) - throws ServiceException; + OAuthTokenResponse getAccessToken(URI oAuthUri, String clientId, + String clientSecret, String scope) throws ServiceException; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthFilter.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthFilter.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthFilter.java index dff2e042c7714..26583f42a9670 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthFilter.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthFilter.java @@ -16,8 +16,8 @@ import java.net.URISyntaxException; -import com.microsoft.windowsazure.services.core.IdempotentClientFilter; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.core.pipeline.jersey.IdempotentClientFilter; +import com.microsoft.windowsazure.exception.ServiceException; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; @@ -30,7 +30,8 @@ public class OAuthFilter extends IdempotentClientFilter { private final OAuthTokenManager oAuthTokenManager; /** - * Creates an OAuthFilter object with specified OAuthTokenManager instance. + * Creates an OAuthFilter object with specified + * OAuthTokenManager instance. * * @param oAuthTokenManager */ @@ -38,24 +39,27 @@ public OAuthFilter(OAuthTokenManager oAuthTokenManager) { this.oAuthTokenManager = oAuthTokenManager; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle(com.sun.jersey.api.client.ClientRequest) + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle + * (com.sun.jersey.api.client.ClientRequest) */@Override public ClientResponse doHandle(ClientRequest clientRequest) { String accessToken; try { accessToken = oAuthTokenManager.getAccessToken(); - } - catch (ServiceException e) { + } catch (ServiceException e) { // must wrap exception because of base class signature throw new ClientHandlerException(e); - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { // must wrap exception because of base class signature throw new ClientHandlerException(e); } - clientRequest.getHeaders().add("Authorization", "Bearer " + accessToken); + clientRequest.getHeaders() + .add("Authorization", "Bearer " + accessToken); return this.getNext().handle(clientRequest); } diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxy.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxy.java new file mode 100644 index 0000000000000..b5d4a1794ce97 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxy.java @@ -0,0 +1,142 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.media.implementation; + +import java.io.IOException; +import java.net.URI; + +import javax.inject.Inject; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.type.TypeReference; + +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterRequestAdapter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.representation.Form; + +/** + * The OAuth rest proxy. + * + */ +public class OAuthRestProxy implements OAuthContract { + private Client channel; + + private final String grantType = "client_credentials"; + + private static Log log = LogFactory.getLog(OAuthContract.class); + + @Inject + public OAuthRestProxy(Client channel, UserAgentFilter userAgentFilter) { + this.channel = channel; + channel.addFilter(new ClientFilterRequestAdapter(userAgentFilter)); + } + + /** + * Gets an OAuth access token with specified OAUTH URI, client ID, client + * secret, and scope. + * + * @param oAuthUri + * A URI object which represents an OAUTH URI. + * + * @param clientId + * A String object which represents a client ID. + * + * @param clientSecret + * A String object which represents a client secret. + * + * @param scope + * A String object which represents the scope. + * + * @return OAuthTokenResponse + * @throws ServiceException + */ + @Override + public OAuthTokenResponse getAccessToken(URI oAuthUri, String clientId, + String clientSecret, String scope) throws ServiceException { + OAuthTokenResponse response = null; + Form requestForm = new Form(); + ClientResponse clientResponse; + String responseJson; + + requestForm.add("grant_type", grantType); + requestForm.add("client_id", clientId); + requestForm.add("client_secret", clientSecret); + requestForm.add("scope", scope); + + try { + clientResponse = channel.resource(oAuthUri) + .accept(MediaType.APPLICATION_FORM_URLENCODED) + .type(MediaType.APPLICATION_FORM_URLENCODED) + .post(ClientResponse.class, requestForm); + } catch (UniformInterfaceException e) { + log.warn("OAuth server returned error acquiring access_token", e); + throw ServiceExceptionFactory + .process( + "OAuth", + new ServiceException( + "OAuth server returned error acquiring access_token", + e)); + } + + responseJson = clientResponse.getEntity(String.class); + + try { + ObjectMapper mapper = new ObjectMapper(); + TypeReference typeReference = new TypeReference() { + }; + response = mapper.readValue(responseJson, typeReference); + } catch (JsonParseException e) { + log.warn( + "The response from OAuth server cannot be parsed correctly", + e); + throw ServiceExceptionFactory + .process( + "OAuth", + new ServiceException( + "The response from OAuth server cannot be parsed correctly", + e)); + } catch (JsonMappingException e) { + log.warn( + "The response from OAuth server cannot be mapped to OAuthResponse object", + e); + throw ServiceExceptionFactory + .process( + "OAuth", + new ServiceException( + "The response from OAuth server cannot be mapped to OAuthResponse object", + e)); + } catch (IOException e) { + log.warn("Cannot map the response from OAuth server correctly.", e); + throw ServiceExceptionFactory + .process( + "OAuth", + new ServiceException( + "Cannot map the response from OAuth server correctly.", + e)); + } + + return response; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManager.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManager.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManager.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManager.java index 7e80474ed2b37..ba5507ce95ac1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManager.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManager.java @@ -22,8 +22,8 @@ import javax.inject.Named; import javax.management.timer.Timer; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.utils.DateFactory; +import com.microsoft.windowsazure.core.utils.DateFactory; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.MediaConfiguration; /** @@ -40,23 +40,28 @@ public class OAuthTokenManager { private final String scope; /** - * Creates an OAuth token manager instance with specified contract, date factory, ACS base URI, client ID, - * and client secret. + * Creates an OAuth token manager instance with specified contract, date + * factory, ACS base URI, client ID, and client secret. * * @param contract - * A OAuthContract object instance that represents the OAUTH contract. + * A OAuthContract object instance that represents + * the OAUTH contract. * * @param dateFactory - * A DateFactory object instance that represents the date factory. + * A DateFactory object instance that represents the + * date factory. * * @param oAuthUri - * A String object instance that represents the ACS base URI. + * A String object instance that represents the ACS + * base URI. * * @param clientId - * A String object instance that represents the client ID. + * A String object instance that represents the + * client ID. * * @param clientSecret - * A String object instance that represents the client secret. + * A String object instance that represents the + * client secret. * @throws URISyntaxException * */ @@ -64,7 +69,8 @@ public OAuthTokenManager(OAuthContract contract, DateFactory dateFactory, @Named(MediaConfiguration.OAUTH_URI) String oAuthUri, @Named(MediaConfiguration.OAUTH_CLIENT_ID) String clientId, @Named(MediaConfiguration.OAUTH_CLIENT_SECRET) String clientSecret, - @Named(MediaConfiguration.OAUTH_SCOPE) String scope) throws URISyntaxException { + @Named(MediaConfiguration.OAUTH_SCOPE) String scope) + throws URISyntaxException { this.contract = contract; this.dateFactory = dateFactory; this.acsBaseUri = new URI(oAuthUri); @@ -78,7 +84,8 @@ public OAuthTokenManager(OAuthContract contract, DateFactory dateFactory, * Gets an OAuth access token with specified media service scope. * * @param mediaServiceScope - * A String instance that represents the media service scope. + * A String instance that represents the media + * service scope. * * @return String * @@ -87,9 +94,12 @@ public OAuthTokenManager(OAuthContract contract, DateFactory dateFactory, */ public String getAccessToken() throws ServiceException, URISyntaxException { Date now = dateFactory.getDate(); - if (this.activeToken == null || now.after(this.activeToken.getExpiresUtc())) { - OAuthTokenResponse oAuth2TokenResponse = contract.getAccessToken(acsBaseUri, clientId, clientSecret, scope); - Date expiresUtc = new Date(now.getTime() + oAuth2TokenResponse.getExpiresIn() * Timer.ONE_SECOND / 2); + if (this.activeToken == null + || now.after(this.activeToken.getExpiresUtc())) { + OAuthTokenResponse oAuth2TokenResponse = contract.getAccessToken( + acsBaseUri, clientId, clientSecret, scope); + Date expiresUtc = new Date(now.getTime() + + oAuth2TokenResponse.getExpiresIn() * Timer.ONE_SECOND / 2); ActiveToken newToken = new ActiveToken(); newToken.setAccessToken(oAuth2TokenResponse.getAccessToken()); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenResponse.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenResponse.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenResponse.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenResponse.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomMarshaller.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomMarshaller.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomMarshaller.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomMarshaller.java index c64044c0f93dc..9f6059b329323 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomMarshaller.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomMarshaller.java @@ -36,26 +36,31 @@ import com.microsoft.windowsazure.services.media.implementation.content.AccessPolicyType; import com.microsoft.windowsazure.services.media.implementation.content.AssetFileType; import com.microsoft.windowsazure.services.media.implementation.content.AssetType; +import com.microsoft.windowsazure.services.media.implementation.content.ChannelType; import com.microsoft.windowsazure.services.media.implementation.content.Constants; import com.microsoft.windowsazure.services.media.implementation.content.ContentKeyRestType; import com.microsoft.windowsazure.services.media.implementation.content.JobNotificationSubscriptionType; import com.microsoft.windowsazure.services.media.implementation.content.JobType; import com.microsoft.windowsazure.services.media.implementation.content.LocatorRestType; import com.microsoft.windowsazure.services.media.implementation.content.NotificationEndPointType; +import com.microsoft.windowsazure.services.media.implementation.content.OperationType; +import com.microsoft.windowsazure.services.media.implementation.content.OriginType; +import com.microsoft.windowsazure.services.media.implementation.content.ProgramType; import com.microsoft.windowsazure.services.media.implementation.content.TaskType; /** - * A class to manage marshalling of request parameters into - * ATOM entry elements for sending to the Media Services REST - * endpoints. + * A class to manage marshalling of request parameters into ATOM entry elements + * for sending to the Media Services REST endpoints. * */ public class ODataAtomMarshaller { private final Marshaller marshaller; private final DocumentBuilder documentBuilder; - public ODataAtomMarshaller() throws JAXBException, ParserConfigurationException { - JAXBContext context = JAXBContext.newInstance(getMarshalledClasses(), null); + public ODataAtomMarshaller() throws JAXBException, + ParserConfigurationException { + JAXBContext context = JAXBContext.newInstance(getMarshalledClasses(), + null); marshaller = context.createMarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -64,9 +69,8 @@ public ODataAtomMarshaller() throws JAXBException, ParserConfigurationException } /** - * Convert the given content object into an ATOM entry - * (represented as a DOM document) suitable for sending - * up to the Media Services service. + * Convert the given content object into an ATOM entry (represented as a DOM + * document) suitable for sending up to the Media Services service. * * @param content * The content object to send @@ -87,8 +91,8 @@ public Document marshalEntry(Object content) throws JAXBException { } /** - * Convert the given content into an ATOM entry - * and write it to the given stream. + * Convert the given content into an ATOM entry and write it to the given + * stream. * * @param content * Content object to send @@ -97,13 +101,16 @@ public Document marshalEntry(Object content) throws JAXBException { * @throws JAXBException * if content is malformed/not marshallable */ - public void marshalEntry(Object content, OutputStream stream) throws JAXBException { + public void marshalEntry(Object content, OutputStream stream) + throws JAXBException { marshaller.marshal(createEntry(content), stream); } - public void marshalEntryType(EntryType entryType, OutputStream stream) throws JAXBException { - marshaller.marshal( - new JAXBElement(new QName(Constants.ATOM_NS, "entry"), EntryType.class, entryType), stream); + public void marshalEntryType(EntryType entryType, OutputStream stream) + throws JAXBException { + marshaller.marshal(new JAXBElement(new QName( + Constants.ATOM_NS, "entry"), EntryType.class, entryType), + stream); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -113,13 +120,16 @@ private JAXBElement createEntry(Object content) { atomContent.setType("application/xml"); atomContent.getContent().add( - new JAXBElement(new QName(Constants.ODATA_METADATA_NS, "properties"), content.getClass(), content)); + new JAXBElement(new QName(Constants.ODATA_METADATA_NS, + "properties"), content.getClass(), content)); atomEntry.getEntryChildren().add( - new JAXBElement(new QName(Constants.ATOM_NS, "content"), ContentType.class, atomContent)); + new JAXBElement(new QName(Constants.ATOM_NS, "content"), + ContentType.class, atomContent)); - JAXBElement entryElement = new JAXBElement(new QName(Constants.ATOM_NS, "entry"), - EntryType.class, atomEntry); + JAXBElement entryElement = new JAXBElement( + new QName(Constants.ATOM_NS, "entry"), EntryType.class, + atomEntry); return entryElement; } @@ -128,15 +138,19 @@ private static Class[] getMarshalledClasses() { List> classes = new ArrayList>(); classes.add(AccessPolicyType.class); classes.add(AssetType.class); + classes.add(AssetFileType.class); + classes.add(ChannelType.class); + classes.add(ContentKeyRestType.class); classes.add(EntryType.class); classes.add(FeedType.class); + classes.add(JobNotificationSubscriptionType.class); classes.add(JobType.class); classes.add(LocatorRestType.class); - classes.add(TaskType.class); - classes.add(ContentKeyRestType.class); - classes.add(AssetFileType.class); classes.add(NotificationEndPointType.class); - classes.add(JobNotificationSubscriptionType.class); + classes.add(OperationType.class); + classes.add(OriginType.class); + classes.add(ProgramType.class); + classes.add(TaskType.class); return classes.toArray(new Class[0]); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomUnmarshaller.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomUnmarshaller.java similarity index 80% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomUnmarshaller.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomUnmarshaller.java index 2543722eb0a52..7d223b465104f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomUnmarshaller.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataAtomUnmarshaller.java @@ -31,7 +31,7 @@ import org.w3c.dom.Element; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.implementation.atom.ContentType; import com.microsoft.windowsazure.services.media.implementation.atom.EntryType; import com.microsoft.windowsazure.services.media.implementation.atom.FeedType; @@ -41,8 +41,7 @@ import com.microsoft.windowsazure.services.media.models.ListResult; /** - * This class implements unmarshalling from OData over Atom into Java - * classes. + * This class implements unmarshalling from OData over Atom into Java classes. * */ public class ODataAtomUnmarshaller { @@ -55,15 +54,18 @@ public class ODataAtomUnmarshaller { * @throws JAXBException */ public ODataAtomUnmarshaller() throws JAXBException { - atomContext = JAXBContext.newInstance(FeedType.class.getPackage().getName()); + atomContext = JAXBContext.newInstance(FeedType.class.getPackage() + .getName()); atomUnmarshaller = atomContext.createUnmarshaller(); - mediaContentContext = JAXBContext.newInstance(AssetType.class.getPackage().getName()); + mediaContentContext = JAXBContext.newInstance(AssetType.class + .getPackage().getName()); mediaContentUnmarshaller = mediaContentContext.createUnmarshaller(); } /** * Given a stream that contains XML with an atom Feed element at the root, - * unmarshal it into Java objects with the given content type in the entries. + * unmarshal it into Java objects with the given content type in the + * entries. * * @param * @@ -76,8 +78,9 @@ public ODataAtomUnmarshaller() throws JAXBException { * @throws ServiceException */ @SuppressWarnings("rawtypes") - public ListResult unmarshalFeed(InputStream stream, Class contentType) - throws JAXBException, ServiceException { + public ListResult unmarshalFeed( + InputStream stream, Class contentType) throws JAXBException, + ServiceException { validateNotNull(stream, "stream"); validateNotNull(contentType, "contentType"); @@ -88,7 +91,8 @@ public ListResult unmarshalFeed(InputStream stream, C for (Object feedChild : feed.getFeedChildren()) { EntryType entry = asEntry(feedChild); if (entry != null) { - entries.add(contentFromEntry(contentType, marshallingContentType, entry)); + entries.add(contentFromEntry(contentType, + marshallingContentType, entry)); } } return new ListResult(entries); @@ -107,8 +111,8 @@ public ListResult unmarshalFeed(InputStream stream, C * @throws ServiceException */ @SuppressWarnings("rawtypes") - public T unmarshalEntry(InputStream stream, Class contentType) throws JAXBException, - ServiceException { + public T unmarshalEntry(InputStream stream, + Class contentType) throws JAXBException, ServiceException { validateNotNull(stream, "stream"); validateNotNull(contentType, "contentType"); @@ -119,11 +123,14 @@ public T unmarshalEntry(InputStream stream, Class con } @SuppressWarnings("rawtypes") - private T contentFromEntry(Class contentType, Class marshallingContentType, - EntryType entry) throws JAXBException, ServiceException { + private T contentFromEntry(Class contentType, + Class marshallingContentType, EntryType entry) + throws JAXBException, ServiceException { unmarshalODataContent(entry, contentType); - ContentType contentElement = getFirstOfType(ContentType.class, entry.getEntryChildren()); - Object contentObject = getFirstOfType(marshallingContentType, contentElement.getContent()); + ContentType contentElement = getFirstOfType(ContentType.class, + entry.getEntryChildren()); + Object contentObject = getFirstOfType(marshallingContentType, + contentElement.getContent()); return constructResultObject(contentType, entry, contentObject); } @@ -138,7 +145,8 @@ private EntryType asEntry(Object o) { return null; } - private void unmarshalODataContent(EntryType entry, Class contentType) throws JAXBException { + private void unmarshalODataContent(EntryType entry, Class contentType) + throws JAXBException { unmarshalEntryActions(entry); unmarshalEntryContent(entry, contentType); } @@ -149,9 +157,10 @@ private void unmarshalEntryActions(EntryType entry) throws JAXBException { Object child = children.get(i); if (child instanceof Element) { Element e = (Element) child; - if (qnameFromElement(e).equals(Constants.ODATA_ACTION_ELEMENT_NAME)) { - JAXBElement actionElement = mediaContentUnmarshaller.unmarshal(e, - ODataActionType.class); + if (qnameFromElement(e).equals( + Constants.ODATA_ACTION_ELEMENT_NAME)) { + JAXBElement actionElement = mediaContentUnmarshaller + .unmarshal(e, ODataActionType.class); children.set(i, actionElement); } } @@ -159,16 +168,20 @@ private void unmarshalEntryActions(EntryType entry) throws JAXBException { } @SuppressWarnings("rawtypes") - private void unmarshalEntryContent(EntryType entry, Class contentType) throws JAXBException { + private void unmarshalEntryContent(EntryType entry, Class contentType) + throws JAXBException { Class marshallingContentType = getMarshallingContentType(contentType); - ContentType contentElement = getFirstOfType(ContentType.class, entry.getEntryChildren()); + ContentType contentElement = getFirstOfType(ContentType.class, + entry.getEntryChildren()); List contentChildren = contentElement.getContent(); for (int i = 0; i < contentChildren.size(); ++i) { Object child = contentChildren.get(i); if (child instanceof Element) { Element e = (Element) child; - if (qnameFromElement(e).equals(Constants.ODATA_PROPERTIES_ELEMENT_NAME)) { - JAXBElement actualContentElement = mediaContentUnmarshaller.unmarshal(e, marshallingContentType); + if (qnameFromElement(e).equals( + Constants.ODATA_PROPERTIES_ELEMENT_NAME)) { + JAXBElement actualContentElement = mediaContentUnmarshaller + .unmarshal(e, marshallingContentType); contentChildren.set(i, actualContentElement); } } @@ -190,40 +203,38 @@ private T getFirstOfType(Class targetType, List collection) { } @SuppressWarnings("rawtypes") - private T constructResultObject(Class contentType, EntryType entry, Object contentObject) + private T constructResultObject( + Class contentType, EntryType entry, Object contentObject) throws ServiceException { Class marshallingType = getMarshallingContentType(contentType); try { - Constructor resultCtor = contentType.getConstructor(EntryType.class, marshallingType); + Constructor resultCtor = contentType.getConstructor( + EntryType.class, marshallingType); return resultCtor.newInstance(entry, contentObject); - } - catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new ServiceException(e); - } - catch (SecurityException e) { + } catch (SecurityException e) { throw new ServiceException(e); - } - catch (InstantiationException e) { + } catch (InstantiationException e) { throw new ServiceException(e); - } - catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { throw new ServiceException(e); - } - catch (InvocationTargetException e) { + } catch (InvocationTargetException e) { throw new ServiceException(e); - } - catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { throw new ServiceException(e); } } public EntryType unmarshalEntry(InputStream stream) throws JAXBException { - JAXBElement entryElement = atomUnmarshaller.unmarshal(new StreamSource(stream), EntryType.class); + JAXBElement entryElement = atomUnmarshaller.unmarshal( + new StreamSource(stream), EntryType.class); return entryElement.getValue(); } private FeedType unmarshalFeed(InputStream stream) throws JAXBException { - JAXBElement feedElement = atomUnmarshaller.unmarshal(new StreamSource(stream), FeedType.class); + JAXBElement feedElement = atomUnmarshaller.unmarshal( + new StreamSource(stream), FeedType.class); return feedElement.getValue(); } @@ -232,7 +243,8 @@ private static QName qnameFromElement(Element e) { } private static Class getMarshallingContentType(Class contentType) { - ParameterizedType pt = (ParameterizedType) contentType.getGenericSuperclass(); + ParameterizedType pt = (ParameterizedType) contentType + .getGenericSuperclass(); return (Class) pt.getActualTypeArguments()[0]; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataDateAdapter.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataDateAdapter.java similarity index 90% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataDateAdapter.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataDateAdapter.java index a23d7a712ddac..1ed0518fc596c 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataDateAdapter.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataDateAdapter.java @@ -24,8 +24,7 @@ import javax.xml.bind.annotation.adapters.XmlAdapter; /** - * Adapter to convert OData time zone conventions into Java - * Dates and back. + * Adapter to convert OData time zone conventions into Java Dates and back. * */ public class ODataDateAdapter extends XmlAdapter { @@ -58,6 +57,7 @@ public String marshal(Date date) throws Exception { } private boolean hasTimezone(String dateString) { - return dateString.endsWith("Z") || HAS_TIMEZONE_REGEX.matcher(dateString).matches(); + return dateString.endsWith("Z") + || HAS_TIMEZONE_REGEX.matcher(dateString).matches(); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntity.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntity.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntity.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntity.java index 65765129905bb..883282a5359ec 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntity.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntity.java @@ -28,8 +28,8 @@ import com.microsoft.windowsazure.services.media.models.ListResult; /** - * Class wrapping deserialized OData entities. Allows easy - * access to entry and content types. + * Class wrapping deserialized OData entities. Allows easy access to entry and + * content types. * */ public abstract class ODataEntity { @@ -48,10 +48,12 @@ protected ODataEntity(T content) { ContentType contentElement = new ContentType(); contentElement.getContent().add( - new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, content.getClass(), content)); + new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, + content.getClass(), content)); entry = new EntryType(); entry.getEntryChildren().add( - new JAXBElement(Constants.ATOM_CONTENT_ELEMENT_NAME, ContentType.class, contentElement)); + new JAXBElement(Constants.ATOM_CONTENT_ELEMENT_NAME, + ContentType.class, contentElement)); } /** @@ -104,8 +106,10 @@ public > LinkInfo getLink(String rel) { * name of the OData relationship * @return the link if found, null if not. */ - public > LinkInfo getRelationLink(String relationName) { - return this. getLink(Constants.ODATA_DATA_NS + "/related/" + relationName); + public > LinkInfo getRelationLink( + String relationName) { + return this. getLink(Constants.ODATA_DATA_NS + "/related/" + + relationName); } @SuppressWarnings("rawtypes") @@ -116,7 +120,8 @@ private static LinkType linkFromChild(Object child) { return null; } - private static LinkType linkFromElement(@SuppressWarnings("rawtypes") JAXBElement element) { + private static LinkType linkFromElement( + @SuppressWarnings("rawtypes") JAXBElement element) { if (element.getDeclaredType() == LinkType.class) { return (LinkType) element.getValue(); } @@ -143,7 +148,8 @@ public static boolean isODataEntityType(Class type) { * Generic type * @return true if it's List<OEntity> or derive from. */ - public static boolean isODataEntityCollectionType(Class type, Type genericType) { + public static boolean isODataEntityCollectionType(Class type, + Type genericType) { if (ListResult.class != type) { return false; } @@ -160,8 +166,8 @@ public static boolean isODataEntityCollectionType(Class type, Type genericTyp } /** - * Reflection helper to pull out the type parameter for - * a List, where T is a ODataEntity derived type. + * Reflection helper to pull out the type parameter for a List, where T + * is a ODataEntity derived type. * * @param genericType * type object for collection diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityCollectionProvider.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityCollectionProvider.java new file mode 100644 index 0000000000000..1c4e36f509bef --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityCollectionProvider.java @@ -0,0 +1,100 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.xml.bind.JAXBException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; + +/** + * Jersey provider to unmarshal lists of entities from Media Services. + * + */ +public class ODataEntityCollectionProvider extends + AbstractMessageReaderWriterProvider>> { + private final ODataAtomUnmarshaller unmarshaller; + + public ODataEntityCollectionProvider() throws JAXBException { + unmarshaller = new ODataAtomUnmarshaller(); + } + + @Override + public boolean isReadable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return ODataEntity.isODataEntityCollectionType(type, genericType); + } + + @SuppressWarnings("unchecked") + @Override + public ListResult> readFrom( + Class>> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) + throws IOException { + + String responseType = mediaType.getParameters().get("type"); + try { + if (responseType == null || responseType.equals("feed")) { + return unmarshaller.unmarshalFeed(entityStream, + (Class>) ODataEntity + .getCollectedType(genericType)); + } else { + throw new RuntimeException(); + } + } catch (JAXBException e) { + throw new RuntimeException(e); + } catch (ServiceException e) { + throw new RuntimeException(e); + } + } + + /** + * Can this type be written by this provider? + * + * @return false - we don't support writing + */ + @Override + public boolean isWriteable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return false; + } + + /** + * Write the given object to the stream. This method implementation throws, + * we don't support writing. + * + * @throws UnsupportedOperationException + */ + @Override + public void writeTo(ListResult> t, Class type, + Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, + OutputStream entityStream) throws IOException { + + throw new UnsupportedOperationException(); + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityProvider.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityProvider.java new file mode 100644 index 0000000000000..574e192ee312c --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityProvider.java @@ -0,0 +1,128 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.ParserConfigurationException; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; + +/** + * An implementation of {@link AbstractMessageReaderWriterProvider } that is used + * to marshal and unmarshal instances of the ODataEntity type. + * + */ +public class ODataEntityProvider extends + AbstractMessageReaderWriterProvider> { + private final ODataAtomUnmarshaller unmarshaller; + + public ODataEntityProvider() throws JAXBException, + ParserConfigurationException { + unmarshaller = new ODataAtomUnmarshaller(); + } + + /* + * (non-Javadoc) + * + * @see javax.ws.rs.ext.MessageBodyReader#isReadable(java.lang.Class, + * java.lang.reflect.Type, java.lang.annotation.Annotation[], + * javax.ws.rs.core.MediaType) + */ + @Override + public boolean isReadable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return ODataEntity.isODataEntityType(type); + } + + /* + * (non-Javadoc) + * + * @see javax.ws.rs.ext.MessageBodyReader#readFrom(java.lang.Class, + * java.lang.reflect.Type, java.lang.annotation.Annotation[], + * javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, + * java.io.InputStream) + */ + @Override + public ODataEntity readFrom(Class> type, + Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) + throws IOException { + + ODataEntity result = null; + String responseType = mediaType.getParameters().get("type"); + try { + if (responseType == null || responseType.equals("feed")) { + List> feedContents = null; + synchronized (unmarshaller) { + feedContents = unmarshaller.unmarshalFeed(entityStream, + type); + } + return feedContents.get(0); + } else if (responseType.equals("entry")) { + synchronized (unmarshaller) { + result = unmarshaller.unmarshalEntry(entityStream, type); + } + } else { + throw new RuntimeException(); + } + } catch (JAXBException e) { + throw new RuntimeException(e); + } catch (ServiceException e) { + throw new RuntimeException(e); + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(java.lang.Class, + * java.lang.reflect.Type, java.lang.annotation.Annotation[], + * javax.ws.rs.core.MediaType) + */ + @Override + public boolean isWriteable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return false; + } + + /* + * (non-Javadoc) + * + * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(java.lang.Object, + * java.lang.Class, java.lang.reflect.Type, + * java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, + * javax.ws.rs.core.MultivaluedMap, java.io.OutputStream) + */ + @Override + public void writeTo(ODataEntity t, Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, + OutputStream entityStream) throws IOException { + throw new UnsupportedOperationException(); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/RedirectFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/RedirectFilter.java similarity index 75% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/RedirectFilter.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/RedirectFilter.java index 6efebe7453d9c..76ef360a0b91b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/RedirectFilter.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/RedirectFilter.java @@ -18,7 +18,7 @@ import java.net.URI; import java.net.URISyntaxException; -import com.microsoft.windowsazure.services.core.IdempotentClientFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.IdempotentClientFilter; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; @@ -30,8 +30,12 @@ public RedirectFilter(ResourceLocationManager locationManager) { this.locationManager = locationManager; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle(com.sun.jersey.api.client.ClientRequest) + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle + * (com.sun.jersey.api.client.ClientRequest) */ @Override public ClientResponse doHandle(ClientRequest request) { @@ -45,13 +49,14 @@ public ClientResponse doHandle(ClientRequest request) { ClientResponse response = getNext().handle(request); while (response.getClientResponseStatus() == ClientResponse.Status.MOVED_PERMANENTLY) { try { - locationManager.setRedirectedURI(response.getHeaders().getFirst("Location")); - } - catch (NullPointerException e) { - throw new ClientHandlerException("HTTP Redirect did not include Location header"); - } - catch (URISyntaxException e) { - throw new ClientHandlerException("HTTP Redirect location is not a valid URI"); + locationManager.setRedirectedURI(response.getHeaders() + .getFirst("Location")); + } catch (NullPointerException e) { + throw new ClientHandlerException( + "HTTP Redirect did not include Location header"); + } catch (URISyntaxException e) { + throw new ClientHandlerException( + "HTTP Redirect location is not a valid URI"); } request.setURI(locationManager.getRedirectedURI(originalURI)); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManager.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManager.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManager.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManager.java index 50c8b54a8f55a..5923b8bcc0d5b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManager.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManager.java @@ -26,7 +26,8 @@ public class ResourceLocationManager { private URI baseURI; - public ResourceLocationManager(@Named(MediaConfiguration.URI) String baseUri) throws URISyntaxException { + public ResourceLocationManager(@Named(MediaConfiguration.URI) String baseUri) + throws URISyntaxException { this.baseURI = new URI(baseUri); } @@ -35,7 +36,8 @@ public URI getBaseURI() { } public URI getRedirectedURI(URI originalURI) { - UriBuilder uriBuilder = UriBuilder.fromUri(baseURI).path(originalURI.getPath()); + UriBuilder uriBuilder = UriBuilder.fromUri(baseURI).path( + originalURI.getPath()); String queryString = originalURI.getRawQuery(); if (queryString != null && !queryString.isEmpty()) { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilter.java similarity index 83% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilter.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilter.java index 400b304a07d6c..d91f0391a1a56 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilter.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilter.java @@ -17,7 +17,7 @@ import javax.ws.rs.core.UriBuilder; -import com.microsoft.windowsazure.services.core.IdempotentClientFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.IdempotentClientFilter; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; @@ -29,8 +29,8 @@ public class SASTokenFilter extends IdempotentClientFilter { private final String sasToken; /** - * Construct a SASTokenFilter that will insert the tokens given - * in the provided sasUrl. + * Construct a SASTokenFilter that will insert the tokens given in the + * provided sasUrl. * * @param sasUrl * URL containing authentication information @@ -39,8 +39,12 @@ public SASTokenFilter(String sasToken) { this.sasToken = sasToken; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle(com.sun.jersey.api.client.ClientRequest) + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle + * (com.sun.jersey.api.client.ClientRequest) */ @Override public ClientResponse doHandle(ClientRequest cr) { @@ -48,8 +52,7 @@ public ClientResponse doHandle(ClientRequest cr) { String currentQuery = cr.getURI().getRawQuery(); if (currentQuery == null) { currentQuery = ""; - } - else if (currentQuery.length() > 0) { + } else if (currentQuery.length() > 0) { currentQuery += "&"; } currentQuery += sasToken; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/SetBoundaryMultipartDataSource.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/SetBoundaryMultipartDataSource.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/SetBoundaryMultipartDataSource.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/SetBoundaryMultipartDataSource.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/StatusLine.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/StatusLine.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/StatusLine.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/StatusLine.java index 1b330c9e93bca..f4a889706b507 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/StatusLine.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/StatusLine.java @@ -30,7 +30,8 @@ public class StatusLine { public static StatusLine create(DataSource dataSource) { try { - LineInputStream stream = new LineInputStream(dataSource.getInputStream()); + LineInputStream stream = new LineInputStream( + dataSource.getInputStream()); try { String line = stream.readLine(); StringReader lineReader = new StringReader(line); @@ -40,13 +41,12 @@ public static StatusLine create(DataSource dataSource) { String statusString = extractInput(lineReader, ' '); String reason = extractInput(lineReader, DELIMITER); - return new StatusLine().setStatus(Integer.parseInt(statusString)).setReason(reason); - } - finally { + return new StatusLine().setStatus( + Integer.parseInt(statusString)).setReason(reason); + } finally { stream.close(); } - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } @@ -58,12 +58,12 @@ private static void expect(Reader reader, String string) { for (int i = 0; i < string.length(); i++) { ch = reader.read(); if (ch != byteArray[i]) { - throw new RuntimeException(String.format("Expected '%s', found '%s' instead", string, + throw new RuntimeException(String.format( + "Expected '%s', found '%s' instead", string, string.substring(0, i) + (char) ch)); } } - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } @@ -80,8 +80,7 @@ private static String extractInput(Reader reader, int delimiter) { sb.append((char) ch); } return sb.toString(); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/VersionHeadersFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/VersionHeadersFilter.java new file mode 100644 index 0000000000000..4e98863a8af10 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/VersionHeadersFilter.java @@ -0,0 +1,46 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import javax.ws.rs.core.MultivaluedMap; + +import com.microsoft.windowsazure.core.pipeline.jersey.IdempotentClientFilter; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; + +/** + * A small filter that adds the required Media services/OData 3 version headers + * to the request as it goes through. + * + */ +public class VersionHeadersFilter extends IdempotentClientFilter { + + /* + * (non-Javadoc) + * + * @see + * com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle + * (com.sun.jersey.api.client.ClientRequest) + */ + @Override + public ClientResponse doHandle(ClientRequest cr) { + MultivaluedMap headers = cr.getHeaders(); + headers.add("DataServiceVersion", "3.0"); + headers.add("MaxDataServiceVersion", "3.0"); + headers.add("x-ms-version", "2.5"); + return getNext().handle(cr); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/CategoryType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/CategoryType.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/CategoryType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/CategoryType.java index 985521f1baf6c..064df1b35ddd1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/CategoryType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/CategoryType.java @@ -20,11 +20,11 @@ // Generated on: 2012.09.17 at 02:31:28 PM PDT // - package com.microsoft.windowsazure.services.media.implementation.atom; import java.util.HashMap; import java.util.Map; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; @@ -35,15 +35,17 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; - /** * - * The Atom cagegory construct is defined in section 4.2.2 of the format spec. - * + * The Atom cagegory construct is defined in section 4.2.2 of the format spec. + * * - *

Java class for categoryType complex type. + *

+ * Java class for categoryType complex type. * - *

The following schema fragment specifies the expected content contained within this class. + *

+ * The following schema fragment specifies the expected content contained within + * this class. * *

  * <complexType name="categoryType">
@@ -66,29 +68,27 @@
 public class CategoryType {
 
     @XmlAttribute(required = true)
-    protected String term;
+    private String term;
     @XmlAttribute
     @XmlSchemaType(name = "anyURI")
-    protected String scheme;
+    private String scheme;
     @XmlAttribute
-    protected String label;
+    private String label;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlSchemaType(name = "anyURI")
-    protected String base;
+    private String base;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
     @XmlSchemaType(name = "language")
-    protected String lang;
+    private String lang;
     @XmlAnyAttribute
     private Map otherAttributes = new HashMap();
 
     /**
      * Gets the value of the term property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getTerm() {
         return term;
@@ -98,9 +98,8 @@ public String getTerm() {
      * Sets the value of the term property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setTerm(String value) {
         this.term = value;
@@ -109,10 +108,8 @@ public void setTerm(String value) {
     /**
      * Gets the value of the scheme property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getScheme() {
         return scheme;
@@ -122,9 +119,8 @@ public String getScheme() {
      * Sets the value of the scheme property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setScheme(String value) {
         this.scheme = value;
@@ -133,10 +129,8 @@ public void setScheme(String value) {
     /**
      * Gets the value of the label property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getLabel() {
         return label;
@@ -146,9 +140,8 @@ public String getLabel() {
      * Sets the value of the label property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setLabel(String value) {
         this.label = value;
@@ -157,10 +150,8 @@ public void setLabel(String value) {
     /**
      * Gets the value of the base property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getBase() {
         return base;
@@ -170,9 +161,8 @@ public String getBase() {
      * Sets the value of the base property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setBase(String value) {
         this.base = value;
@@ -181,10 +171,8 @@ public void setBase(String value) {
     /**
      * Gets the value of the lang property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getLang() {
         return lang;
@@ -194,27 +182,26 @@ public String getLang() {
      * Sets the value of the lang property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setLang(String value) {
         this.lang = value;
     }
 
     /**
-     * Gets a map that contains attributes that aren't bound to any typed property on this class.
+     * Gets a map that contains attributes that aren't bound to any typed
+     * property on this class.
      * 
      * 

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. + * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. * * - * @return - * always non-null + * @return always non-null */ public Map getOtherAttributes() { return otherAttributes; diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ContentType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ContentType.java new file mode 100644 index 0000000000000..3d57ebeaaee52 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ContentType.java @@ -0,0 +1,228 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlMixed; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom content construct is defined in section 4.1.3 of the format spec. + * + * + *

+ * Java class for contentType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="contentType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <attribute name="src" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
+ *       <anyAttribute namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "contentType", propOrder = { "content" }) +public class ContentType { + + @XmlMixed + @XmlAnyElement(lax = true) + private List content; + @XmlAttribute + private String type; + @XmlAttribute + @XmlSchemaType(name = "anyURI") + private String src; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * + * The Atom content construct is defined in section 4.1.3 of the format + * spec. Gets the value of the content property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the content property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+     * getContent().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list {@link Object } + * {@link String } + * + * + */ + public List getContent() { + if (content == null) { + content = new ArrayList(); + } + return this.content; + } + + /** + * Gets the value of the type property. + * + * @return possible object is {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Gets the value of the src property. + * + * @return possible object is {@link String } + * + */ + public String getSrc() { + return src; + } + + /** + * Sets the value of the src property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setSrc(String value) { + this.src = value; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/DateTimeType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/DateTimeType.java similarity index 77% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/DateTimeType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/DateTimeType.java index 8097815ad1874..9825fc58b66c6 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/DateTimeType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/DateTimeType.java @@ -20,11 +20,11 @@ // Generated on: 2012.09.17 at 02:31:28 PM PDT // - package com.microsoft.windowsazure.services.media.implementation.atom; import java.util.HashMap; import java.util.Map; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; @@ -37,11 +37,13 @@ import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; - /** - *

Java class for dateTimeType complex type. + *

+ * Java class for dateTimeType complex type. * - *

The following schema fragment specifies the expected content contained within this class. + *

+ * The following schema fragment specifies the expected content contained within + * this class. * *

  * <complexType name="dateTimeType">
@@ -57,31 +59,27 @@
  * 
  */
 @XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "dateTimeType", propOrder = {
-    "value"
-})
+@XmlType(name = "dateTimeType", propOrder = { "value" })
 public class DateTimeType {
 
     @XmlValue
     @XmlSchemaType(name = "dateTime")
-    protected XMLGregorianCalendar value;
+    private XMLGregorianCalendar value;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlSchemaType(name = "anyURI")
-    protected String base;
+    private String base;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
     @XmlSchemaType(name = "language")
-    protected String lang;
+    private String lang;
     @XmlAnyAttribute
     private Map otherAttributes = new HashMap();
 
     /**
      * Gets the value of the value property.
      * 
-     * @return
-     *     possible object is
-     *     {@link XMLGregorianCalendar }
-     *     
+     * @return possible object is {@link XMLGregorianCalendar }
+     * 
      */
     public XMLGregorianCalendar getValue() {
         return value;
@@ -91,9 +89,8 @@ public XMLGregorianCalendar getValue() {
      * Sets the value of the value property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link XMLGregorianCalendar }
-     *     
+     *            allowed object is {@link XMLGregorianCalendar }
+     * 
      */
     public void setValue(XMLGregorianCalendar value) {
         this.value = value;
@@ -102,10 +99,8 @@ public void setValue(XMLGregorianCalendar value) {
     /**
      * Gets the value of the base property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getBase() {
         return base;
@@ -115,9 +110,8 @@ public String getBase() {
      * Sets the value of the base property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setBase(String value) {
         this.base = value;
@@ -126,10 +120,8 @@ public void setBase(String value) {
     /**
      * Gets the value of the lang property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getLang() {
         return lang;
@@ -139,27 +131,26 @@ public String getLang() {
      * Sets the value of the lang property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setLang(String value) {
         this.lang = value;
     }
 
     /**
-     * Gets a map that contains attributes that aren't bound to any typed property on this class.
+     * Gets a map that contains attributes that aren't bound to any typed
+     * property on this class.
      * 
      * 

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. + * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. * * - * @return - * always non-null + * @return always non-null */ public Map getOtherAttributes() { return otherAttributes; diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/EntryType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/EntryType.java new file mode 100644 index 0000000000000..76aef53799a53 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/EntryType.java @@ -0,0 +1,213 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlElementRefs; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom entry construct is defined in section 4.1.2 of the format spec. + * + * + *

+ * Java class for entryType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="entryType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <choice maxOccurs="unbounded">
+ *         <element name="author" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="category" type="{http://www.w3.org/2005/Atom}categoryType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="content" type="{http://www.w3.org/2005/Atom}contentType" minOccurs="0"/>
+ *         <element name="contributor" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="id" type="{http://www.w3.org/2005/Atom}idType"/>
+ *         <element name="link" type="{http://www.w3.org/2005/Atom}linkType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="published" type="{http://www.w3.org/2005/Atom}dateTimeType" minOccurs="0"/>
+ *         <element name="rights" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="source" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="summary" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="title" type="{http://www.w3.org/2005/Atom}textType"/>
+ *         <element name="updated" type="{http://www.w3.org/2005/Atom}dateTimeType"/>
+ *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </choice>
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <anyAttribute namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "entryType", propOrder = { "entryChildren" }) +public class EntryType { + + @XmlElementRefs({ + @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "published", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "summary", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "source", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "content", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) + @XmlAnyElement(lax = true) + private List entryChildren; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * Gets the value of the entryChildren property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the entryChildren property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+     * getEntryChildren().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link JAXBElement }{@code <}{@link CategoryType }{@code >} + * {@link JAXBElement }{@code <}{@link TextType }{@code >} {@link JAXBElement } + * {@code <}{@link DateTimeType }{@code >} {@link JAXBElement }{@code <} + * {@link PersonType }{@code >} {@link JAXBElement }{@code <}{@link LinkType } + * {@code >} {@link JAXBElement }{@code <}{@link TextType }{@code >} + * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} + * {@link JAXBElement }{@code <}{@link PersonType }{@code >} + * {@link JAXBElement }{@code <}{@link TextType }{@code >} {@link JAXBElement } + * {@code <}{@link TextType }{@code >} {@link JAXBElement }{@code <} + * {@link IdType }{@code >} {@link JAXBElement }{@code <}{@link ContentType } + * {@code >} {@link Object } + * + * + */ + public List getEntryChildren() { + if (entryChildren == null) { + entryChildren = new ArrayList(); + } + return this.entryChildren; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/FeedType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/FeedType.java new file mode 100644 index 0000000000000..319c1cfd2323e --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/FeedType.java @@ -0,0 +1,216 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.18 at 11:05:53 AM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlElementRefs; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom feed construct is defined in section 4.1.1 of the format spec. + * + * + *

+ * Java class for feedType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="feedType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <choice maxOccurs="unbounded" minOccurs="3">
+ *         <element name="author" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="category" type="{http://www.w3.org/2005/Atom}categoryType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="contributor" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="generator" type="{http://www.w3.org/2005/Atom}generatorType" minOccurs="0"/>
+ *         <element name="icon" type="{http://www.w3.org/2005/Atom}iconType" minOccurs="0"/>
+ *         <element name="id" type="{http://www.w3.org/2005/Atom}idType"/>
+ *         <element name="link" type="{http://www.w3.org/2005/Atom}linkType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="logo" type="{http://www.w3.org/2005/Atom}logoType" minOccurs="0"/>
+ *         <element name="rights" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="subtitle" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="title" type="{http://www.w3.org/2005/Atom}textType"/>
+ *         <element name="updated" type="{http://www.w3.org/2005/Atom}dateTimeType"/>
+ *         <element name="entry" type="{http://www.w3.org/2005/Atom}entryType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </choice>
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <anyAttribute namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "feedType", propOrder = { "feedChildren" }) +public class FeedType { + + @XmlElementRefs({ + @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "entry", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) + @XmlAnyElement(lax = true) + private List feedChildren; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * Gets the value of the feedChildren property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the feedChildren property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+     * getFeedChildren().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} + * {@link JAXBElement }{@code <}{@link GeneratorType }{@code >} + * {@link JAXBElement }{@code <}{@link TextType }{@code >} {@link JAXBElement } + * {@code <}{@link IdType }{@code >} {@link JAXBElement }{@code <} + * {@link LinkType }{@code >} {@link JAXBElement }{@code <}{@link TextType } + * {@code >} {@link JAXBElement }{@code <}{@link PersonType }{@code >} + * {@link Object } {@link JAXBElement }{@code <}{@link EntryType }{@code >} + * {@link JAXBElement }{@code <}{@link LogoType }{@code >} {@link JAXBElement } + * {@code <}{@link IconType }{@code >} {@link JAXBElement }{@code <} + * {@link PersonType }{@code >} {@link JAXBElement }{@code <} + * {@link CategoryType }{@code >} {@link JAXBElement }{@code <} + * {@link TextType }{@code >} + * + * + */ + public List getFeedChildren() { + if (feedChildren == null) { + feedChildren = new ArrayList(); + } + return this.feedChildren; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/GeneratorType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/GeneratorType.java new file mode 100644 index 0000000000000..841656d312853 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/GeneratorType.java @@ -0,0 +1,210 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlValue; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom generator element is defined in section 4.2.4 of the format spec. + * + * + *

+ * Java class for generatorType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="generatorType">
+ *   <simpleContent>
+ *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <attribute name="uri" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
+ *       <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <anyAttribute namespace='##other'/>
+ *     </extension>
+ *   </simpleContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "generatorType", propOrder = { "value" }) +public class GeneratorType { + + @XmlValue + private String value; + @XmlAttribute + @XmlSchemaType(name = "anyURI") + private String uri; + @XmlAttribute + private String version; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * Gets the value of the value property. + * + * @return possible object is {@link String } + * + */ + public String getValue() { + return value; + } + + /** + * Sets the value of the value property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Gets the value of the uri property. + * + * @return possible object is {@link String } + * + */ + public String getUri() { + return uri; + } + + /** + * Sets the value of the uri property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setUri(String value) { + this.uri = value; + } + + /** + * Gets the value of the version property. + * + * @return possible object is {@link String } + * + */ + public String getVersion() { + return version; + } + + /** + * Sets the value of the version property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setVersion(String value) { + this.version = value; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IconType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IconType.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IconType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IconType.java index 5ceea0b56e0c4..e98d74d6ae078 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IconType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IconType.java @@ -20,11 +20,11 @@ // Generated on: 2012.09.17 at 02:31:28 PM PDT // - package com.microsoft.windowsazure.services.media.implementation.atom; import java.util.HashMap; import java.util.Map; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; @@ -36,15 +36,17 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; - /** * - * The Atom icon construct is defined in section 4.2.5 of the format spec. - * + * The Atom icon construct is defined in section 4.2.5 of the format spec. * - *

Java class for iconType complex type. * - *

The following schema fragment specifies the expected content contained within this class. + *

+ * Java class for iconType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. * *

  * <complexType name="iconType">
@@ -60,31 +62,27 @@
  * 
  */
 @XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "iconType", propOrder = {
-    "value"
-})
+@XmlType(name = "iconType", propOrder = { "value" })
 public class IconType {
 
     @XmlValue
     @XmlSchemaType(name = "anyURI")
-    protected String value;
+    private String value;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlSchemaType(name = "anyURI")
-    protected String base;
+    private String base;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
     @XmlSchemaType(name = "language")
-    protected String lang;
+    private String lang;
     @XmlAnyAttribute
     private Map otherAttributes = new HashMap();
 
     /**
      * Gets the value of the value property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getValue() {
         return value;
@@ -94,9 +92,8 @@ public String getValue() {
      * Sets the value of the value property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setValue(String value) {
         this.value = value;
@@ -105,10 +102,8 @@ public void setValue(String value) {
     /**
      * Gets the value of the base property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getBase() {
         return base;
@@ -118,9 +113,8 @@ public String getBase() {
      * Sets the value of the base property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setBase(String value) {
         this.base = value;
@@ -129,10 +123,8 @@ public void setBase(String value) {
     /**
      * Gets the value of the lang property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getLang() {
         return lang;
@@ -142,27 +134,26 @@ public String getLang() {
      * Sets the value of the lang property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setLang(String value) {
         this.lang = value;
     }
 
     /**
-     * Gets a map that contains attributes that aren't bound to any typed property on this class.
+     * Gets a map that contains attributes that aren't bound to any typed
+     * property on this class.
      * 
      * 

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. + * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. * * - * @return - * always non-null + * @return always non-null */ public Map getOtherAttributes() { return otherAttributes; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IdType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IdType.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IdType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IdType.java index a32ff13c35437..b3b4a215d51d4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IdType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/IdType.java @@ -20,11 +20,11 @@ // Generated on: 2012.09.17 at 02:31:28 PM PDT // - package com.microsoft.windowsazure.services.media.implementation.atom; import java.util.HashMap; import java.util.Map; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; @@ -36,15 +36,17 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; - /** * - * The Atom id construct is defined in section 4.2.6 of the format spec. - * + * The Atom id construct is defined in section 4.2.6 of the format spec. * - *

Java class for idType complex type. * - *

The following schema fragment specifies the expected content contained within this class. + *

+ * Java class for idType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. * *

  * <complexType name="idType">
@@ -60,31 +62,27 @@
  * 
  */
 @XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "idType", propOrder = {
-    "value"
-})
+@XmlType(name = "idType", propOrder = { "value" })
 public class IdType {
 
     @XmlValue
     @XmlSchemaType(name = "anyURI")
-    protected String value;
+    private String value;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlSchemaType(name = "anyURI")
-    protected String base;
+    private String base;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
     @XmlSchemaType(name = "language")
-    protected String lang;
+    private String lang;
     @XmlAnyAttribute
     private Map otherAttributes = new HashMap();
 
     /**
      * Gets the value of the value property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getValue() {
         return value;
@@ -94,9 +92,8 @@ public String getValue() {
      * Sets the value of the value property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setValue(String value) {
         this.value = value;
@@ -105,10 +102,8 @@ public void setValue(String value) {
     /**
      * Gets the value of the base property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getBase() {
         return base;
@@ -118,9 +113,8 @@ public String getBase() {
      * Sets the value of the base property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setBase(String value) {
         this.base = value;
@@ -129,10 +123,8 @@ public void setBase(String value) {
     /**
      * Gets the value of the lang property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getLang() {
         return lang;
@@ -142,27 +134,26 @@ public String getLang() {
      * Sets the value of the lang property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setLang(String value) {
         this.lang = value;
     }
 
     /**
-     * Gets a map that contains attributes that aren't bound to any typed property on this class.
+     * Gets a map that contains attributes that aren't bound to any typed
+     * property on this class.
      * 
      * 

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. + * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. * * - * @return - * always non-null + * @return always non-null */ public Map getOtherAttributes() { return otherAttributes; diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LinkType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LinkType.java new file mode 100644 index 0000000000000..109c22639ac37 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LinkType.java @@ -0,0 +1,312 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlValue; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom link construct is defined in section 3.4 of the format spec. + * + * + *

+ * Java class for linkType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="linkType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <attribute name="href" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
+ *       <attribute name="rel" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <attribute name="hreflang" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
+ *       <attribute name="title" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *       <attribute name="length" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" />
+ *       <anyAttribute namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "linkType", propOrder = { "content" }) +public class LinkType { + + @XmlValue + private String content; + @XmlAttribute(required = true) + @XmlSchemaType(name = "anyURI") + private String href; + @XmlAttribute + private String rel; + @XmlAttribute + private String type; + @XmlAttribute + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "NMTOKEN") + private String hreflang; + @XmlAttribute + private String title; + @XmlAttribute + @XmlSchemaType(name = "positiveInteger") + private BigInteger length; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * + * The Atom link construct is defined in section 3.4 of the format spec. + * + * + * @return possible object is {@link String } + * + */ + public String getContent() { + return content; + } + + /** + * Sets the value of the content property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setContent(String value) { + this.content = value; + } + + /** + * Gets the value of the href property. + * + * @return possible object is {@link String } + * + */ + public String getHref() { + return href; + } + + /** + * Sets the value of the href property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setHref(String value) { + this.href = value; + } + + /** + * Gets the value of the rel property. + * + * @return possible object is {@link String } + * + */ + public String getRel() { + return rel; + } + + /** + * Sets the value of the rel property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setRel(String value) { + this.rel = value; + } + + /** + * Gets the value of the type property. + * + * @return possible object is {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Gets the value of the hreflang property. + * + * @return possible object is {@link String } + * + */ + public String getHreflang() { + return hreflang; + } + + /** + * Sets the value of the hreflang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setHreflang(String value) { + this.hreflang = value; + } + + /** + * Gets the value of the title property. + * + * @return possible object is {@link String } + * + */ + public String getTitle() { + return title; + } + + /** + * Sets the value of the title property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } + + /** + * Gets the value of the length property. + * + * @return possible object is {@link BigInteger } + * + */ + public BigInteger getLength() { + return length; + } + + /** + * Sets the value of the length property. + * + * @param value + * allowed object is {@link BigInteger } + * + */ + public void setLength(BigInteger value) { + this.length = value; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LogoType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LogoType.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LogoType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LogoType.java index 8cdff364873f0..fa0c6be3491fb 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LogoType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LogoType.java @@ -20,11 +20,11 @@ // Generated on: 2012.09.17 at 02:31:28 PM PDT // - package com.microsoft.windowsazure.services.media.implementation.atom; import java.util.HashMap; import java.util.Map; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; @@ -36,15 +36,17 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; - /** * - * The Atom logo construct is defined in section 4.2.8 of the format spec. - * + * The Atom logo construct is defined in section 4.2.8 of the format spec. * - *

Java class for logoType complex type. * - *

The following schema fragment specifies the expected content contained within this class. + *

+ * Java class for logoType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. * *

  * <complexType name="logoType">
@@ -60,31 +62,27 @@
  * 
  */
 @XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "logoType", propOrder = {
-    "value"
-})
+@XmlType(name = "logoType", propOrder = { "value" })
 public class LogoType {
 
     @XmlValue
     @XmlSchemaType(name = "anyURI")
-    protected String value;
+    private String value;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlSchemaType(name = "anyURI")
-    protected String base;
+    private String base;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
     @XmlSchemaType(name = "language")
-    protected String lang;
+    private String lang;
     @XmlAnyAttribute
     private Map otherAttributes = new HashMap();
 
     /**
      * Gets the value of the value property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getValue() {
         return value;
@@ -94,9 +92,8 @@ public String getValue() {
      * Sets the value of the value property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setValue(String value) {
         this.value = value;
@@ -105,10 +102,8 @@ public void setValue(String value) {
     /**
      * Gets the value of the base property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getBase() {
         return base;
@@ -118,9 +113,8 @@ public String getBase() {
      * Sets the value of the base property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setBase(String value) {
         this.base = value;
@@ -129,10 +123,8 @@ public void setBase(String value) {
     /**
      * Gets the value of the lang property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getLang() {
         return lang;
@@ -142,27 +134,26 @@ public String getLang() {
      * Sets the value of the lang property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setLang(String value) {
         this.lang = value;
     }
 
     /**
-     * Gets a map that contains attributes that aren't bound to any typed property on this class.
+     * Gets a map that contains attributes that aren't bound to any typed
+     * property on this class.
      * 
      * 

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. + * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. * * - * @return - * always non-null + * @return always non-null */ public Map getOtherAttributes() { return otherAttributes; diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ObjectFactory.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ObjectFactory.java new file mode 100644 index 0000000000000..c664661da68b8 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ObjectFactory.java @@ -0,0 +1,670 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlRegistry; +import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * This object contains factory methods for each Java content interface and Java + * element interface generated in the + * com.microsoft.windowsazure.services.media.implementation.atom package. + *

+ * An ObjectFactory allows you to programatically construct new instances of the + * Java representation for XML content. The Java representation of XML content + * can consist of schema derived interfaces and classes representing the binding + * of schema type definitions, element declarations and model groups. Factory + * methods for each of these are provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + private static final QName ENTRY_QNAME = new QName( + "http://www.w3.org/2005/Atom", "entry"); + private static final QName FEED_QNAME = new QName( + "http://www.w3.org/2005/Atom", "feed"); + private static final QName PERSON_TYPE_NAME_QNAME = new QName( + "http://www.w3.org/2005/Atom", "name"); + private static final QName PERSON_TYPE_EMAIL_QNAME = new QName( + "http://www.w3.org/2005/Atom", "email"); + private static final QName PERSON_TYPE_URI_QNAME = new QName( + "http://www.w3.org/2005/Atom", "uri"); + private static final QName ENTRY_TYPE_TITLE_QNAME = new QName( + "http://www.w3.org/2005/Atom", "title"); + private static final QName ENTRY_TYPE_CATEGORY_QNAME = new QName( + "http://www.w3.org/2005/Atom", "category"); + private static final QName ENTRY_TYPE_AUTHOR_QNAME = new QName( + "http://www.w3.org/2005/Atom", "author"); + private static final QName ENTRY_TYPE_SUMMARY_QNAME = new QName( + "http://www.w3.org/2005/Atom", "summary"); + private static final QName ENTRY_TYPE_ID_QNAME = new QName( + "http://www.w3.org/2005/Atom", "id"); + private static final QName ENTRY_TYPE_CONTENT_QNAME = new QName( + "http://www.w3.org/2005/Atom", "content"); + private static final QName ENTRY_TYPE_LINK_QNAME = new QName( + "http://www.w3.org/2005/Atom", "link"); + private static final QName ENTRY_TYPE_CONTRIBUTOR_QNAME = new QName( + "http://www.w3.org/2005/Atom", "contributor"); + private static final QName ENTRY_TYPE_UPDATED_QNAME = new QName( + "http://www.w3.org/2005/Atom", "updated"); + private static final QName ENTRY_TYPE_SOURCE_QNAME = new QName( + "http://www.w3.org/2005/Atom", "source"); + private static final QName ENTRY_TYPE_RIGHTS_QNAME = new QName( + "http://www.w3.org/2005/Atom", "rights"); + private static final QName ENTRY_TYPE_PUBLISHED_QNAME = new QName( + "http://www.w3.org/2005/Atom", "published"); + private static final QName FEED_TYPE_GENERATOR_QNAME = new QName( + "http://www.w3.org/2005/Atom", "generator"); + private static final QName FEED_TYPE_SUBTITLE_QNAME = new QName( + "http://www.w3.org/2005/Atom", "subtitle"); + private static final QName FEED_TYPE_LOGO_QNAME = new QName( + "http://www.w3.org/2005/Atom", "logo"); + private static final QName FEED_TYPE_ICON_QNAME = new QName( + "http://www.w3.org/2005/Atom", "icon"); + + /** + * Create a new ObjectFactory that can be used to create new instances of + * schema derived classes for package: + * com.microsoft.windowsazure.services.media.implementation.atom + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link PersonType } + * + */ + public PersonType createPersonType() { + return new PersonType(); + } + + /** + * Create an instance of {@link EntryType } + * + */ + public EntryType createEntryType() { + return new EntryType(); + } + + /** + * Create an instance of {@link IconType } + * + */ + public IconType createIconType() { + return new IconType(); + } + + /** + * Create an instance of {@link UriType } + * + */ + public UriType createUriType() { + return new UriType(); + } + + /** + * Create an instance of {@link TextType } + * + */ + public TextType createTextType() { + return new TextType(); + } + + /** + * Create an instance of {@link FeedType } + * + */ + public FeedType createFeedType() { + return new FeedType(); + } + + /** + * Create an instance of {@link DateTimeType } + * + */ + public DateTimeType createDateTimeType() { + return new DateTimeType(); + } + + /** + * Create an instance of {@link IdType } + * + */ + public IdType createIdType() { + return new IdType(); + } + + /** + * Create an instance of {@link SourceType } + * + */ + public SourceType createSourceType() { + return new SourceType(); + } + + /** + * Create an instance of {@link LinkType } + * + */ + public LinkType createLinkType() { + return new LinkType(); + } + + /** + * Create an instance of {@link LogoType } + * + */ + public LogoType createLogoType() { + return new LogoType(); + } + + /** + * Create an instance of {@link GeneratorType } + * + */ + public GeneratorType createGeneratorType() { + return new GeneratorType(); + } + + /** + * Create an instance of {@link ContentType } + * + */ + public ContentType createContentType() { + return new ContentType(); + } + + /** + * Create an instance of {@link CategoryType } + * + */ + public CategoryType createCategoryType() { + return new CategoryType(); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link EntryType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "entry") + public JAXBElement createEntry(EntryType value) { + return new JAXBElement(ENTRY_QNAME, EntryType.class, null, + value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link FeedType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "feed") + public JAXBElement createFeed(FeedType value) { + return new JAXBElement(FEED_QNAME, FeedType.class, null, + value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "name", scope = PersonType.class) + public JAXBElement createPersonTypeName(String value) { + return new JAXBElement(PERSON_TYPE_NAME_QNAME, String.class, + PersonType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "email", scope = PersonType.class) + @XmlJavaTypeAdapter(NormalizedStringAdapter.class) + public JAXBElement createPersonTypeEmail(String value) { + return new JAXBElement(PERSON_TYPE_EMAIL_QNAME, String.class, + PersonType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link UriType }{@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "uri", scope = PersonType.class) + public JAXBElement createPersonTypeUri(UriType value) { + return new JAXBElement(PERSON_TYPE_URI_QNAME, UriType.class, + PersonType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "title", scope = EntryType.class) + public JAXBElement createEntryTypeTitle(TextType value) { + return new JAXBElement(ENTRY_TYPE_TITLE_QNAME, TextType.class, + EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link CategoryType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "category", scope = EntryType.class) + public JAXBElement createEntryTypeCategory(CategoryType value) { + return new JAXBElement(ENTRY_TYPE_CATEGORY_QNAME, + CategoryType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link PersonType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "author", scope = EntryType.class) + public JAXBElement createEntryTypeAuthor(PersonType value) { + return new JAXBElement(ENTRY_TYPE_AUTHOR_QNAME, + PersonType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "summary", scope = EntryType.class) + public JAXBElement createEntryTypeSummary(TextType value) { + return new JAXBElement(ENTRY_TYPE_SUMMARY_QNAME, + TextType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link IdType }{@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "id", scope = EntryType.class) + public JAXBElement createEntryTypeId(IdType value) { + return new JAXBElement(ENTRY_TYPE_ID_QNAME, IdType.class, + EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link ContentType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "content", scope = EntryType.class) + public JAXBElement createEntryTypeContent(ContentType value) { + return new JAXBElement(ENTRY_TYPE_CONTENT_QNAME, + ContentType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link LinkType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "link", scope = EntryType.class) + public JAXBElement createEntryTypeLink(LinkType value) { + return new JAXBElement(ENTRY_TYPE_LINK_QNAME, LinkType.class, + EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link PersonType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "contributor", scope = EntryType.class) + public JAXBElement createEntryTypeContributor(PersonType value) { + return new JAXBElement(ENTRY_TYPE_CONTRIBUTOR_QNAME, + PersonType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "updated", scope = EntryType.class) + public JAXBElement createEntryTypeUpdated(DateTimeType value) { + return new JAXBElement(ENTRY_TYPE_UPDATED_QNAME, + DateTimeType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "source", scope = EntryType.class) + public JAXBElement createEntryTypeSource(TextType value) { + return new JAXBElement(ENTRY_TYPE_SOURCE_QNAME, + TextType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "rights", scope = EntryType.class) + public JAXBElement createEntryTypeRights(TextType value) { + return new JAXBElement(ENTRY_TYPE_RIGHTS_QNAME, + TextType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "published", scope = EntryType.class) + public JAXBElement createEntryTypePublished(DateTimeType value) { + return new JAXBElement(ENTRY_TYPE_PUBLISHED_QNAME, + DateTimeType.class, EntryType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link CategoryType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "category", scope = FeedType.class) + public JAXBElement createFeedTypeCategory(CategoryType value) { + return new JAXBElement(ENTRY_TYPE_CATEGORY_QNAME, + CategoryType.class, FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "title", scope = FeedType.class) + public JAXBElement createFeedTypeTitle(TextType value) { + return new JAXBElement(ENTRY_TYPE_TITLE_QNAME, TextType.class, + FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link PersonType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "author", scope = FeedType.class) + public JAXBElement createFeedTypeAuthor(PersonType value) { + return new JAXBElement(ENTRY_TYPE_AUTHOR_QNAME, + PersonType.class, FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link IdType }{@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "id", scope = FeedType.class) + public JAXBElement createFeedTypeId(IdType value) { + return new JAXBElement(ENTRY_TYPE_ID_QNAME, IdType.class, + FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link EntryType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "entry", scope = FeedType.class) + public JAXBElement createFeedTypeEntry(EntryType value) { + return new JAXBElement(ENTRY_QNAME, EntryType.class, + FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link PersonType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "contributor", scope = FeedType.class) + public JAXBElement createFeedTypeContributor(PersonType value) { + return new JAXBElement(ENTRY_TYPE_CONTRIBUTOR_QNAME, + PersonType.class, FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "updated", scope = FeedType.class) + public JAXBElement createFeedTypeUpdated(DateTimeType value) { + return new JAXBElement(ENTRY_TYPE_UPDATED_QNAME, + DateTimeType.class, FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link GeneratorType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "generator", scope = FeedType.class) + public JAXBElement createFeedTypeGenerator( + GeneratorType value) { + return new JAXBElement(FEED_TYPE_GENERATOR_QNAME, + GeneratorType.class, FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "subtitle", scope = FeedType.class) + public JAXBElement createFeedTypeSubtitle(TextType value) { + return new JAXBElement(FEED_TYPE_SUBTITLE_QNAME, + TextType.class, FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link LogoType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "logo", scope = FeedType.class) + public JAXBElement createFeedTypeLogo(LogoType value) { + return new JAXBElement(FEED_TYPE_LOGO_QNAME, LogoType.class, + FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link IconType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "icon", scope = FeedType.class) + public JAXBElement createFeedTypeIcon(IconType value) { + return new JAXBElement(FEED_TYPE_ICON_QNAME, IconType.class, + FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link LinkType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "link", scope = FeedType.class) + public JAXBElement createFeedTypeLink(LinkType value) { + return new JAXBElement(ENTRY_TYPE_LINK_QNAME, LinkType.class, + FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "rights", scope = FeedType.class) + public JAXBElement createFeedTypeRights(TextType value) { + return new JAXBElement(ENTRY_TYPE_RIGHTS_QNAME, + TextType.class, FeedType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "title", scope = SourceType.class) + public JAXBElement createSourceTypeTitle(TextType value) { + return new JAXBElement(ENTRY_TYPE_TITLE_QNAME, TextType.class, + SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link CategoryType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "category", scope = SourceType.class) + public JAXBElement createSourceTypeCategory(CategoryType value) { + return new JAXBElement(ENTRY_TYPE_CATEGORY_QNAME, + CategoryType.class, SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link IconType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "icon", scope = SourceType.class) + public JAXBElement createSourceTypeIcon(IconType value) { + return new JAXBElement(FEED_TYPE_ICON_QNAME, IconType.class, + SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link PersonType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "author", scope = SourceType.class) + public JAXBElement createSourceTypeAuthor(PersonType value) { + return new JAXBElement(ENTRY_TYPE_AUTHOR_QNAME, + PersonType.class, SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link LogoType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "logo", scope = SourceType.class) + public JAXBElement createSourceTypeLogo(LogoType value) { + return new JAXBElement(FEED_TYPE_LOGO_QNAME, LogoType.class, + SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link IdType }{@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "id", scope = SourceType.class) + public JAXBElement createSourceTypeId(IdType value) { + return new JAXBElement(ENTRY_TYPE_ID_QNAME, IdType.class, + SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link LinkType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "link", scope = SourceType.class) + public JAXBElement createSourceTypeLink(LinkType value) { + return new JAXBElement(ENTRY_TYPE_LINK_QNAME, LinkType.class, + SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link PersonType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "contributor", scope = SourceType.class) + public JAXBElement createSourceTypeContributor(PersonType value) { + return new JAXBElement(ENTRY_TYPE_CONTRIBUTOR_QNAME, + PersonType.class, SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "updated", scope = SourceType.class) + public JAXBElement createSourceTypeUpdated(DateTimeType value) { + return new JAXBElement(ENTRY_TYPE_UPDATED_QNAME, + DateTimeType.class, SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link GeneratorType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "generator", scope = SourceType.class) + public JAXBElement createSourceTypeGenerator( + GeneratorType value) { + return new JAXBElement(FEED_TYPE_GENERATOR_QNAME, + GeneratorType.class, SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "rights", scope = SourceType.class) + public JAXBElement createSourceTypeRights(TextType value) { + return new JAXBElement(ENTRY_TYPE_RIGHTS_QNAME, + TextType.class, SourceType.class, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link TextType } + * {@code >} + * + */ + @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "subtitle", scope = SourceType.class) + public JAXBElement createSourceTypeSubtitle(TextType value) { + return new JAXBElement(FEED_TYPE_SUBTITLE_QNAME, + TextType.class, SourceType.class, value); + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/PersonType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/PersonType.java new file mode 100644 index 0000000000000..11f46bcdc0d03 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/PersonType.java @@ -0,0 +1,187 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlElementRefs; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom person construct is defined in section 3.2 of the format spec. + * + * + *

+ * Java class for personType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="personType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <choice maxOccurs="unbounded">
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="uri" type="{http://www.w3.org/2005/Atom}uriType" minOccurs="0"/>
+ *         <element name="email" type="{http://www.w3.org/2005/Atom}emailType" minOccurs="0"/>
+ *         <any namespace='##other'/>
+ *       </choice>
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <anyAttribute namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "personType", propOrder = { "nameOrUriOrEmail" }) +public class PersonType { + + @XmlElementRefs({ + @XmlElementRef(name = "email", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "uri", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "name", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) + @XmlAnyElement(lax = true) + private List nameOrUriOrEmail; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * Gets the value of the nameOrUriOrEmail property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the nameOrUriOrEmail property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+     * getNameOrUriOrEmail().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link JAXBElement }{@code <}{@link String }{@code >} {@link Object } + * {@link JAXBElement }{@code <}{@link String }{@code >} {@link JAXBElement } + * {@code <}{@link UriType }{@code >} + * + * + */ + public List getNameOrUriOrEmail() { + if (nameOrUriOrEmail == null) { + nameOrUriOrEmail = new ArrayList(); + } + return this.nameOrUriOrEmail; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/SourceType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/SourceType.java new file mode 100644 index 0000000000000..a11d845fec13c --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/SourceType.java @@ -0,0 +1,213 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlElementRefs; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom source construct is defined in section 4.2.11 of the format spec. + * + * + *

+ * Java class for sourceType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="sourceType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <choice maxOccurs="unbounded">
+ *         <element name="author" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="category" type="{http://www.w3.org/2005/Atom}categoryType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="contributor" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="generator" type="{http://www.w3.org/2005/Atom}generatorType" minOccurs="0"/>
+ *         <element name="icon" type="{http://www.w3.org/2005/Atom}iconType" minOccurs="0"/>
+ *         <element name="id" type="{http://www.w3.org/2005/Atom}idType" minOccurs="0"/>
+ *         <element name="link" type="{http://www.w3.org/2005/Atom}linkType" maxOccurs="unbounded" minOccurs="0"/>
+ *         <element name="logo" type="{http://www.w3.org/2005/Atom}logoType" minOccurs="0"/>
+ *         <element name="rights" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="subtitle" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="title" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
+ *         <element name="updated" type="{http://www.w3.org/2005/Atom}dateTimeType" minOccurs="0"/>
+ *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </choice>
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <anyAttribute namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "sourceType", propOrder = { "authorOrCategoryOrContributor" }) +public class SourceType { + + @XmlElementRefs({ + @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), + @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) + @XmlAnyElement(lax = true) + private List authorOrCategoryOrContributor; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * Gets the value of the authorOrCategoryOrContributor property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the authorOrCategoryOrContributor property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+     * getAuthorOrCategoryOrContributor().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link JAXBElement }{@code <}{@link PersonType }{@code >} + * {@link JAXBElement }{@code <}{@link TextType }{@code >} {@link JAXBElement } + * {@code <}{@link PersonType }{@code >} {@link JAXBElement }{@code <} + * {@link GeneratorType }{@code >} {@link JAXBElement }{@code <} + * {@link LogoType }{@code >} {@link JAXBElement }{@code <}{@link IdType } + * {@code >} {@link JAXBElement }{@code <}{@link TextType }{@code >} + * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} + * {@link JAXBElement }{@code <}{@link CategoryType }{@code >} {@link Object } + * {@link JAXBElement }{@code <}{@link IconType }{@code >} {@link JAXBElement } + * {@code <}{@link LinkType }{@code >} {@link JAXBElement }{@code <} + * {@link TextType }{@code >} + * + * + */ + public List getAuthorOrCategoryOrContributor() { + if (authorOrCategoryOrContributor == null) { + authorOrCategoryOrContributor = new ArrayList(); + } + return this.authorOrCategoryOrContributor; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/TextType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/TextType.java new file mode 100644 index 0000000000000..c18bd847bd817 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/TextType.java @@ -0,0 +1,212 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.09.17 at 02:31:28 PM PDT +// + +package com.microsoft.windowsazure.services.media.implementation.atom; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlMixed; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.namespace.QName; + +/** + * + * The Atom text construct is defined in section 3.1 of the format spec. + * + * + *

+ * Java class for textType complex type. + * + *

+ * The following schema fragment specifies the expected content contained within + * this class. + * + *

+ * <complexType name="textType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <any namespace='http://www.w3.org/1999/xhtml' minOccurs="0"/>
+ *       </sequence>
+ *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
+ *       <attribute name="type">
+ *         <simpleType>
+ *           <restriction base="{http://www.w3.org/2001/XMLSchema}token">
+ *             <enumeration value="text"/>
+ *             <enumeration value="html"/>
+ *             <enumeration value="xhtml"/>
+ *           </restriction>
+ *         </simpleType>
+ *       </attribute>
+ *       <anyAttribute namespace='##other'/>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "textType", propOrder = { "content" }) +public class TextType { + + @XmlMixed + @XmlAnyElement(lax = true) + private List content; + @XmlAttribute + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + private String type; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anyURI") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "language") + private String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * + * The Atom text construct is defined in section 3.1 of the format spec. + * Gets the value of the content property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the content property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+     * getContent().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list {@link Object } + * {@link String } + * + * + */ + public List getContent() { + if (content == null) { + content = new ArrayList(); + } + return this.content; + } + + /** + * Gets the value of the type property. + * + * @return possible object is {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Gets the value of the base property. + * + * @return possible object is {@link String } + * + */ + public String getBase() { + return base; + } + + /** + * Sets the value of the base property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } + + /** + * Gets the value of the lang property. + * + * @return possible object is {@link String } + * + */ + public String getLang() { + return lang; + } + + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed + * property on this class. + * + *

+ * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. + * + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. + * + * + * @return always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/UriType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/UriType.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/UriType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/UriType.java index a6a8041129892..057e580264bc4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/UriType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/UriType.java @@ -20,11 +20,11 @@ // Generated on: 2012.09.17 at 02:31:28 PM PDT // - package com.microsoft.windowsazure.services.media.implementation.atom; import java.util.HashMap; import java.util.Map; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; @@ -36,11 +36,13 @@ import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; - /** - *

Java class for uriType complex type. + *

+ * Java class for uriType complex type. * - *

The following schema fragment specifies the expected content contained within this class. + *

+ * The following schema fragment specifies the expected content contained within + * this class. * *

  * <complexType name="uriType">
@@ -56,31 +58,27 @@
  * 
  */
 @XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "uriType", propOrder = {
-    "value"
-})
+@XmlType(name = "uriType", propOrder = { "value" })
 public class UriType {
 
     @XmlValue
     @XmlSchemaType(name = "anyURI")
-    protected String value;
+    private String value;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlSchemaType(name = "anyURI")
-    protected String base;
+    private String base;
     @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
     @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
     @XmlSchemaType(name = "language")
-    protected String lang;
+    private String lang;
     @XmlAnyAttribute
     private Map otherAttributes = new HashMap();
 
     /**
      * Gets the value of the value property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getValue() {
         return value;
@@ -90,9 +88,8 @@ public String getValue() {
      * Sets the value of the value property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setValue(String value) {
         this.value = value;
@@ -101,10 +98,8 @@ public void setValue(String value) {
     /**
      * Gets the value of the base property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getBase() {
         return base;
@@ -114,9 +109,8 @@ public String getBase() {
      * Sets the value of the base property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setBase(String value) {
         this.base = value;
@@ -125,10 +119,8 @@ public void setBase(String value) {
     /**
      * Gets the value of the lang property.
      * 
-     * @return
-     *     possible object is
-     *     {@link String }
-     *     
+     * @return possible object is {@link String }
+     * 
      */
     public String getLang() {
         return lang;
@@ -138,27 +130,26 @@ public String getLang() {
      * Sets the value of the lang property.
      * 
      * @param value
-     *     allowed object is
-     *     {@link String }
-     *     
+     *            allowed object is {@link String }
+     * 
      */
     public void setLang(String value) {
         this.lang = value;
     }
 
     /**
-     * Gets a map that contains attributes that aren't bound to any typed property on this class.
+     * Gets a map that contains attributes that aren't bound to any typed
+     * property on this class.
      * 
      * 

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. + * the map is keyed by the name of the attribute and the value is the string + * value of the attribute. * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. + * the map returned by this method is live, and you can add new attribute by + * updating the map directly. Because of this design, there's no setter. * * - * @return - * always non-null + * @return always non-null */ public Map getOtherAttributes() { return otherAttributes; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/package-info.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/package-info.java similarity index 99% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/package-info.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/package-info.java index 735e1ae1d6241..23a179781afea 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/package-info.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/package-info.java @@ -22,3 +22,4 @@ @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.w3.org/2005/Atom", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package com.microsoft.windowsazure.services.media.implementation.atom; + diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AccessPolicyType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AccessPolicyType.java similarity index 94% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AccessPolicyType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AccessPolicyType.java index b362d17696943..4bb71e8b9b3c3 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AccessPolicyType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AccessPolicyType.java @@ -29,22 +29,22 @@ public class AccessPolicyType implements MediaServiceDTO { @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) - protected Date created; + private Date created; @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) - protected Date lastModified; + private Date lastModified; @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) - protected String name; + private String name; @XmlElement(name = "DurationInMinutes", namespace = Constants.ODATA_DATA_NS) - protected Double durationInMinutes; + private Double durationInMinutes; @XmlElement(name = "Permissions", namespace = Constants.ODATA_DATA_NS) - protected Integer permissions; + private Integer permissions; /** * @return the id diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetFileType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetFileType.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetFileType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetFileType.java index fcf17089d2986..259659d5755df 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetFileType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetFileType.java @@ -30,46 +30,46 @@ public class AssetFileType implements MediaServiceDTO { @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) - protected String name; + private String name; @XmlElement(name = "ContentFileSize", namespace = Constants.ODATA_DATA_NS) - protected Long contentFileSize; + private Long contentFileSize; @XmlElement(name = "ParentAssetId", namespace = Constants.ODATA_DATA_NS) - protected String parentAssetId; + private String parentAssetId; @XmlElement(name = "EncryptionVersion", namespace = Constants.ODATA_DATA_NS) - protected String encryptionVersion; + private String encryptionVersion; @XmlElement(name = "EncryptionScheme", namespace = Constants.ODATA_DATA_NS) - protected String encryptionScheme; + private String encryptionScheme; @XmlElement(name = "IsEncrypted", namespace = Constants.ODATA_DATA_NS) - protected Boolean isEncrypted; + private Boolean isEncrypted; @XmlElement(name = "EncryptionKeyId", namespace = Constants.ODATA_DATA_NS) - protected String encryptionKeyId; + private String encryptionKeyId; @XmlElement(name = "InitializationVector", namespace = Constants.ODATA_DATA_NS) - protected String initializationVector; + private String initializationVector; @XmlElement(name = "IsPrimary", namespace = Constants.ODATA_DATA_NS) - protected Boolean isPrimary; + private Boolean isPrimary; @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) - protected Date lastModified; + private Date lastModified; @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) - protected Date created; + private Date created; @XmlElement(name = "MimeType", namespace = Constants.ODATA_DATA_NS) - protected String mimeType; + private String mimeType; @XmlElement(name = "ContentChecksum", namespace = Constants.ODATA_DATA_NS) - protected String contentChecksum; + private String contentChecksum; /** * @return the id diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetType.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetType.java index 8cbc101c74bd8..1b050d19d0352 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/AssetType.java @@ -22,33 +22,33 @@ import javax.xml.bind.annotation.XmlElement; /** - * This type maps the XML returned in the odata ATOM serialization - * for Asset entities. + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. * */ @XmlAccessorType(XmlAccessType.FIELD) public class AssetType implements MediaServiceDTO { @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; @XmlElement(name = "State", namespace = Constants.ODATA_DATA_NS) - protected Integer state; + private Integer state; @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) - protected Date created; + private Date created; @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) - protected Date lastModified; + private Date lastModified; @XmlElement(name = "AlternateId", namespace = Constants.ODATA_DATA_NS) - protected String alternateId; + private String alternateId; @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) - protected String name; + private String name; @XmlElement(name = "Options", namespace = Constants.ODATA_DATA_NS) - protected Integer options; + private Integer options; /** * @return the id diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ChannelType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ChannelType.java new file mode 100644 index 0000000000000..705bd40bd6375 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ChannelType.java @@ -0,0 +1,282 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation.content; + +import java.net.URI; +import java.util.Date; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +/** + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +public class ChannelType implements MediaServiceDTO { + + /** The id. */ + @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) + private String id; + + /** The name. */ + @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) + private String name; + + /** The description. */ + @XmlElement(name = "Description", namespace = Constants.ODATA_DATA_NS) + private String description; + + /** The created. */ + @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) + private Date created; + + /** The last modified. */ + @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) + private Date lastModified; + + /** The preview uri. */ + @XmlElement(name = "PreviewUri", namespace = Constants.ODATA_DATA_NS) + private URI previewUri; + + /** The ingest uri. */ + @XmlElement(name = "IngestUri", namespace = Constants.ODATA_DATA_NS) + private URI ingestUri; + + /** The state. */ + @XmlElement(name = "State", namespace = Constants.ODATA_DATA_NS) + private String state; + + /** The size. */ + @XmlElement(name = "Size", namespace = Constants.ODATA_DATA_NS) + private String size; + + /** The settings. */ + @XmlElement(name = "Settings", namespace = Constants.ODATA_DATA_NS) + private String settings; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * Sets the id. + * + * @param id + * the id + * @return the channel type + */ + public ChannelType setId(String id) { + this.id = id; + return this; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name + * the name to set + * @return the channel type + */ + public ChannelType setName(String name) { + this.name = name; + return this; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets the description. + * + * @param description + * the description + * @return the channel type + */ + public ChannelType setDescription(String description) { + this.description = description; + return this; + } + + /** + * Gets the created. + * + * @return the created + */ + public Date getCreated() { + return created; + } + + /** + * Sets the created. + * + * @param created + * the created + * @return the channel type + */ + public ChannelType setCreated(Date created) { + this.created = created; + return this; + } + + /** + * Gets the last modified. + * + * @return the lastModified + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Sets the last modified. + * + * @param lastModified + * the last modified + * @return the channel type + */ + public ChannelType setLastModified(Date lastModified) { + this.lastModified = lastModified; + return this; + } + + /** + * Sets the preview uri. + * + * @param previewUri + * the preview uri + * @return the channel type + */ + public ChannelType setPreviewUri(URI previewUri) { + this.previewUri = previewUri; + return this; + } + + /** + * Gets the preview uri. + * + * @return the preview + */ + public URI getPreviewUri() { + return previewUri; + } + + /** + * Sets the ingest uri. + * + * @param ingestUri + * the ingest uri + * @return the channel type + */ + public ChannelType setIngestUri(URI ingestUri) { + this.ingestUri = ingestUri; + return this; + } + + /** + * Gets the ingest uri. + * + * @return the ingest uri + */ + public URI getIngestUri() { + return ingestUri; + } + + /** + * Sets the state. + * + * @param state + * the state + * @return the channel type + */ + public ChannelType setState(String state) { + this.state = state; + return this; + } + + /** + * Gets the state. + * + * @return the state + */ + public String getState() { + return this.state; + } + + /** + * Gets the size. + * + * @return the name + */ + public String getSize() { + return this.size; + } + + /** + * Sets the size. + * + * @param size + * the size + * @return the channel type + */ + public ChannelType setSize(String size) { + this.size = size; + return this; + } + + /** + * Gets the settings. + * + * @return the settings + */ + public String getSettings() { + return this.settings; + } + + /** + * Sets the settings. + * + * @param settings + * the settings + * @return the channel type + */ + public ChannelType setSettings(String settings) { + this.settings = settings; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/Constants.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/Constants.java new file mode 100644 index 0000000000000..747a8e0e4813d --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/Constants.java @@ -0,0 +1,70 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation.content; + +import javax.xml.namespace.QName; + +/** + * This class provides a set of constants for element names and namespaces used + * throughout the serialization of media services entities. + */ + +public final class Constants { + + private Constants() { + } + + /** + * XML Namespace for Atom syndication format, as defined by IETF RFC 4287 + */ + public static final String ATOM_NS = "http://www.w3.org/2005/Atom"; + + /** + * XML Namespace for OData data as serialized inside Atom syndication + * format. + */ + public static final String ODATA_DATA_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices"; + + /** + * XML Namespace for OData metadata as serialized inside Atom syndication + * format. + */ + public static final String ODATA_METADATA_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; + + /** + * EDM namespace for Azure Media Services entities, as defined in Media + * Services EDMX file. + */ + public static final String MEDIA_SERVICES_EDM_NAMESPACE = "Microsoft.Cloud.Media.Vod.Rest.Data.Models"; + + /** + * Element name for Atom content element, including namespace + */ + public static final QName ATOM_CONTENT_ELEMENT_NAME = new QName("content", + ATOM_NS); + + /** + * Element name for OData action elements, including namespace + */ + public static final QName ODATA_ACTION_ELEMENT_NAME = new QName("action", + ODATA_METADATA_NS); + + /** + * Element name for the metadata properties element, including namespace. + */ + public static final QName ODATA_PROPERTIES_ELEMENT_NAME = new QName( + "properties", ODATA_METADATA_NS); +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ContentKeyRestType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ContentKeyRestType.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ContentKeyRestType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ContentKeyRestType.java index 72e0e7261481c..1bced674e7482 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ContentKeyRestType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ContentKeyRestType.java @@ -22,8 +22,8 @@ import javax.xml.bind.annotation.XmlElement; /** - * This type maps the XML returned in the odata ATOM serialization - * for Asset entities. + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. * */ @XmlAccessorType(XmlAccessType.FIELD) @@ -31,31 +31,31 @@ public class ContentKeyRestType implements MediaServiceDTO { /** The id. */ @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; /** The created. */ @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) - protected Date created; + private Date created; /** The last modified. */ @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) - protected Date lastModified; + private Date lastModified; /** The content key type. */ @XmlElement(name = "ContentKeyType", namespace = Constants.ODATA_DATA_NS) - protected Integer contentKeyType; + private Integer contentKeyType; /** The encrypted content key. */ @XmlElement(name = "EncryptedContentKey", namespace = Constants.ODATA_DATA_NS) - protected String encryptedContentKey; + private String encryptedContentKey; /** The name. */ @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) - protected String name; + private String name; /** The protection key id. */ @XmlElement(name = "ProtectionKeyId", namespace = Constants.ODATA_DATA_NS) - protected String protectionKeyId; + private String protectionKeyId; /** The protection key type. */ @XmlElement(name = "ProtectionKeyType", namespace = Constants.ODATA_DATA_NS) @@ -63,7 +63,7 @@ public class ContentKeyRestType implements MediaServiceDTO { /** The checksum. */ @XmlElement(name = "Checksum", namespace = Constants.ODATA_DATA_NS) - protected String checksum; + private String checksum; /** * Gets the id. diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorDetailType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorDetailType.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorDetailType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorDetailType.java index 3a5ffdef35f33..cbb6a32bb6cb4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorDetailType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorDetailType.java @@ -20,8 +20,8 @@ import javax.xml.bind.annotation.XmlElement; /** - * This type maps the XML returned in the odata ATOM serialization - * for ErrorDetail entities. + * This type maps the XML returned in the odata ATOM serialization for + * ErrorDetail entities. * */ @XmlAccessorType(XmlAccessType.FIELD) @@ -29,11 +29,11 @@ public class ErrorDetailType implements MediaServiceDTO { /** The code. */ @XmlElement(name = "Code", namespace = Constants.ODATA_DATA_NS) - protected String code; + private String code; /** The message. */ @XmlElement(name = "Message", namespace = Constants.ODATA_DATA_NS) - protected String message; + private String message; /** * Gets the code. diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorType.java new file mode 100644 index 0000000000000..f736fabe36054 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ErrorType.java @@ -0,0 +1,83 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation.content; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * This type maps the XML returned in the odata ATOM serialization for + * ErrorDetail entities. + * + */ + +@XmlRootElement(name = "error", namespace = Constants.ODATA_METADATA_NS) +@XmlAccessorType(XmlAccessType.FIELD) +public class ErrorType { + + /** The code. */ + @XmlElement(name = "code", namespace = Constants.ODATA_METADATA_NS) + private String code; + + /** The message. */ + @XmlElement(name = "message", namespace = Constants.ODATA_METADATA_NS) + private String message; + + /** + * Gets the code. + * + * @return the code + */ + public String getCode() { + return code; + } + + /** + * Sets the code. + * + * @param code + * the id to set + * @return the error type + */ + public ErrorType setCode(String code) { + this.code = code; + return this; + } + + /** + * Gets the message. + * + * @return the message + */ + public String getMessage() { + return message; + } + + /** + * Sets the message. + * + * @param message + * the message to set + * @return the error type + */ + public ErrorType setMessage(String message) { + this.message = message; + return this; + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobNotificationSubscriptionType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobNotificationSubscriptionType.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobNotificationSubscriptionType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobNotificationSubscriptionType.java index d6f42ecae21e7..f2df8847e70e4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobNotificationSubscriptionType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobNotificationSubscriptionType.java @@ -20,8 +20,8 @@ import javax.xml.bind.annotation.XmlElement; /** - * This type maps the XML returned in the odata ATOM serialization - * for job notification subscription. + * This type maps the XML returned in the odata ATOM serialization for job + * notification subscription. * */ @XmlAccessorType(XmlAccessType.FIELD) @@ -29,11 +29,11 @@ public class JobNotificationSubscriptionType implements MediaServiceDTO { /** The ID of the notification end point. */ @XmlElement(name = "NotificationEndPointId", namespace = Constants.ODATA_DATA_NS) - protected String notificationEndPointId; + private String notificationEndPointId; /** The target state of the job. */ @XmlElement(name = "TargetJobState", namespace = Constants.ODATA_DATA_NS) - protected int targetJobState; + private int targetJobState; /** * Gets the ID of the notification end point. @@ -51,7 +51,8 @@ public String getNotificationEndPointId() { * the ID of the notification end point to set * @return the job notification subscription type */ - public JobNotificationSubscriptionType setNotificationEndPointId(String notificationEndPointId) { + public JobNotificationSubscriptionType setNotificationEndPointId( + String notificationEndPointId) { this.notificationEndPointId = notificationEndPointId; return this; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobType.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobType.java index 9c3dede3da4e2..c3661b7b9ae65 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/JobType.java @@ -25,8 +25,8 @@ import javax.xml.bind.annotation.XmlElementWrapper; /** - * This type maps the XML returned in the odata ATOM serialization - * for Job entities. + * This type maps the XML returned in the odata ATOM serialization for Job + * entities. * */ @XmlAccessorType(XmlAccessType.FIELD) @@ -34,48 +34,48 @@ public class JobType implements MediaServiceDTO { /** The id. */ @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; /** The job notification subscriptions. */ @XmlElementWrapper(name = "JobNotificationSubscriptions", namespace = Constants.ODATA_DATA_NS) @XmlElement(name = "element", namespace = Constants.ODATA_DATA_NS) - protected List jobNotificationSubscriptionTypes; + private List jobNotificationSubscriptionTypes; /** The name. */ @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) - protected String name; + private String name; /** The created. */ @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) - protected Date created; + private Date created; /** The last modified. */ @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) - protected Date lastModified; + private Date lastModified; /** The end time. */ @XmlElement(name = "EndTime", namespace = Constants.ODATA_DATA_NS) - protected Date endTime; + private Date endTime; /** The priority. */ @XmlElement(name = "Priority", namespace = Constants.ODATA_DATA_NS) - protected Integer priority; + private Integer priority; /** The running duration. */ @XmlElement(name = "RunningDuration", namespace = Constants.ODATA_DATA_NS) - protected Double runningDuration; + private Double runningDuration; /** The start time. */ @XmlElement(name = "StartTime", namespace = Constants.ODATA_DATA_NS) - protected Date startTime; + private Date startTime; /** The state. */ @XmlElement(name = "State", namespace = Constants.ODATA_DATA_NS) - protected Integer state; + private Integer state; /** The template id. */ @XmlElement(name = "TemplateId", namespace = Constants.ODATA_DATA_NS) - protected String templateId; + private String templateId; /** * Gets the id. @@ -303,7 +303,8 @@ public List getJobNotificationSubscriptionTypes * the job notification subscription * @return the job type */ - public JobType addJobNotificationSubscriptionType(JobNotificationSubscriptionType jobNotificationSubscription) { + public JobType addJobNotificationSubscriptionType( + JobNotificationSubscriptionType jobNotificationSubscription) { if (this.jobNotificationSubscriptionTypes == null) { this.jobNotificationSubscriptionTypes = new ArrayList(); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/LocatorRestType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/LocatorRestType.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/LocatorRestType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/LocatorRestType.java index 1f30a8a6afcdd..f010311c73bb7 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/LocatorRestType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/LocatorRestType.java @@ -30,31 +30,31 @@ public class LocatorRestType implements MediaServiceDTO { /** The id. */ @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; /** The expiration date time. */ @XmlElement(name = "ExpirationDateTime", namespace = Constants.ODATA_DATA_NS) - protected Date expirationDateTime; + private Date expirationDateTime; /** The type. */ @XmlElement(name = "Type", namespace = Constants.ODATA_DATA_NS) - protected Integer type; + private Integer type; /** The path. */ @XmlElement(name = "Path", namespace = Constants.ODATA_DATA_NS) - protected String path; + private String path; /** The access policy id. */ @XmlElement(name = "AccessPolicyId", namespace = Constants.ODATA_DATA_NS) - protected String accessPolicyId; + private String accessPolicyId; /** The asset id. */ @XmlElement(name = "AssetId", namespace = Constants.ODATA_DATA_NS) - protected String assetId; + private String assetId; /** The start time. */ @XmlElement(name = "StartTime", namespace = Constants.ODATA_DATA_NS) - protected Date startTime; + private Date startTime; /** The base uri. */ @XmlElement(name = "BaseUri", namespace = Constants.ODATA_DATA_NS) @@ -248,7 +248,8 @@ public String getContentAccessComponent() { * the content access component * @return the locator rest type */ - public LocatorRestType setContentAccessComponent(String contentAccessComponent) { + public LocatorRestType setContentAccessComponent( + String contentAccessComponent) { this.contentAccessComponent = contentAccessComponent; return this; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaProcessorType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaProcessorType.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaProcessorType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaProcessorType.java index c79778a5b3417..809707af4117c 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaProcessorType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaProcessorType.java @@ -20,30 +20,30 @@ import javax.xml.bind.annotation.XmlElement; /** - * This type maps the XML returned in the odata ATOM serialization - * for Asset entities. + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. * */ @XmlAccessorType(XmlAccessType.FIELD) public class MediaProcessorType implements MediaServiceDTO { @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) - protected String name; + private String name; @XmlElement(name = "Description", namespace = Constants.ODATA_DATA_NS) - protected String description; + private String description; @XmlElement(name = "Sku", namespace = Constants.ODATA_DATA_NS) - protected String sku; + private String sku; @XmlElement(name = "Vendor", namespace = Constants.ODATA_DATA_NS) - protected String vendor; + private String vendor; @XmlElement(name = "Version", namespace = Constants.ODATA_DATA_NS) - protected String version; + private String version; /** * @return the id diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaServiceDTO.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaServiceDTO.java similarity index 77% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaServiceDTO.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaServiceDTO.java index f99f73b111065..588e613ec0960 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaServiceDTO.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaServiceDTO.java @@ -16,11 +16,11 @@ package com.microsoft.windowsazure.services.media.implementation.content; /** - * Marker interface to mark types as a data transfer object - * to or from Media Services. + * Marker interface to mark types as a data transfer object to or from Media + * Services. * - * This is a marker interface rather than an annotation so - * that it can be used as a generic type parameter or restriction. + * This is a marker interface rather than an annotation so that it can be used + * as a generic type parameter or restriction. * */ public interface MediaServiceDTO { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaUriType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaUriType.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaUriType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaUriType.java index 7c612ed67a1a3..682cbddbec10f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaUriType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/MediaUriType.java @@ -21,14 +21,14 @@ import javax.xml.bind.annotation.XmlValue; /** - * This type maps the URI. + * This type maps the URI. * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "uri", namespace = Constants.ODATA_DATA_NS) public class MediaUriType implements MediaServiceDTO { @XmlValue - String uri; + private String uri; /** * @return the uri. @@ -39,8 +39,7 @@ public String getUri() { /** * @param uri - * uri - * the uri to set + * uri the uri to set */ public void setUri(String uri) { this.uri = uri; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/NotificationEndPointType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/NotificationEndPointType.java similarity index 97% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/NotificationEndPointType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/NotificationEndPointType.java index 836e31d053628..99a129354dbda 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/NotificationEndPointType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/NotificationEndPointType.java @@ -63,8 +63,7 @@ public String getId() { * Sets the id. * * @param id - * id - * the id to set + * id the id to set * @return the notification end point type */ public NotificationEndPointType setId(String id) { @@ -85,8 +84,7 @@ public String getName() { * Sets the name. * * @param name - * name - * the name to set + * name the name to set * @return the notification end point type */ public NotificationEndPointType setName(String name) { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ODataActionType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ODataActionType.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ODataActionType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ODataActionType.java index bc358a3540b83..f8f81e75da8e0 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ODataActionType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ODataActionType.java @@ -27,13 +27,13 @@ public class ODataActionType { @XmlAttribute(required = true) - protected String metadata; + private String metadata; @XmlAttribute(required = true) - protected String target; + private String target; @XmlAttribute(required = true) - protected String title; + private String title; /** * Get metadata diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ObjectFactory.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ObjectFactory.java new file mode 100644 index 0000000000000..1fda19a7eae8c --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ObjectFactory.java @@ -0,0 +1,179 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation.content; + +import javax.xml.bind.annotation.XmlRegistry; + +/** + * Class used by JAXB to instantiate the types in this package. + * + */ +@XmlRegistry +public class ObjectFactory { + + /** + * Create a new ObjectFactory that can be used to create new instances of + * schema derived classes for package: + * com.microsoft.windowsazure.services.media.implementation.atom + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link AssetType }. + * + * @return a new AssetType instance. + */ + public AssetType createAssetType() { + return new AssetType(); + } + + /** + * Create an instance of {@link ODataActionType }. + * + * @return a new ODataActionType instance. + */ + public ODataActionType createODataActionType() { + return new ODataActionType(); + } + + /** + * Create an instance of {@link AccessPolicyType }. + * + * @return a new AccessPolicyType instance. + */ + public AccessPolicyType createAccessPolicyType() { + return new AccessPolicyType(); + } + + /** + * Create an instance of {@link LocatorRestType }. + * + * @return a new LocatorRestType instance. + */ + public LocatorRestType createLocatorRestType() { + return new LocatorRestType(); + } + + /** + * Create an instance of {@link MediaProcessorType }. + * + * @return a new MediaProcessorType instance. + */ + public MediaProcessorType createMediaProcessorType() { + return new MediaProcessorType(); + } + + /** + * Create an instance of {@link JobType}. + * + * @return a new JobType instance. + */ + public JobType createJobType() { + return new JobType(); + } + + /** + * Create an instance of {@link TaskType}. + * + * @return a new TaskType instance. + */ + public TaskType createTaskType() { + return new TaskType(); + } + + /** + * Creates a new Object object. + * + * @return the content key rest type + */ + public ContentKeyRestType createContentKeyRestType() { + return new ContentKeyRestType(); + } + + /** + * Create an instance of {@link AssetFileType}. + * + * @return a new AssetFileType instance. + */ + public AssetFileType createAssetFileType() { + return new AssetFileType(); + } + + /** + * Creates an instance of (@link RebindContentKeyType). + * + * @return the rebind content key type instance. + */ + public RebindContentKeyType createRebindContentKeyType() { + return new RebindContentKeyType(); + } + + /** + * Creates an instance of (@link ChannelType). + * + * @return the channel type. + */ + public ChannelType createChannelType() { + return new ChannelType(); + } + + /** + * Creates an instance of (@link JobNotificationSubscriptionType). + * + * @return the job notification subscription type. + */ + public JobNotificationSubscriptionType createJobNotificationSubscriptionType() { + return new JobNotificationSubscriptionType(); + } + + /** + * Creates an instance of (@link NotificationEndPointType). + * + * @return the notification end point type. + */ + public NotificationEndPointType createNotificationEndPointType() { + return new NotificationEndPointType(); + } + + /** + * Creates an instance of (@link OperationType). + * + * @return the operation type + */ + public OperationType createOperationType() { + return new OperationType(); + } + + /** + * Creates an instance of (@link OriginType). + * + * @return the origin type + */ + public OriginType createOriginType() { + return new OriginType(); + } + + /** + * Creates a instance of (@link @ProgramType). + * + * @return the program type + */ + public ProgramType createProgramType() { + return new ProgramType(); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/OperationType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/OperationType.java new file mode 100644 index 0000000000000..59638a21bce93 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/OperationType.java @@ -0,0 +1,155 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation.content; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +/** + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +public class OperationType implements MediaServiceDTO { + + /** The id. */ + @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) + private String id; + + /** The target entity id. */ + @XmlElement(name = "TargetEntityId", namespace = Constants.ODATA_DATA_NS) + private String targetEntityId; + + /** The state. */ + @XmlElement(name = "State", namespace = Constants.ODATA_DATA_NS) + private String state; + + /** The error code. */ + @XmlElement(name = "ErrorCode", namespace = Constants.ODATA_DATA_NS) + private String errorCode; + + /** The error message. */ + @XmlElement(name = "ErrorMessage", namespace = Constants.ODATA_DATA_NS) + private String errorMessage; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Sets the id. + * + * @param id + * the id to set + * @return the operation type + */ + public OperationType setId(String id) { + this.id = id; + return this; + } + + /** + * Gets the target entity id. + * + * @return the target entity id + */ + public String getTargetEntityId() { + return targetEntityId; + } + + /** + * Sets the target entity id. + * + * @param targetEntityId + * the target entity id + * @return the operation type + */ + public OperationType setTargetEntityId(String targetEntityId) { + this.targetEntityId = targetEntityId; + return this; + } + + /** + * Gets the state. + * + * @return the state + */ + public String getState() { + return state; + } + + /** + * Sets the state. + * + * @param state + * the state to set + * @return the operation type + */ + public OperationType setState(String state) { + this.state = state; + return this; + } + + /** + * Gets the error code. + * + * @return the error code + */ + public String getErrorCode() { + return this.errorCode; + } + + /** + * Sets the error code. + * + * @param errorCode + * the error code + * @return the operation type + */ + public OperationType setErrorCode(String errorCode) { + this.errorCode = errorCode; + return this; + } + + /** + * Gets the error message. + * + * @return the error message + */ + public String getErrorMessage() { + return this.errorMessage; + } + + /** + * Sets the error message. + * + * @param errorMessage + * the error message + * @return the operation type + */ + public OperationType setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/OriginType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/OriginType.java new file mode 100644 index 0000000000000..d089c8c5571de --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/OriginType.java @@ -0,0 +1,256 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation.content; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +/** + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +public class OriginType implements MediaServiceDTO { + + /** The id. */ + @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) + private String id; + + /** The name. */ + @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) + private String name; + + /** The description. */ + @XmlElement(name = "Description", namespace = Constants.ODATA_DATA_NS) + private String description; + + /** The hostName. */ + @XmlElement(name = "HostName", namespace = Constants.ODATA_DATA_NS) + private String hostName; + + /** The created. */ + @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) + private Date created; + + /** The last modified. */ + @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) + private Date lastModified; + + /** The state. */ + @XmlElement(name = "State", namespace = Constants.ODATA_DATA_NS) + private String state; + + /** The reserved units. */ + @XmlElement(name = "ReservedUnits", namespace = Constants.ODATA_DATA_NS) + private int reservedUnits; + + /** The settings. */ + @XmlElement(name = "Settings", namespace = Constants.ODATA_DATA_NS) + private String settings; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * Sets the id. + * + * @param id + * the id + * @return the origin type + */ + public OriginType setId(String id) { + this.id = id; + return this; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name + * the name to set + * @return the origin type + */ + public OriginType setName(String name) { + this.name = name; + return this; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets the description. + * + * @param description + * the description + * @return the origin type + */ + public OriginType setDescription(String description) { + this.description = description; + return this; + } + + /** + * Gets the host name. + * + * @return the host name + */ + public String getHostName() { + return hostName; + } + + /** + * Sets the host name. + * + * @param host + * name the host name to set + * @return the origin type + */ + public OriginType setHostName(String hostName) { + this.hostName = hostName; + return this; + } + + /** + * Gets the created. + * + * @return the created + */ + public Date getCreated() { + return created; + } + + /** + * Sets the created. + * + * @param created + * the created + * @return the origin type + */ + public OriginType setCreated(Date created) { + this.created = created; + return this; + } + + /** + * Gets the last modified. + * + * @return the lastModified + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Sets the last modified. + * + * @param lastModified + * the last modified + * @return the origin type + */ + public OriginType setLastModified(Date lastModified) { + this.lastModified = lastModified; + return this; + } + + /** + * Sets the state. + * + * @param state + * the state + * @return the origin type + */ + public OriginType setState(String state) { + this.state = state; + return this; + } + + /** + * Gets the state. + * + * @return the state + */ + public String getState() { + return this.state; + } + + /** + * Sets the reserved units. + * + * @param reservedUnits + * the reserved units + * @return the origin type + */ + public OriginType setReservedUnits(int reservedUnits) { + this.reservedUnits = reservedUnits; + return this; + } + + /** + * Gets the reserved units. + * + * @return the reserved units + */ + public int getReservedUnits() { + return this.reservedUnits; + } + + /** + * Gets the settings. + * + * @return the settings + */ + public String getSettings() { + return this.settings; + } + + /** + * Sets the settings. + * + * @param settings + * the settings + * @return the origin type + */ + public OriginType setSettings(String settings) { + this.settings = settings; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProgramType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProgramType.java new file mode 100644 index 0000000000000..12bb3aa37b915 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProgramType.java @@ -0,0 +1,296 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation.content; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +/** + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +public class ProgramType implements MediaServiceDTO { + + /** The id. */ + @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) + private String id; + + /** The name. */ + @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) + private String name; + + /** The description. */ + @XmlElement(name = "Description", namespace = Constants.ODATA_DATA_NS) + private String description; + + /** The created. */ + @XmlElement(name = "Created", namespace = Constants.ODATA_DATA_NS) + private Date created; + + /** The last modified. */ + @XmlElement(name = "LastModified", namespace = Constants.ODATA_DATA_NS) + private Date lastModified; + + /** The channel id. */ + @XmlElement(name = "ChannelId", namespace = Constants.ODATA_DATA_NS) + private String channelId; + + /** The asset id. */ + @XmlElement(name = "AssetId", namespace = Constants.ODATA_DATA_NS) + private String assetId; + + /** The dvr window length seconds. */ + @XmlElement(name = "DvrWindowLengthSeconds", namespace = Constants.ODATA_DATA_NS) + private int dvrWindowLengthSeconds; + + /** The estimated duration seconds. */ + @XmlElement(name = "EstimatedDurationSeconds", namespace = Constants.ODATA_DATA_NS) + private int estimatedDurationSeconds; + + /** The enable archive. */ + @XmlElement(name = "EnableArchive", namespace = Constants.ODATA_DATA_NS) + private boolean enableArchive; + + /** The state. */ + @XmlElement(name = "State", namespace = Constants.ODATA_DATA_NS) + private String state; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * Sets the id. + * + * @param id + * the id + * @return the channel type + */ + public ProgramType setId(String id) { + this.id = id; + return this; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name + * the name to set + * @return the channel type + */ + public ProgramType setName(String name) { + this.name = name; + return this; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets the description. + * + * @param description + * the description + * @return the channel type + */ + public ProgramType setDescription(String description) { + this.description = description; + return this; + } + + /** + * Gets the created. + * + * @return the created + */ + public Date getCreated() { + return created; + } + + /** + * Sets the created. + * + * @param created + * the created + * @return the channel type + */ + public ProgramType setCreated(Date created) { + this.created = created; + return this; + } + + /** + * Gets the last modified. + * + * @return the lastModified + */ + public Date getLastModified() { + return lastModified; + } + + /** + * Sets the last modified. + * + * @param lastModified + * the last modified + * @return the channel type + */ + public ProgramType setLastModified(Date lastModified) { + this.lastModified = lastModified; + return this; + } + + /** + * Sets the state. + * + * @param state + * the state + * @return the channel type + */ + public ProgramType setState(String state) { + this.state = state; + return this; + } + + /** + * Gets the state. + * + * @return the state + */ + public String getState() { + return this.state; + } + + /** + * Gets the channel id. + * + * @return the channel id + */ + public String getChannelId() { + return this.channelId; + } + + /** + * Gets the asset id. + * + * @return the asset id + */ + public String getAssetId() { + return this.assetId; + } + + /** + * Gets the dvr window length seconds. + * + * @return the dvr window length seconds + */ + public int getDvrWindowLengthSeconds() { + return this.dvrWindowLengthSeconds; + } + + /** + * Gets the estimated duration seconds. + * + * @return the estimated duration seconds + */ + public int getEstimatedDurationSeconds() { + return this.estimatedDurationSeconds; + } + + /** + * Checks if is enable archive. + * + * @return true, if is enable archive + */ + public boolean isEnableArchive() { + return this.enableArchive; + } + + /** + * Sets the enable archive. + * + * @param enableArchive + * the new enable archive + */ + public void setEnableArchive(boolean enableArchive) { + this.enableArchive = enableArchive; + } + + /** + * Sets the asset id. + * + * @param assetId + * the new asset id + */ + public void setAssetId(String assetId) { + this.assetId = assetId; + } + + /** + * Sets the channel id. + * + * @param channelId + * the new channel id + */ + public void setChannelId(String channelId) { + this.channelId = channelId; + } + + /** + * Sets the estimated duration seconds. + * + * @param estimatedDurationSeconds + * the new estimated duration seconds + */ + public void setEstimatedDurationSeconds(int estimatedDurationSeconds) { + this.estimatedDurationSeconds = estimatedDurationSeconds; + } + + /** + * Sets the dvr window length seconds. + * + * @param dvrWindowLengthSeconds + * the new dvr window length seconds + */ + public void setDvrWindowLengthSeconds(int dvrWindowLengthSeconds) { + this.dvrWindowLengthSeconds = dvrWindowLengthSeconds; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyIdType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyIdType.java similarity index 91% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyIdType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyIdType.java index 3190c34c29077..c2cd0e429c9c4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyIdType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyIdType.java @@ -21,15 +21,15 @@ import javax.xml.bind.annotation.XmlValue; /** - * This type maps the XML returned in the odata ATOM serialization - * for Asset entities. + * This type maps the XML returned in the odata ATOM serialization for Asset + * entities. * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "GetProtectionKeyId", namespace = Constants.ODATA_DATA_NS) public class ProtectionKeyIdType implements MediaServiceDTO { @XmlValue - String protectionKeyId; + private String protectionKeyId; /** * @return the protection key id @@ -40,8 +40,7 @@ public String getProtectionKeyId() { /** * @param protection - * key id - * the protection key id to set + * key id the protection key id to set */ public void setProtectionKeyId(String protectionKeyId) { this.protectionKeyId = protectionKeyId; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyRestType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyRestType.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyRestType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyRestType.java index d17551fb13fb0..855fa9d74bf6e 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyRestType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ProtectionKeyRestType.java @@ -28,7 +28,7 @@ @XmlRootElement(name = "GetProtectionKey", namespace = Constants.ODATA_DATA_NS) public class ProtectionKeyRestType implements MediaServiceDTO { @XmlValue - String protectionKey; + private String protectionKey; /** * @return the protection key @@ -39,8 +39,7 @@ public String getProtectionKey() { /** * @param protection - * key id - * the protection key id to set + * key id the protection key id to set */ public void setProtectionKey(String protectionKey) { this.protectionKey = protectionKey; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/RebindContentKeyType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/RebindContentKeyType.java similarity index 97% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/RebindContentKeyType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/RebindContentKeyType.java index 9f84670b10689..8cdf5c52014d3 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/RebindContentKeyType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/RebindContentKeyType.java @@ -29,7 +29,7 @@ public class RebindContentKeyType implements MediaServiceDTO { /** The rebind content key. */ @XmlValue - String rebindContentKey; + private String rebindContentKey; /** * Gets the content key. diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskHistoricalEventType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskHistoricalEventType.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskHistoricalEventType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskHistoricalEventType.java index 973b9b53c3e2c..90aca8bdfe1e8 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskHistoricalEventType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskHistoricalEventType.java @@ -22,8 +22,8 @@ import javax.xml.bind.annotation.XmlElement; /** - * This type maps the XML returned in the odata ATOM serialization - * for ErrorDetail entities. + * This type maps the XML returned in the odata ATOM serialization for + * ErrorDetail entities. * */ @XmlAccessorType(XmlAccessType.FIELD) @@ -31,15 +31,15 @@ public class TaskHistoricalEventType implements MediaServiceDTO { /** The code. */ @XmlElement(name = "Code", namespace = Constants.ODATA_DATA_NS) - protected String code; + private String code; /** The message. */ @XmlElement(name = "Message", namespace = Constants.ODATA_DATA_NS) - protected String message; + private String message; /** The time stamp. */ @XmlElement(name = "TimeStamp", namespace = Constants.ODATA_DATA_NS) - protected Date timeStamp; + private Date timeStamp; /** * Gets the code. diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskType.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskType.java index e6486eb697d0b..0f53679eb0848 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/TaskType.java @@ -24,75 +24,75 @@ import javax.xml.bind.annotation.XmlElementWrapper; /** - * This type maps the XML returned in the odata ATOM serialization - * for Task entities. + * This type maps the XML returned in the odata ATOM serialization for Task + * entities. * */ @XmlAccessorType(XmlAccessType.FIELD) public class TaskType implements MediaServiceDTO { @XmlElement(name = "Id", namespace = Constants.ODATA_DATA_NS) - protected String id; + private String id; @XmlElement(name = "Configuration", namespace = Constants.ODATA_DATA_NS) - protected String configuration; + private String configuration; @XmlElement(name = "EndTime", namespace = Constants.ODATA_DATA_NS) - protected Date endTime; + private Date endTime; @XmlElementWrapper(name = "ErrorDetails", namespace = Constants.ODATA_DATA_NS) @XmlElement(name = "element", namespace = Constants.ODATA_DATA_NS) - protected List errorDetails; + private List errorDetails; @XmlElementWrapper(name = "HistoricalEvents", namespace = Constants.ODATA_DATA_NS) @XmlElement(name = "element", namespace = Constants.ODATA_DATA_NS) - protected List historicalEventTypes; + private List historicalEventTypes; @XmlElement(name = "MediaProcessorId", namespace = Constants.ODATA_DATA_NS) - protected String mediaProcessorId; + private String mediaProcessorId; @XmlElement(name = "Name", namespace = Constants.ODATA_DATA_NS) - protected String name; + private String name; @XmlElement(name = "PerfMessage", namespace = Constants.ODATA_DATA_NS) - protected String perfMessage; + private String perfMessage; @XmlElement(name = "Priority", namespace = Constants.ODATA_DATA_NS) - protected Integer priority; + private Integer priority; @XmlElement(name = "Progress", namespace = Constants.ODATA_DATA_NS) - protected Double progress; + private Double progress; @XmlElement(name = "RunningDuration", namespace = Constants.ODATA_DATA_NS) - protected Double runningDuration; + private Double runningDuration; @XmlElement(name = "StartTime", namespace = Constants.ODATA_DATA_NS) - protected Date startTime; + private Date startTime; @XmlElement(name = "State", namespace = Constants.ODATA_DATA_NS) - protected Integer state; + private Integer state; @XmlElement(name = "TaskBody", namespace = Constants.ODATA_DATA_NS) - protected String taskBody; + private String taskBody; @XmlElement(name = "Options", namespace = Constants.ODATA_DATA_NS) - protected Integer options; + private Integer options; @XmlElement(name = "EncryptionKeyId", namespace = Constants.ODATA_DATA_NS) - protected String encryptionKeyId; + private String encryptionKeyId; @XmlElement(name = "EncryptionScheme", namespace = Constants.ODATA_DATA_NS) - protected String encryptionScheme; + private String encryptionScheme; @XmlElement(name = "EncryptionVersion", namespace = Constants.ODATA_DATA_NS) - protected String encryptionVersion; + private String encryptionVersion; @XmlElement(name = "InitializationVector", namespace = Constants.ODATA_DATA_NS) - protected String initializationVector; + private String initializationVector; - protected List outputMediaAssets; + private List outputMediaAssets; - protected List inputMediaAssets; + private List inputMediaAssets; public String getId() { return id; @@ -278,7 +278,8 @@ public List getHistoricalEventTypes() { return historicalEventTypes; } - public TaskType setHistoricalEventTypes(List historicalEventTypes) { + public TaskType setHistoricalEventTypes( + List historicalEventTypes) { this.historicalEventTypes = historicalEventTypes; return this; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/package-info.java b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/package-info.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/package-info.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/package-info.java diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/package.html b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/package.html new file mode 100644 index 0000000000000..e7819f1479631 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/implementation/package.html @@ -0,0 +1,5 @@ + + +This package contains the media service OData operation class, interface, and utility classes. + + diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicy.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicy.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicy.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicy.java index 200d571abb72a..d0988b8337550 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicy.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicy.java @@ -31,7 +31,7 @@ * Class for creating operations to manipulate Access Policy entities. * */ -public class AccessPolicy { +public final class AccessPolicy { private static final String ENTITY_SET = "AccessPolicies"; @@ -49,18 +49,21 @@ private AccessPolicy() { * permissions allowed by this access policy * @return The operation */ - public static EntityCreateOperation create(String name, double durationInMinutes, + public static EntityCreateOperation create(String name, + double durationInMinutes, EnumSet permissions) { return new Creator(name, durationInMinutes, permissions); } - private static class Creator extends EntityOperationSingleResultBase implements + private static class Creator extends + EntityOperationSingleResultBase implements EntityCreateOperation { private final String policyName; private final double durationInMinutes; private final EnumSet permissions; - public Creator(String policyName, double durationInMinutes, EnumSet permissions) { + public Creator(String policyName, double durationInMinutes, + EnumSet permissions) { super(ENTITY_SET, AccessPolicyInfo.class); @@ -71,8 +74,12 @@ public Creator(String policyName, double durationInMinutes, EnumSet get(String accessPolicyId) { - return new DefaultGetOperation(ENTITY_SET, accessPolicyId, AccessPolicyInfo.class); + return new DefaultGetOperation(ENTITY_SET, + accessPolicyId, AccessPolicyInfo.class); } /** - * Create an operation that will retrieve the access policy at the given link + * Create an operation that will retrieve the access policy at the given + * link * * @param link * the link * @return the operation */ - public static EntityGetOperation get(LinkInfo link) { - return new DefaultGetOperation(link.getHref(), AccessPolicyInfo.class); + public static EntityGetOperation get( + LinkInfo link) { + return new DefaultGetOperation(link.getHref(), + AccessPolicyInfo.class); } /** @@ -105,8 +116,9 @@ public static EntityGetOperation get(LinkInfo list() { - return new DefaultListOperation(ENTITY_SET, new GenericType>() { - }); + return new DefaultListOperation(ENTITY_SET, + new GenericType>() { + }); } /** diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfo.java similarity index 96% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfo.java index 290e1bdcb25d5..a51c533b62457 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfo.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfo.java @@ -29,8 +29,8 @@ public class AccessPolicyInfo extends ODataEntity { /** - * Creates a new {@link AccessPolicyInfo} wrapping the given ATOM - * entry and content objects. + * Creates a new {@link AccessPolicyInfo} wrapping the given ATOM entry and + * content objects. * * @param entry * Entry containing this AccessPolicy data @@ -92,6 +92,7 @@ public double getDurationInMinutes() { * @return the permissions. */ public EnumSet getPermissions() { - return AccessPolicyPermission.permissionsFromBits(getContent().getPermissions()); + return AccessPolicyPermission.permissionsFromBits(getContent() + .getPermissions()); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermission.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermission.java similarity index 90% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermission.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermission.java index d721069e6df8b..f9f658a1bbfbe 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermission.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermission.java @@ -39,16 +39,17 @@ public int getFlagValue() { } /** - * Given an integer representing the permissions as a bit vector, - * convert it into an EnumSet<AccessPolicyPermission> object containing the correct permissions - * * + * Given an integer representing the permissions as a bit vector, convert it + * into an EnumSet<AccessPolicyPermission> object + * containing the correct permissions * * * @param bits * The bit vector of permissions * @return The set of permissions in an EnumSet object. */ public static EnumSet permissionsFromBits(int bits) { - EnumSet perms = EnumSet.of(AccessPolicyPermission.NONE); + EnumSet perms = EnumSet + .of(AccessPolicyPermission.NONE); for (AccessPolicyPermission p : AccessPolicyPermission.values()) { if ((bits & p.getFlagValue()) != 0) { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java index 3606cc7fc669e..ab493ff06c425 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Asset.java @@ -38,7 +38,7 @@ * Class for creating operations to manipulate Asset entities. * */ -public class Asset { +public final class Asset { /** The Constant ENTITY_SET. */ private static final String ENTITY_SET = "Assets"; @@ -51,7 +51,7 @@ private Asset() { } /** - * Creates the. + * Creates an Asset Creator. * * @return the creator */ @@ -62,7 +62,8 @@ public static Creator create() { /** * The Class Creator. */ - public static class Creator extends EntityOperationSingleResultBase implements + public static class Creator extends + EntityOperationSingleResultBase implements EntityCreateOperation { /** The name. */ @@ -84,8 +85,11 @@ public Creator() { super(ENTITY_SET, AssetInfo.class); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation#getRequestContents() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityCreateOperation#getRequestContents() */ @Override public Object getRequestContents() { @@ -159,7 +163,8 @@ public Creator setState(AssetState state) { * @return the get operation */ public static EntityGetOperation get(String assetId) { - return new DefaultGetOperation(ENTITY_SET, assetId, AssetInfo.class); + return new DefaultGetOperation(ENTITY_SET, assetId, + AssetInfo.class); } /** @@ -170,7 +175,8 @@ public static EntityGetOperation get(String assetId) { * @return the get operation */ public static EntityGetOperation get(LinkInfo link) { - return new DefaultGetOperation(link.getHref(), AssetInfo.class); + return new DefaultGetOperation(link.getHref(), + AssetInfo.class); } /** @@ -179,8 +185,9 @@ public static EntityGetOperation get(LinkInfo link) { * @return The list operation */ public static DefaultListOperation list() { - return new DefaultListOperation(ENTITY_SET, new GenericType>() { - }); + return new DefaultListOperation(ENTITY_SET, + new GenericType>() { + }); } /** @@ -191,8 +198,9 @@ public static DefaultListOperation list() { * @return The list operation. */ public static DefaultListOperation list(LinkInfo link) { - return new DefaultListOperation(link.getHref(), new GenericType>() { - }); + return new DefaultListOperation(link.getHref(), + new GenericType>() { + }); } /** @@ -209,7 +217,8 @@ public static Updater update(String assetId) { /** * The Class Updater. */ - public static class Updater extends EntityOperationBase implements EntityUpdateOperation { + public static class Updater extends EntityOperationBase implements + EntityUpdateOperation { /** The name. */ private String name; @@ -224,19 +233,28 @@ public static class Updater extends EntityOperationBase implements EntityUpdateO * the asset id */ protected Updater(String assetId) { - super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, assetId)); + super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, + assetId)); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#setProxyData(com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData) + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityOperation + * #setProxyData(com.microsoft.windowsazure.services.media + * .entityoperations.EntityProxyData) */ @Override public void setProxyData(EntityProxyData proxyData) { // Deliberately empty } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation#getRequestContents() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityUpdateOperation#getRequestContents() */ @Override public Object getRequestContents() { @@ -291,15 +309,17 @@ public static EntityDeleteOperation delete(String assetId) { * the content key id * @return the entity action operation */ - public static EntityLinkOperation linkContentKey(String assetId, String contentKeyId) { + public static EntityLinkOperation linkContentKey(String assetId, + String contentKeyId) { String escapedContentKeyId = null; try { escapedContentKeyId = URLEncoder.encode(contentKeyId, "UTF-8"); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { throw new InvalidParameterException("contentKeyId"); } - URI contentKeyUri = URI.create(String.format("ContentKeys('%s')", escapedContentKeyId)); - return new EntityLinkOperation("Assets", assetId, "ContentKeys", contentKeyUri); + URI contentKeyUri = URI.create(String.format("ContentKeys('%s')", + escapedContentKeyId)); + return new EntityLinkOperation("Assets", assetId, "ContentKeys", + contentKeyUri); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFile.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFile.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFile.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFile.java index b8406b208dc70..1b2178e02831e 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFile.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFile.java @@ -18,7 +18,7 @@ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.entityoperations.DefaultActionOperation; import com.microsoft.windowsazure.services.media.entityoperations.DefaultDeleteOperation; import com.microsoft.windowsazure.services.media.entityoperations.DefaultGetOperation; @@ -34,7 +34,7 @@ import com.microsoft.windowsazure.services.media.implementation.content.AssetFileType; import com.sun.jersey.api.client.GenericType; -public class AssetFile { +public final class AssetFile { private static final String ENTITY_SET = "Files"; // Prevent instantiation @@ -45,7 +45,8 @@ public static Creator create(String parentAssetId, String name) { return new Creator(parentAssetId, name); } - public static class Creator extends EntityOperationSingleResultBase implements + public static final class Creator extends + EntityOperationSingleResultBase implements EntityCreateOperation { private final String parentAssetId; private final String name; @@ -67,11 +68,16 @@ private Creator(String parentAssetId, String name) { @Override public Object getRequestContents() throws ServiceException { - AssetFileType content = new AssetFileType().setName(name).setParentAssetId(parentAssetId) - .setContentChecksum(contentChecksum).setContentFileSize(contentFileSize) - .setEncryptionKeyId(encryptionKeyId).setEncryptionScheme(encryptionScheme) - .setEncryptionVersion(encryptionVersion).setInitializationVector(initializationVector) - .setIsEncrypted(isEncrypted).setIsPrimary(isPrimary).setMimeType(mimeType); + AssetFileType content = new AssetFileType().setName(name) + .setParentAssetId(parentAssetId) + .setContentChecksum(contentChecksum) + .setContentFileSize(contentFileSize) + .setEncryptionKeyId(encryptionKeyId) + .setEncryptionScheme(encryptionScheme) + .setEncryptionVersion(encryptionVersion) + .setInitializationVector(initializationVector) + .setIsEncrypted(isEncrypted).setIsPrimary(isPrimary) + .setMimeType(mimeType); return content; } @@ -171,12 +177,12 @@ public static EntityActionOperation createFileInfos(String assetId) { String encodedId; try { encodedId = URLEncoder.encode(assetId, "UTF-8"); - } - catch (UnsupportedEncodingException ex) { + } catch (UnsupportedEncodingException ex) { // This can never happen unless JVM is broken throw new RuntimeException(ex); } - return new DefaultActionOperation("CreateFileInfos").addQueryParameter("assetid", "'" + encodedId + "'"); + return new DefaultActionOperation("CreateFileInfos").addQueryParameter( + "assetid", "'" + encodedId + "'"); } /** @@ -187,7 +193,8 @@ public static EntityActionOperation createFileInfos(String assetId) { * @return the get operation to pass to rest proxy */ public static EntityGetOperation get(String assetFileId) { - return new DefaultGetOperation(ENTITY_SET, assetFileId, AssetFileInfo.class); + return new DefaultGetOperation(ENTITY_SET, assetFileId, + AssetFileInfo.class); } /** @@ -196,8 +203,9 @@ public static EntityGetOperation get(String assetFileId) { * @return The list operation to pass to rest proxy. */ public static DefaultListOperation list() { - return new DefaultListOperation(ENTITY_SET, new GenericType>() { - }); + return new DefaultListOperation(ENTITY_SET, + new GenericType>() { + }); } /** @@ -207,16 +215,19 @@ public static DefaultListOperation list() { * Link to request AssetFiles from. * @return The list operation. */ - public static DefaultListOperation list(LinkInfo link) { - return new DefaultListOperation(link.getHref(), new GenericType>() { - }); + public static DefaultListOperation list( + LinkInfo link) { + return new DefaultListOperation(link.getHref(), + new GenericType>() { + }); } public static Updater update(String assetFileId) { return new Updater(assetFileId); } - public static class Updater extends EntityOperationBase implements EntityUpdateOperation { + public static final class Updater extends EntityOperationBase implements + EntityUpdateOperation { private String contentChecksum; private Long contentFileSize; private String encryptionKeyId; @@ -228,19 +239,29 @@ public static class Updater extends EntityOperationBase implements EntityUpdateO private String mimeType; private Updater(String assetFileId) { - super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, assetFileId)); + super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, + assetFileId)); } @Override public Object getRequestContents() { - return new AssetFileType().setContentChecksum(contentChecksum).setContentFileSize(contentFileSize) - .setEncryptionKeyId(encryptionKeyId).setEncryptionScheme(encryptionScheme) - .setEncryptionVersion(encryptionVersion).setInitializationVector(initializationVector) - .setIsEncrypted(isEncrypted).setIsPrimary(isPrimary).setMimeType(mimeType); + return new AssetFileType().setContentChecksum(contentChecksum) + .setContentFileSize(contentFileSize) + .setEncryptionKeyId(encryptionKeyId) + .setEncryptionScheme(encryptionScheme) + .setEncryptionVersion(encryptionVersion) + .setInitializationVector(initializationVector) + .setIsEncrypted(isEncrypted).setIsPrimary(isPrimary) + .setMimeType(mimeType); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#setProxyData(com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData) + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityOperation + * #setProxyData(com.microsoft.windowsazure.services.media + * .entityoperations.EntityProxyData) */ @Override public void setProxyData(EntityProxyData proxyData) { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFileInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFileInfo.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFileInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetFileInfo.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetInfo.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetInfo.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetOption.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetOption.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetOption.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetOption.java index 8722e853ffcf5..ff0984205decb 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetOption.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetOption.java @@ -52,8 +52,7 @@ public int getCode() { } /** - * Create an AssetOption instance based on the - * given integer. + * Create an AssetOption instance based on the given integer. * * @param option * the integer value of option @@ -61,14 +60,14 @@ public int getCode() { */ public static AssetOption fromCode(int option) { switch (option) { - case 0: - return AssetOption.None; - case 1: - return AssetOption.StorageEncrypted; - case 2: - return AssetOption.CommonEncryptionProtected; - default: - throw new InvalidParameterException("option"); + case 0: + return AssetOption.None; + case 1: + return AssetOption.StorageEncrypted; + case 2: + return AssetOption.CommonEncryptionProtected; + default: + throw new InvalidParameterException("option"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetState.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetState.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetState.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetState.java index 8afc9954a8bda..bbadf9a1bc204 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/AssetState.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/AssetState.java @@ -60,14 +60,14 @@ public int getCode() { */ public static AssetState fromCode(int state) { switch (state) { - case 0: - return AssetState.Initialized; - case 1: - return AssetState.Published; - case 2: - return AssetState.Deleted; - default: - throw new InvalidParameterException("state"); + case 0: + return AssetState.Initialized; + case 1: + return AssetState.Published; + case 2: + return AssetState.Deleted; + default: + throw new InvalidParameterException("state"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKey.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKey.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKey.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKey.java index 6f579dd608a5b..c78cdd865006f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKey.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKey.java @@ -26,7 +26,7 @@ import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; +import com.microsoft.windowsazure.core.pipeline.PipelineHelpers; import com.microsoft.windowsazure.services.media.entityoperations.DefaultDeleteOperation; import com.microsoft.windowsazure.services.media.entityoperations.DefaultEntityTypeActionOperation; import com.microsoft.windowsazure.services.media.entityoperations.DefaultGetOperation; @@ -45,7 +45,7 @@ * Class for creating operations to manipulate content key entities. * */ -public class ContentKey { +public final class ContentKey { /** The Constant ENTITY_SET. */ private static final String ENTITY_SET = "ContentKeys"; @@ -67,14 +67,16 @@ private ContentKey() { * the encrypted content key * @return The operation */ - public static Creator create(String id, ContentKeyType contentKeyType, String encryptedContentKey) { + public static Creator create(String id, ContentKeyType contentKeyType, + String encryptedContentKey) { return new Creator(id, contentKeyType, encryptedContentKey); } /** * The Class Creator. */ - public static class Creator extends EntityOperationSingleResultBase implements + public static class Creator extends + EntityOperationSingleResultBase implements EntityCreateOperation { /** The id. */ @@ -108,7 +110,8 @@ public static class Creator extends EntityOperationSingleResultBase get(String contentKeyId) { - return new DefaultGetOperation(ENTITY_SET, contentKeyId, ContentKeyInfo.class); + return new DefaultGetOperation(ENTITY_SET, + contentKeyId, ContentKeyInfo.class); } /** @@ -202,20 +210,24 @@ public static EntityGetOperation get(String contentKeyId) { * @return the operation */ public static DefaultListOperation list() { - return new DefaultListOperation(ENTITY_SET, new GenericType>() { - }); + return new DefaultListOperation(ENTITY_SET, + new GenericType>() { + }); } /** - * Create an operation that will list all the content keys at the given link. + * Create an operation that will list all the content keys at the given + * link. * * @param link * Link to request content keys from. * @return The list operation. */ - public static DefaultListOperation list(LinkInfo link) { - return new DefaultListOperation(link.getHref(), new GenericType>() { - }); + public static DefaultListOperation list( + LinkInfo link) { + return new DefaultListOperation(link.getHref(), + new GenericType>() { + }); } /** @@ -238,8 +250,10 @@ public static EntityDeleteOperation delete(String contentKeyId) { * the x509 certificate * @return the entity action operation */ - public static EntityTypeActionOperation rebind(String contentKeyId, String x509Certificate) { - return new RebindContentKeyActionOperation(contentKeyId, x509Certificate); + public static EntityTypeActionOperation rebind(String contentKeyId, + String x509Certificate) { + return new RebindContentKeyActionOperation(contentKeyId, + x509Certificate); } /** @@ -253,42 +267,44 @@ public static EntityTypeActionOperation rebind(String contentKeyId) { return rebind(contentKeyId, ""); } - private static class RebindContentKeyActionOperation extends DefaultEntityTypeActionOperation { + private static class RebindContentKeyActionOperation extends + DefaultEntityTypeActionOperation { private final JAXBContext jaxbContext; private final Unmarshaller unmarshaller; - public RebindContentKeyActionOperation(String contentKeyId, String x509Certificate) { + public RebindContentKeyActionOperation(String contentKeyId, + String x509Certificate) { super("RebindContentKey"); String escapedContentKeyId; try { escapedContentKeyId = URLEncoder.encode(contentKeyId, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new InvalidParameterException( + "UTF-8 encoding is not supported."); } - catch (UnsupportedEncodingException e) { - throw new InvalidParameterException("UTF-8 encoding is not supported."); - } - this.addQueryParameter("x509Certificate", "'" + x509Certificate + "'"); + this.addQueryParameter("x509Certificate", "'" + x509Certificate + + "'"); this.addQueryParameter("id", "'" + escapedContentKeyId + "'"); try { - jaxbContext = JAXBContext.newInstance(RebindContentKeyType.class); - } - catch (JAXBException e) { + jaxbContext = JAXBContext + .newInstance(RebindContentKeyType.class); + } catch (JAXBException e) { throw new RuntimeException(e); } try { unmarshaller = jaxbContext.createUnmarshaller(); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); } } @Override public String processTypeResponse(ClientResponse clientResponse) { - PipelineHelpers.ThrowIfNotSuccess(clientResponse); + PipelineHelpers.throwIfNotSuccess(clientResponse); RebindContentKeyType rebindContentKeyType = parseResponse(clientResponse); return rebindContentKeyType.getContentKey(); } @@ -297,10 +313,10 @@ private RebindContentKeyType parseResponse(ClientResponse clientResponse) { InputStream inputStream = clientResponse.getEntityInputStream(); JAXBElement rebindContentKeyTypeJaxbElement; try { - rebindContentKeyTypeJaxbElement = unmarshaller.unmarshal(new StreamSource(inputStream), + rebindContentKeyTypeJaxbElement = unmarshaller.unmarshal( + new StreamSource(inputStream), RebindContentKeyType.class); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); } return rebindContentKeyTypeJaxbElement.getValue(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfo.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfo.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyType.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyType.java index 6015424f6e6b1..8cd0f5d589660 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ContentKeyType.java @@ -62,14 +62,14 @@ public int getCode() { */ public static ContentKeyType fromCode(int code) { switch (code) { - case 0: - return ContentKeyType.CommonEncryption; - case 1: - return ContentKeyType.StorageEncryption; - case 2: - return ContentKeyType.ConfigurationEncryption; - default: - throw new InvalidParameterException("code"); + case 0: + return ContentKeyType.CommonEncryption; + case 1: + return ContentKeyType.StorageEncryption; + case 2: + return ContentKeyType.ConfigurationEncryption; + default: + throw new InvalidParameterException("code"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/EndPointType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/EndPointType.java similarity index 91% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/EndPointType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/EndPointType.java index 86a8e2367a25c..9a135b1645a87 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/EndPointType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/EndPointType.java @@ -56,10 +56,10 @@ public int getCode() { */ public static EndPointType fromCode(int code) { switch (code) { - case 1: - return AzureQueue; - default: - throw new InvalidParameterException("code"); + case 1: + return AzureQueue; + default: + throw new InvalidParameterException("code"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ErrorDetail.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ErrorDetail.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ErrorDetail.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/ErrorDetail.java diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/models/Ipv4.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Ipv4.java new file mode 100644 index 0000000000000..e2889f30d29db --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Ipv4.java @@ -0,0 +1,62 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.models; + +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * The Class Ipv4. + */ +public class Ipv4 { + + /** The name. */ + private String name; + + /** The ip. */ + private String ip; + + /** + * Gets the name. + * + * @return the name + */ + @JsonProperty("Name") + public String getName() { + return this.name; + } + + @JsonProperty("Name") + public Ipv4 setName(String name) { + this.name = name; + return this; + } + + /** + * Gets the ip. + * + * @return the ip + */ + @JsonProperty("IP") + public String getIp() { + return this.ip; + } + + @JsonProperty("IP") + public Ipv4 setIp(String ip) { + this.ip = ip; + return this; + } +} \ No newline at end of file diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Job.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Job.java similarity index 80% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Job.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/Job.java index 6103da02d6def..fe687703eeb72 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Job.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Job.java @@ -26,7 +26,7 @@ import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.entityoperations.DefaultActionOperation; import com.microsoft.windowsazure.services.media.entityoperations.DefaultDeleteOperation; import com.microsoft.windowsazure.services.media.entityoperations.DefaultGetOperation; @@ -47,7 +47,7 @@ * Class for creating operations to manipulate Job entities. * */ -public class Job { +public final class Job { /** The Constant ENTITY_SET. */ private static final String ENTITY_SET = "Jobs"; @@ -71,7 +71,8 @@ public static Creator create() { /** * The Class Creator. */ - public static class Creator extends EntityOperationSingleResultBase implements + public static class Creator extends + EntityOperationSingleResultBase implements EntityCreateOperation { /** The name. */ @@ -109,15 +110,14 @@ public static class Creator extends EntityOperationSingleResultBase imp */ private void buildMimeMultipart(URI serviceUri) { mediaBatchOperations = null; - CreateBatchOperation createJobBatchOperation = CreateBatchOperation.create(serviceUri, this); + CreateBatchOperation createJobBatchOperation = CreateBatchOperation + .create(serviceUri, this); try { mediaBatchOperations = new MediaBatchOperations(serviceUri); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); - } - catch (ParserConfigurationException e) { + } catch (ParserConfigurationException e) { throw new RuntimeException(e); } @@ -128,14 +128,11 @@ private void buildMimeMultipart(URI serviceUri) { try { mimeMultipart = mediaBatchOperations.getMimeMultipart(); - } - catch (MessagingException e) { + } catch (MessagingException e) { throw new RuntimeException(e); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); } @@ -154,8 +151,11 @@ public Creator() { this.fresh = true; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation#getRequestContents() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityCreateOperation#getRequestContents() */ @Override public Object getRequestContents() throws ServiceException { @@ -165,8 +165,11 @@ public Object getRequestContents() throws ServiceException { return mimeMultipart; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperationSingleResultBase#getResponseClass() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityOperationSingleResultBase#getResponseClass() */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Override @@ -174,21 +177,27 @@ public Class getResponseClass() { return ClientResponse.class; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation#processResponse(java.lang.Object) + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityCreateOperation#processResponse(java.lang.Object) */ @Override - public Object processResponse(Object clientResponse) throws ServiceException { + public Object processResponse(Object clientResponse) + throws ServiceException { try { - this.mediaBatchOperations.parseBatchResult((ClientResponse) clientResponse); - } - catch (IOException e) { + this.mediaBatchOperations + .parseBatchResult((ClientResponse) clientResponse); + } catch (IOException e) { throw new ServiceException(e); } JobInfo jobInfo = null; - for (EntityBatchOperation entityBatchOperation : this.mediaBatchOperations.getOperations()) { + for (EntityBatchOperation entityBatchOperation : this.mediaBatchOperations + .getOperations()) { if (entityBatchOperation instanceof Job.CreateBatchOperation) { - jobInfo = ((Job.CreateBatchOperation) entityBatchOperation).getJobInfo(); + jobInfo = ((Job.CreateBatchOperation) entityBatchOperation) + .getJobInfo(); break; } } @@ -203,7 +212,8 @@ public Object processResponse(Object clientResponse) throws ServiceException { * the task create batch operation * @return the creator */ - public Creator addTaskCreator(Task.CreateBatchOperation taskCreateBatchOperation) { + public Creator addTaskCreator( + Task.CreateBatchOperation taskCreateBatchOperation) { this.taskCreateBatchOperations.add(taskCreateBatchOperation); this.fresh = true; return this; @@ -284,8 +294,11 @@ public Creator addInputMediaAsset(String assetId) { return this; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperationBase#getContentType() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityOperationBase#getContentType() */ @Override public MediaType getContentType() { @@ -295,8 +308,11 @@ public MediaType getContentType() { return this.contentType; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperationBase#getUri() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityOperationBase#getUri() */ @Override public String getUri() { @@ -310,7 +326,8 @@ public String getUri() { * the job notification subscription * @return the creator */ - public Creator addJobNotificationSubscription(JobNotificationSubscription jobNotificationSubscription) { + public Creator addJobNotificationSubscription( + JobNotificationSubscription jobNotificationSubscription) { this.jobNotificationSubscriptions.add(jobNotificationSubscription); this.fresh = true; return this; @@ -345,7 +362,7 @@ public static class CreateBatchOperation extends EntityBatchOperation { */ public CreateBatchOperation(URI serviceUri) { this.serviceUri = serviceUri; - this.verb = "POST"; + this.setVerb("POST"); } /** @@ -357,25 +374,36 @@ public CreateBatchOperation(URI serviceUri) { * the creator * @return the creates the batch operation */ - public static CreateBatchOperation create(URI serviceUri, Creator creator) { - CreateBatchOperation createBatchOperation = new CreateBatchOperation(serviceUri); + public static CreateBatchOperation create(URI serviceUri, + Creator creator) { + CreateBatchOperation createBatchOperation = new CreateBatchOperation( + serviceUri); JobType jobType = new JobType(); jobType.setName(creator.getName()); jobType.setPriority(creator.getPriority()); - for (JobNotificationSubscription jobNotificationSubscription : creator.getJobNotificationSubscription()) { + for (JobNotificationSubscription jobNotificationSubscription : creator + .getJobNotificationSubscription()) { JobNotificationSubscriptionType jobNotificationSubscriptionType = new JobNotificationSubscriptionType(); - jobNotificationSubscriptionType.setNotificationEndPointId(jobNotificationSubscription - .getNotificationEndPointId()); - jobNotificationSubscriptionType.setTargetJobState(jobNotificationSubscription.getTargetJobState() - .getCode()); + jobNotificationSubscriptionType + .setNotificationEndPointId(jobNotificationSubscription + .getNotificationEndPointId()); + jobNotificationSubscriptionType + .setTargetJobState(jobNotificationSubscription + .getTargetJobState().getCode()); jobType.addJobNotificationSubscriptionType(jobNotificationSubscriptionType); } for (String inputMediaAsset : creator.getInputMediaAssets()) { - createBatchOperation.addLink("InputMediaAssets", String.format("%s/Assets('%s')", createBatchOperation - .getServiceUri().toString(), inputMediaAsset.toString()), "application/atom+xml;type=feed", - "http://schemas.microsoft.com/ado/2007/08/dataservices/related/InputMediaAssets"); + createBatchOperation + .addLink( + "InputMediaAssets", + String.format("%s/Assets('%s')", + createBatchOperation.getServiceUri() + .toString(), inputMediaAsset + .toString()), + "application/atom+xml;type=feed", + "http://schemas.microsoft.com/ado/2007/08/dataservices/related/InputMediaAssets"); } createBatchOperation.addContentObject(jobType); return createBatchOperation; @@ -421,7 +449,8 @@ public JobInfo getJobInfo() { * @return the get operation */ public static EntityGetOperation get(String jobId) { - return new DefaultGetOperation(ENTITY_SET, jobId, JobInfo.class); + return new DefaultGetOperation(ENTITY_SET, jobId, + JobInfo.class); } /** @@ -430,8 +459,9 @@ public static EntityGetOperation get(String jobId) { * @return The list operation */ public static DefaultListOperation list() { - return new DefaultListOperation(ENTITY_SET, new GenericType>() { - }); + return new DefaultListOperation(ENTITY_SET, + new GenericType>() { + }); } /** @@ -453,6 +483,7 @@ public static EntityDeleteOperation delete(String jobId) { * @return the entity action operation */ public static EntityActionOperation cancel(String jobId) { - return new DefaultActionOperation("CancelJob").addQueryParameter("jobId", String.format("'%s'", jobId)); + return new DefaultActionOperation("CancelJob").addQueryParameter( + "jobId", String.format("'%s'", jobId)); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobInfo.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/JobInfo.java index d6bb193f1a279..ad8948b056769 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobInfo.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobInfo.java @@ -163,7 +163,8 @@ public LinkInfo getTasksLink() { * @return the job notification subscriptions */ public List getJobNotificationSubscriptions() { - return JobNotificationSubscriptionListFactory.create(getContent().getJobNotificationSubscriptionTypes()); + return JobNotificationSubscriptionListFactory.create(getContent() + .getJobNotificationSubscriptionTypes()); } /** @@ -173,11 +174,16 @@ public List getJobNotificationSubscriptions() { * the job notification subscription * @return the job info */ - public JobInfo addJobNotificationSubscription(JobNotificationSubscription jobNotificationSubscription) { + public JobInfo addJobNotificationSubscription( + JobNotificationSubscription jobNotificationSubscription) { getContent().addJobNotificationSubscriptionType( - new JobNotificationSubscriptionType().setNotificationEndPointId( - jobNotificationSubscription.getNotificationEndPointId()).setTargetJobState( - jobNotificationSubscription.getTargetJobState().getCode())); + new JobNotificationSubscriptionType() + .setNotificationEndPointId( + jobNotificationSubscription + .getNotificationEndPointId()) + .setTargetJobState( + jobNotificationSubscription.getTargetJobState() + .getCode())); return this; } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscription.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscription.java similarity index 97% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscription.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscription.java index 6cd4ea59e3011..9e5360a9344c8 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscription.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscription.java @@ -34,7 +34,8 @@ public class JobNotificationSubscription { * @param targetJobState * the target job state */ - public JobNotificationSubscription(String notificationEndPointId, TargetJobState targetJobState) { + public JobNotificationSubscription(String notificationEndPointId, + TargetJobState targetJobState) { this.notificationEndPointId = notificationEndPointId; this.targetJobState = targetJobState; } diff --git a/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscriptionListFactory.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscriptionListFactory.java new file mode 100644 index 0000000000000..86006d6301484 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscriptionListFactory.java @@ -0,0 +1,47 @@ +/* + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.models; + +import java.util.ArrayList; +import java.util.List; + +import com.microsoft.windowsazure.services.media.implementation.content.JobNotificationSubscriptionType; + +/** + * The Class JobNotificationSubscription factory. + */ +public abstract class JobNotificationSubscriptionListFactory { + + public static List create( + List jobNotificationSubscriptionTypeList) { + if (jobNotificationSubscriptionTypeList == null) { + throw new IllegalArgumentException( + "The jobNotificationSubscriptionTypeList cannot be null."); + } + List jobNotificationSubscriptionList = new ArrayList(); + for (JobNotificationSubscriptionType jobNotificationSubscriptionType : jobNotificationSubscriptionTypeList) { + jobNotificationSubscriptionList + .add(new JobNotificationSubscription( + jobNotificationSubscriptionType + .getNotificationEndPointId(), + TargetJobState + .fromCode(jobNotificationSubscriptionType + .getTargetJobState()))); + } + return jobNotificationSubscriptionList; + + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobState.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobState.java similarity index 76% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobState.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/JobState.java index b7bce6a0b273d..b1edbc7e1d23f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobState.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/JobState.java @@ -73,22 +73,22 @@ public int getCode() { */ public static JobState fromCode(int jobStateCode) { switch (jobStateCode) { - case 0: - return JobState.Queued; - case 1: - return JobState.Scheduled; - case 2: - return JobState.Processing; - case 3: - return JobState.Finished; - case 4: - return JobState.Error; - case 5: - return JobState.Canceled; - case 6: - return JobState.Canceling; - default: - throw new InvalidParameterException("jobStateCode"); + case 0: + return JobState.Queued; + case 1: + return JobState.Scheduled; + case 2: + return JobState.Processing; + case 3: + return JobState.Finished; + case 4: + return JobState.Error; + case 5: + return JobState.Canceled; + case 6: + return JobState.Canceling; + default: + throw new InvalidParameterException("jobStateCode"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/LinkInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/LinkInfo.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/LinkInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/LinkInfo.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ListResult.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ListResult.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ListResult.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/ListResult.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Locator.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Locator.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Locator.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/Locator.java index a565db206d7af..11402e7e0b74e 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Locator.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Locator.java @@ -32,10 +32,10 @@ /** * Implementation of Locator entity. */ -public class Locator { +public final class Locator { /** The Constant ENTITY_SET. */ - private final static String ENTITY_SET = "Locators"; + private static final String ENTITY_SET = "Locators"; /** * Instantiates a new locator. @@ -54,14 +54,16 @@ private Locator() { * locator type * @return the operation */ - public static Creator create(String accessPolicyId, String assetId, LocatorType locatorType) { + public static Creator create(String accessPolicyId, String assetId, + LocatorType locatorType) { return new Creator(accessPolicyId, assetId, locatorType); } /** * The Class Creator. */ - public static class Creator extends EntityOperationSingleResultBase implements + public static class Creator extends + EntityOperationSingleResultBase implements EntityCreateOperation { /** The access policy id. */ @@ -98,21 +100,28 @@ public static class Creator extends EntityOperationSingleResultBase * @param locatorType * the locator type */ - protected Creator(String accessPolicyId, String assetId, LocatorType locatorType) { + protected Creator(String accessPolicyId, String assetId, + LocatorType locatorType) { super(ENTITY_SET, LocatorInfo.class); this.accessPolicyId = accessPolicyId; this.assetId = assetId; this.locatorType = locatorType; } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation#getRequestContents() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityCreateOperation#getRequestContents() */ @Override public Object getRequestContents() { - return new LocatorRestType().setId(id).setAccessPolicyId(accessPolicyId).setAssetId(assetId) - .setStartTime(startDateTime).setType(locatorType.getCode()).setBaseUri(baseUri) - .setContentAccessComponent(contentAccessComponent).setPath(path); + return new LocatorRestType().setId(id) + .setAccessPolicyId(accessPolicyId).setAssetId(assetId) + .setStartTime(startDateTime).setType(locatorType.getCode()) + .setBaseUri(baseUri) + .setContentAccessComponent(contentAccessComponent) + .setPath(path); } /** @@ -184,7 +193,8 @@ public EntityCreateOperation setId(String id) { * @return the get operation */ public static EntityGetOperation get(String locatorId) { - return new DefaultGetOperation(ENTITY_SET, locatorId, LocatorInfo.class); + return new DefaultGetOperation(ENTITY_SET, locatorId, + LocatorInfo.class); } /** @@ -193,8 +203,9 @@ public static EntityGetOperation get(String locatorId) { * @return the list operation */ public static DefaultListOperation list() { - return new DefaultListOperation(ENTITY_SET, new GenericType>() { - }); + return new DefaultListOperation(ENTITY_SET, + new GenericType>() { + }); } /** @@ -204,9 +215,11 @@ public static DefaultListOperation list() { * Link to request locators from. * @return The list operation. */ - public static DefaultListOperation list(LinkInfo link) { - return new DefaultListOperation(link.getHref(), new GenericType>() { - }); + public static DefaultListOperation list( + LinkInfo link) { + return new DefaultListOperation(link.getHref(), + new GenericType>() { + }); } /** @@ -223,7 +236,8 @@ public static Updater update(String locatorId) { /** * The Class Updater. */ - public static class Updater extends EntityOperationBase implements EntityUpdateOperation { + public static class Updater extends EntityOperationBase implements + EntityUpdateOperation { /** The start date time. */ private Date startDateTime; @@ -235,19 +249,28 @@ public static class Updater extends EntityOperationBase implements EntityUpdateO * the locator id */ public Updater(String locatorId) { - super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, locatorId)); + super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, + locatorId)); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation#getRequestContents() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityUpdateOperation#getRequestContents() */ @Override public Object getRequestContents() { return new LocatorRestType().setStartTime(startDateTime); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#setProxyData(com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData) + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityOperation + * #setProxyData(com.microsoft.windowsazure.services.media + * .entityoperations.EntityProxyData) */ @Override public void setProxyData(EntityProxyData proxyData) { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorInfo.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorInfo.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorType.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorType.java index d8ade5d01c4ba..4fa6409e72b3c 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/LocatorType.java @@ -60,14 +60,14 @@ public int getCode() { */ public static LocatorType fromCode(int type) { switch (type) { - case 0: - return LocatorType.None; - case 1: - return LocatorType.SAS; - case 2: - return LocatorType.OnDemandOrigin; - default: - throw new InvalidParameterException("type"); + case 0: + return LocatorType.None; + case 1: + return LocatorType.SAS; + case 2: + return LocatorType.OnDemandOrigin; + default: + throw new InvalidParameterException("type"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessor.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessor.java similarity index 97% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessor.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessor.java index 9be60e4ee3bd6..adc6186c2694b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessor.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessor.java @@ -22,7 +22,7 @@ * Entity operations for Media processors * */ -public class MediaProcessor { +public final class MediaProcessor { private static final String ENTITY_SET = "MediaProcessors"; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfo.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfo.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPoint.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPoint.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPoint.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPoint.java index 123e4c2255b4d..7226b842db245 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPoint.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPoint.java @@ -31,7 +31,7 @@ * Class for creating operations to manipulate notification end point entities. * */ -public class NotificationEndPoint { +public final class NotificationEndPoint { private static final String ENTITY_SET = "NotificationEndPoints"; @@ -49,18 +49,20 @@ private NotificationEndPoint() { * the address of the end point. * @return The operation */ - public static EntityCreateOperation create(String name, EndPointType endPointType, - String endPointAddress) { + public static EntityCreateOperation create( + String name, EndPointType endPointType, String endPointAddress) { return new Creator(name, endPointType, endPointAddress); } - public static class Creator extends EntityOperationSingleResultBase implements + public static class Creator extends + EntityOperationSingleResultBase implements EntityCreateOperation { private final String name; private final EndPointType endPointType; private final String endPointAddress; - public Creator(String name, EndPointType endPointType, String endPointAddress) { + public Creator(String name, EndPointType endPointType, + String endPointAddress) { super(ENTITY_SET, NotificationEndPointInfo.class); @@ -71,7 +73,8 @@ public Creator(String name, EndPointType endPointType, String endPointAddress) { @Override public Object getRequestContents() { - return new NotificationEndPointType().setName(name).setEndPointType(endPointType.getCode()) + return new NotificationEndPointType().setName(name) + .setEndPointType(endPointType.getCode()) .setEndPointAddress(endPointAddress); } } @@ -83,20 +86,24 @@ public Object getRequestContents() { * id of notification end point to retrieve * @return the operation */ - public static EntityGetOperation get(String notificationEndPointId) { - return new DefaultGetOperation(ENTITY_SET, notificationEndPointId, - NotificationEndPointInfo.class); + public static EntityGetOperation get( + String notificationEndPointId) { + return new DefaultGetOperation(ENTITY_SET, + notificationEndPointId, NotificationEndPointInfo.class); } /** - * Create an operation that will retrieve the notification end point at the given link + * Create an operation that will retrieve the notification end point at the + * given link * * @param link * the link * @return the operation */ - public static EntityGetOperation get(LinkInfo link) { - return new DefaultGetOperation(link.getHref(), NotificationEndPointInfo.class); + public static EntityGetOperation get( + LinkInfo link) { + return new DefaultGetOperation( + link.getHref(), NotificationEndPointInfo.class); } /** @@ -128,7 +135,8 @@ public static EntityDeleteOperation delete(String notificationEndPointId) { /** * The Class Updater. */ - public static class Updater extends EntityOperationBase implements EntityUpdateOperation { + public static class Updater extends EntityOperationBase implements + EntityUpdateOperation { /** The name. */ private String name; @@ -140,11 +148,15 @@ public static class Updater extends EntityOperationBase implements EntityUpdateO * the asset id */ protected Updater(String notificationEndPointId) { - super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, notificationEndPointId)); + super(new EntityOperationBase.EntityIdUriBuilder(ENTITY_SET, + notificationEndPointId)); } - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation#getRequestContents() + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * EntityUpdateOperation#getRequestContents() */ @Override public Object getRequestContents() { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfo.java similarity index 91% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfo.java index 511b5194a70f3..8b7b2a1ae389a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfo.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfo.java @@ -25,7 +25,8 @@ * Type containing data about notification end points. * */ -public class NotificationEndPointInfo extends ODataEntity { +public class NotificationEndPointInfo extends + ODataEntity { /** * Creates a new {@link NotificationEndPointInfo} wrapping the given ATOM @@ -36,7 +37,8 @@ public class NotificationEndPointInfo extends ODataEntity getProtectionKeyId( + ContentKeyType contentKeyType) { + return new GetProtectionKeyIdActionOperation("GetProtectionKeyId") + .addQueryParameter("contentKeyType", + String.format("%d", contentKeyType.getCode())) + .setAcceptType(MediaType.APPLICATION_XML_TYPE); + } + + /** + * Gets the protection key. + * + * @param protectionKeyId + * the protection key id + * @return the protection key + */ + public static EntityTypeActionOperation getProtectionKey( + String protectionKeyId) { + return new GetProtectionKeyActionOperation("GetProtectionKey") + .addQueryParameter("ProtectionKeyId", + String.format("'%s'", protectionKeyId)).setAcceptType( + MediaType.APPLICATION_XML_TYPE); + } + + /** + * The Class GetProtectionKeyIdActionOperation. + * + * @param + */ + private static class GetProtectionKeyIdActionOperation extends + DefaultEntityTypeActionOperation { + + /** The jaxb context. */ + private final JAXBContext jaxbContext; + + /** The unmarshaller. */ + private final Unmarshaller unmarshaller; + + /** + * Instantiates a new gets the protection key id action operation. + * + * @param name + * the name + */ + public GetProtectionKeyIdActionOperation(String name) { + super(name); + try { + jaxbContext = JAXBContext + .newInstance(ProtectionKeyIdType.class); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + + try { + unmarshaller = jaxbContext.createUnmarshaller(); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * DefaultActionOperation + * #processResponse(com.sun.jersey.api.client.ClientResponse) + */ + @Override + public String processTypeResponse(ClientResponse clientResponse) { + PipelineHelpers.throwIfNotSuccess(clientResponse); + ProtectionKeyIdType protectionKeyIdType; + try { + protectionKeyIdType = parseResponse(clientResponse); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + + return protectionKeyIdType.getProtectionKeyId(); + } + + /** + * Parses the response. + * + * @param clientResponse + * the client response + * @return the protection key id type + * @throws JAXBException + * the jAXB exception + */ + private ProtectionKeyIdType parseResponse(ClientResponse clientResponse) + throws JAXBException { + + InputStream inputStream = clientResponse.getEntityInputStream(); + JAXBElement protectionKeyIdTypeJaxbElement = unmarshaller + .unmarshal(new StreamSource(inputStream), + ProtectionKeyIdType.class); + return protectionKeyIdTypeJaxbElement.getValue(); + + } + + } + + /** + * The Class GetProtectionKeyActionOperation. + */ + private static class GetProtectionKeyActionOperation extends + DefaultEntityTypeActionOperation { + + /** The jaxb context. */ + private final JAXBContext jaxbContext; + + /** The unmarshaller. */ + private final Unmarshaller unmarshaller; + + /** + * Instantiates a new gets the protection key action operation. + * + * @param name + * the name + */ + public GetProtectionKeyActionOperation(String name) { + super(name); + try { + jaxbContext = JAXBContext + .newInstance(ProtectionKeyRestType.class); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + + try { + unmarshaller = jaxbContext.createUnmarshaller(); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.media.entityoperations. + * DefaultActionOperation + * #processResponse(com.sun.jersey.api.client.ClientResponse) + */ + @Override + public String processTypeResponse(ClientResponse clientResponse) { + PipelineHelpers.throwIfNotSuccess(clientResponse); + ProtectionKeyRestType protectionKeyRestType; + try { + protectionKeyRestType = parseResponse(clientResponse); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + + return protectionKeyRestType.getProtectionKey(); + } + + /** + * Parses the response. + * + * @param clientResponse + * the client response + * @return the protection key rest type + * @throws JAXBException + * the jAXB exception + */ + private ProtectionKeyRestType parseResponse( + ClientResponse clientResponse) throws JAXBException { + InputStream inputStream = clientResponse.getEntityInputStream(); + JAXBElement protectionKeyTypeJaxbElement = unmarshaller + .unmarshal(new StreamSource(inputStream), + ProtectionKeyRestType.class); + return protectionKeyTypeJaxbElement.getValue(); + + } + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyType.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyType.java similarity index 90% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyType.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyType.java index 64db9a5327976..3c3f893fe9936 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyType.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyType.java @@ -56,10 +56,10 @@ public int getCode() { */ public static ProtectionKeyType fromCode(int protectionKeyTypeCode) { switch (protectionKeyTypeCode) { - case 0: - return ProtectionKeyType.X509CertificateThumbprint; - default: - throw new InvalidParameterException("state"); + case 0: + return ProtectionKeyType.X509CertificateThumbprint; + default: + throw new InvalidParameterException("state"); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TargetJobState.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TargetJobState.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TargetJobState.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/TargetJobState.java index edfc3099d43f4..d7b87705c1194 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TargetJobState.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TargetJobState.java @@ -61,14 +61,14 @@ public int getCode() { */ public static TargetJobState fromCode(int targetJobStateCode) { switch (targetJobStateCode) { - case 0: - return TargetJobState.None; - case 1: - return TargetJobState.FinalStatesOnly; - case 2: - return TargetJobState.All; - default: - throw new InvalidParameterException("targetJobStateCode"); + case 0: + return TargetJobState.None; + case 1: + return TargetJobState.FinalStatesOnly; + case 2: + return TargetJobState.All; + default: + throw new InvalidParameterException("targetJobStateCode"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Task.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Task.java similarity index 91% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Task.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/Task.java index 707970b7b7e83..bdb8d2d377ead 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/Task.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/Task.java @@ -24,7 +24,7 @@ * Class for creating operations to manipulate Task entities. * */ -public class Task { +public final class Task { /** The Constant ENTITY_SET. */ private static final String ENTITY_SET = "Tasks"; @@ -45,7 +45,8 @@ private Task() { * the task body * @return the creates the batch operation */ - public static CreateBatchOperation create(String mediaProcessorId, String taskBody) { + public static CreateBatchOperation create(String mediaProcessorId, + String taskBody) { return new CreateBatchOperation(mediaProcessorId, taskBody); } @@ -55,20 +56,23 @@ public static CreateBatchOperation create(String mediaProcessorId, String taskBo * @return The list operation */ public static DefaultListOperation list() { - return new DefaultListOperation(ENTITY_SET, new GenericType>() { - }); + return new DefaultListOperation(ENTITY_SET, + new GenericType>() { + }); } /** - * Create an operation that will list the tasks pointed to by the given link. + * Create an operation that will list the tasks pointed to by the given + * link. * * @param link * link to tasks * @return the list operation. */ public static DefaultListOperation list(LinkInfo link) { - return new DefaultListOperation(link.getHref(), new GenericType>() { - }); + return new DefaultListOperation(link.getHref(), + new GenericType>() { + }); } /** @@ -88,7 +92,7 @@ public static class CreateBatchOperation extends EntityBatchOperation { * the task body */ public CreateBatchOperation(String mediaProcessorId, String taskBody) { - this.verb = "POST"; + this.setVerb("POST"); taskType = new TaskType(); addContentObject(taskType); this.taskType.setMediaProcessorId(mediaProcessorId); @@ -198,7 +202,8 @@ public CreateBatchOperation setEncryptionScheme(String encryptionScheme) { * the encryption version * @return the creates the batch operation */ - public CreateBatchOperation setEncryptionVersion(String encryptionVersion) { + public CreateBatchOperation setEncryptionVersion( + String encryptionVersion) { this.taskType.setEncryptionVersion(encryptionVersion); return this; } @@ -210,7 +215,8 @@ public CreateBatchOperation setEncryptionVersion(String encryptionVersion) { * the initialization vector * @return the creates the batch operation */ - public CreateBatchOperation setInitializationVector(String initializationVector) { + public CreateBatchOperation setInitializationVector( + String initializationVector) { this.taskType.setInitializationVector(initializationVector); return this; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskHistoricalEvent.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskHistoricalEvent.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskHistoricalEvent.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskHistoricalEvent.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskInfo.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskInfo.java similarity index 94% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskInfo.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskInfo.java index 6f22c00bb7697..3dc4636e0654c 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskInfo.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskInfo.java @@ -79,7 +79,8 @@ public List getErrorDetails() { List errorDetailTypes = getContent().getErrorDetails(); if (errorDetailTypes != null) { for (ErrorDetailType errorDetailType : errorDetailTypes) { - ErrorDetail errorDetail = new ErrorDetail(errorDetailType.getCode(), errorDetailType.getMessage()); + ErrorDetail errorDetail = new ErrorDetail( + errorDetailType.getCode(), errorDetailType.getMessage()); result.add(errorDetail); } return result; @@ -94,7 +95,8 @@ public List getErrorDetails() { */ public List getHistoricalEvents() { List result = new ArrayList(); - List historicalEventTypes = getContent().getHistoricalEventTypes(); + List historicalEventTypes = getContent() + .getHistoricalEventTypes(); if (historicalEventTypes != null) { for (TaskHistoricalEventType taskHistoricalEventType : historicalEventTypes) { @@ -102,8 +104,9 @@ public List getHistoricalEvents() { if ((message != null) && (message.isEmpty())) { message = null; } - TaskHistoricalEvent taskHistoricalEvent = new TaskHistoricalEvent(taskHistoricalEventType.getCode(), - message, taskHistoricalEventType.getTimeStamp()); + TaskHistoricalEvent taskHistoricalEvent = new TaskHistoricalEvent( + taskHistoricalEventType.getCode(), message, + taskHistoricalEventType.getTimeStamp()); result.add(taskHistoricalEvent); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskOption.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskOption.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskOption.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskOption.java index cb3dd9ba79420..252b30e04e968 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskOption.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskOption.java @@ -57,13 +57,13 @@ public int getCode() { */ public static TaskOption fromCode(int code) { switch (code) { - case 0: - return None; - case 1: - return ProtectedConfiguration; + case 0: + return None; + case 1: + return ProtectedConfiguration; - default: - throw new InvalidParameterException("code"); + default: + throw new InvalidParameterException("code"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskState.java b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskState.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskState.java rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskState.java index 3793e2e606d67..67651ad9f9301 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/TaskState.java +++ b/media/src/main/java/com/microsoft/windowsazure/services/media/models/TaskState.java @@ -74,22 +74,22 @@ public int getCode() { */ public static TaskState fromCode(int code) { switch (code) { - case 0: - return None; - case 1: - return Active; - case 2: - return Running; - case 3: - return Completed; - case 4: - return Error; - case 5: - return Canceled; - case 6: - return Canceling; - default: - throw new InvalidParameterException("code"); + case 0: + return None; + case 1: + return Active; + case 2: + return Running; + case 3: + return Completed; + case 4: + return Error; + case 5: + return Canceled; + case 6: + return Canceling; + default: + throw new InvalidParameterException("code"); } } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/package.html b/media/src/main/java/com/microsoft/windowsazure/services/media/models/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/media/models/package.html diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/package.html b/media/src/main/java/com/microsoft/windowsazure/services/media/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/media/package.html diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/Exports.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/Exports.java new file mode 100644 index 0000000000000..b16c687758834 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/Exports.java @@ -0,0 +1,34 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.services.queue.implementation.QueueExceptionProcessor; +import com.microsoft.windowsazure.services.queue.implementation.QueueRestProxy; +import com.microsoft.windowsazure.services.queue.implementation.SharedKeyFilter; +import com.microsoft.windowsazure.services.queue.implementation.SharedKeyLiteFilter; + +public class Exports implements Builder.Exports { + @Override + public void register(Builder.Registry registry) { + registry.add(QueueContract.class, QueueExceptionProcessor.class); + registry.add(QueueExceptionProcessor.class); + registry.add(QueueRestProxy.class); + registry.add(SharedKeyLiteFilter.class); + registry.add(SharedKeyFilter.class); + registry.add(UserAgentFilter.class); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueConfiguration.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueConfiguration.java new file mode 100644 index 0000000000000..a8e30604a8b05 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueConfiguration.java @@ -0,0 +1,27 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue; + +/** + * A class that contains static strings used to identify parts of a service + * configuration instance associated with the Windows Azure Queue service. + *

+ * These values must not be altered. + */ +public abstract class QueueConfiguration { + public static final String ACCOUNT_NAME = "queue.accountName"; + public static final String ACCOUNT_KEY = "queue.accountKey"; + public static final String URI = "queue.uri"; +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueContract.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueContract.java new file mode 100644 index 0000000000000..4eede912e5a52 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueContract.java @@ -0,0 +1,516 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue; + +import java.util.HashMap; + +import com.microsoft.windowsazure.core.pipeline.jersey.JerseyFilterableService; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.queue.models.CreateMessageOptions; +import com.microsoft.windowsazure.services.queue.models.CreateQueueOptions; +import com.microsoft.windowsazure.services.queue.models.GetQueueMetadataResult; +import com.microsoft.windowsazure.services.queue.models.GetServicePropertiesResult; +import com.microsoft.windowsazure.services.queue.models.ListMessagesOptions; +import com.microsoft.windowsazure.services.queue.models.ListMessagesResult; +import com.microsoft.windowsazure.services.queue.models.ListQueuesOptions; +import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; +import com.microsoft.windowsazure.services.queue.models.PeekMessagesOptions; +import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult; +import com.microsoft.windowsazure.services.queue.models.QueueServiceOptions; +import com.microsoft.windowsazure.services.queue.models.ServiceProperties; +import com.microsoft.windowsazure.services.queue.models.UpdateMessageResult; + +/** + * Defines the methods available on the Windows Azure storage queue service. + * Construct an object instance implementing QueueContract with + * one of the static create methods on {@link QueueService}. These + * methods associate a {@link Configuration} with the implementation, so the + * methods on the instance of QueueContract all work with a + * particular storage account. + */ +public interface QueueContract extends JerseyFilterableService { + /** + * Gets the service properties of the queue. + * + * @return A {@link GetServicePropertiesResult} reference to the queue + * service properties. + * + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + GetServicePropertiesResult getServiceProperties() throws ServiceException; + + /** + * Gets the service properties of the queue, using the specified options. + * Use the {@link QueueServiceOptions options} parameter to specify the + * server timeout for the operation. + * + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @return A {@link GetServicePropertiesResult} reference to the queue + * service properties. + * + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + GetServicePropertiesResult getServiceProperties(QueueServiceOptions options) + throws ServiceException; + + /** + * Sets the service properties of the queue. + * + * @param serviceProperties + * A {@link ServiceProperties} instance containing the queue + * service properties to set. + * + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void setServiceProperties(ServiceProperties serviceProperties) + throws ServiceException; + + /** + * Sets the service properties of the queue, using the specified options. + * Use the {@link QueueServiceOptions options} parameter to specify the + * server timeout for the operation. + * + * @param serviceProperties + * A {@link ServiceProperties} instance containing the queue + * service properties to set. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs accessing the storage service. + */ + void setServiceProperties(ServiceProperties serviceProperties, + QueueServiceOptions options) throws ServiceException; + + /** + * Creates a queue in the storage account with the specified queue name. + * + * @param queue + * A {@link String} containing the name of the queue to create. + * + * @throws ServiceException + * if an error occurs in the storage service. + */ + void createQueue(String queue) throws ServiceException; + + /** + * Creates a queue in the storage account with the specified queue name, + * using the specified options. Use the {@link QueueServiceOptions options} + * parameter to specify the server timeout for the operation. + * + * @param queue + * A {@link String} containing the name of the queue to create. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void createQueue(String queue, CreateQueueOptions options) + throws ServiceException; + + /** + * Deletes the queue in the storage account with the specified queue name. + * + * @param queue + * A {@link String} containing the name of the queue to delete. + * + * @throws ServiceException + * if an error occurs in the storage service. + */ + void deleteQueue(String queue) throws ServiceException; + + /** + * Deletes the queue in the storage account with the specified queue name, + * using the specified options. Use the {@link QueueServiceOptions options} + * parameter to specify the server timeout for the operation. + * + * @param queue + * A {@link String} containing the name of the queue to delete. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void deleteQueue(String queue, QueueServiceOptions options) + throws ServiceException; + + /** + * Gets a list of the queues in the storage account. + * + * @return A {@link ListQueuesResult} reference to the queues returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + ListQueuesResult listQueues() throws ServiceException; + + /** + * Gets a list of the queues in the storage account, using the specified + * options. Use the {@link ListQueuesOptions options} parameter to specify + * the server timeout for the operation, the prefix for queue names to + * match, the marker for the beginning of the queues to list, the maximum + * number of results to return, and whether to include queue metadata with + * the results. + * + * @param options + * A {@link ListQueuesOptions} instance containing options for + * the request. + * @return A {@link ListQueuesResult} reference to the queues returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + ListQueuesResult listQueues(ListQueuesOptions options) + throws ServiceException; + + /** + * Gets the metadata for the named queue in the storage account. Queue + * metadata is a user-defined collection of key-value {@link String} pairs + * that is opaque to the server. + * + * @param queue + * A {@link String} containing the name of the queue to get the + * metadata for. + * @return A {@link GetQueueMetadataResult} reference to the metadata for + * the queue. + * @throws ServiceException + * if an error occurs in the storage service. + */ + GetQueueMetadataResult getQueueMetadata(String queue) + throws ServiceException; + + /** + * Gets the metadata for the named queue in the storage account, using the + * specified options. Use the {@link QueueServiceOptions options} parameter + * to specify the server timeout for the operation. Queue metadata is a + * user-defined collection of key-value {@link String} pairs that is opaque + * to the server. + * + * @param queue + * A {@link String} containing the name of the queue to get the + * metadata for. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @return A {@link ListQueuesResult} reference to the queues returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + GetQueueMetadataResult getQueueMetadata(String queue, + QueueServiceOptions options) throws ServiceException; + + /** + * Sets the specified metadata on the named queue in the storage account. + * Queue metadata is a user-defined collection of key-value {@link String} + * pairs that is opaque to the server. + * + * @param queue + * A {@link String} containing the name of the queue to set the + * metadata on. + * @param metadata + * A {@link java.util.HashMap} of metadata key-value + * {@link String} pairs to set on the queue. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void setQueueMetadata(String queue, HashMap metadata) + throws ServiceException; + + /** + * Sets the specified metadata on the named queue in the storage account, + * using the specified options. Use the {@link QueueServiceOptions options} + * parameter to specify the server timeout for the operation. Queue metadata + * is a user-defined collection of key-value {@link String} pairs that is + * opaque to the server. + * + * @param queue + * A {@link String} containing the name of the queue to set the + * metadata on. + * @param metadata + * A {@link java.util.HashMap} of metadata key-value + * {@link String} pairs to set on the queue. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void setQueueMetadata(String queue, HashMap metadata, + QueueServiceOptions options) throws ServiceException; + + /** + * Appends a message with the specified text to the tail of the named queue + * in the storage account. + * + * @param queue + * A {@link String} containing the name of the queue to append + * the message to. + * @param messageText + * A {@link String} containing the text of the message to append + * to the queue. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void createMessage(String queue, String messageText) + throws ServiceException; + + /** + * Appends a message with the specified text to the tail of the named queue + * in the storage account, using the specified options. Use the + * {@link CreateMessageOptions options} parameter to specify the server + * timeout for the operation, the message visibility timeout, and the + * message time to live in the queue. + * + * @param queue + * A {@link String} containing the name of the queue to append + * the message to. + * @param messageText + * A {@link String} containing the text of the message to append + * to the queue. + * @param options + * A {@link CreateMessageOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void createMessage(String queue, String messageText, + CreateMessageOptions options) throws ServiceException; + + /** + * Updates the message in the named queue with the specified message ID and + * pop receipt value to have the specified message text and visibility + * timeout value. + * + * @param queue + * A {@link String} containing the name of the queue with the + * message to update. + * @param messageId + * A {@link String} containing the ID of the message to update. + * @param popReceipt + * A {@link String} containing the pop receipt for the message + * returned by a call to updateMessage or listMessages. + * @param messageText + * A {@link String} containing the updated text to set for the + * message. + * @param visibilityTimeoutInSeconds + * The new visibility timeout to set on the message, in seconds. + * @return An {@link UpdateMessageResult} reference to the updated message + * result returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + UpdateMessageResult updateMessage(String queue, String messageId, + String popReceipt, String messageText, + int visibilityTimeoutInSeconds) throws ServiceException; + + /** + * Updates the message in the named queue with the specified message ID and + * pop receipt value to have the specified message text and visibility + * timeout value, using the specified options. Use the + * {@link QueueServiceOptions options} parameter to specify the server + * timeout for the operation. + * + * @param queue + * A {@link String} containing the name of the queue with the + * message to update. + * @param messageId + * A {@link String} containing the ID of the message to update. + * @param popReceipt + * A {@link String} containing the pop receipt for the message + * returned by a call to updateMessage or listMessages. + * @param messageText + * A {@link String} containing the updated text to set for the + * message. + * @param visibilityTimeoutInSeconds + * The new visibility timeout to set on the message, in seconds. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @return An {@link UpdateMessageResult} reference to the updated message + * result returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + UpdateMessageResult updateMessage(String queue, String messageId, + String popReceipt, String messageText, + int visibilityTimeoutInSeconds, QueueServiceOptions options) + throws ServiceException; + + /** + * Deletes the message in the named queue with the specified message ID and + * pop receipt value. + * + * @param queue + * A {@link String} containing the name of the queue with the + * message to delete. + * @param messageId + * A {@link String} containing the ID of the message to delete. + * @param popReceipt + * A {@link String} containing the pop receipt for the message + * returned by a call to updateMessage or listMessages. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void deleteMessage(String queue, String messageId, String popReceipt) + throws ServiceException; + + /** + * Deletes the message in the named queue with the specified message ID and + * popReceipt value, using the specified options. Use the + * {@link QueueServiceOptions options} parameter to specify the server + * timeout for the operation. + * + * @param queue + * A {@link String} containing the name of the queue with the + * message to delete. + * @param messageId + * A {@link String} containing the ID of the message to delete. + * @param popReceipt + * A {@link String} containing the pop receipt for the message + * returned by a call to updateMessage or listMessages. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void deleteMessage(String queue, String messageId, String popReceipt, + QueueServiceOptions options) throws ServiceException; + + /** + * Retrieves the first message from head of the named queue in the storage + * account. This marks the message as invisible for the default visibility + * timeout period. When message processing is complete, the message must be + * deleted with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract#deleteMessage(String, String, String, QueueServiceOptions) + * deleteMessage}. If message processing will take longer than the + * visibility timeout period, use the + * {@link com.microsoft.windowsazure.services.queue.QueueContract#updateMessage(String, String, String, String, int, QueueServiceOptions) + * updateMessage} method to extend the visibility timeout. The message will + * become visible in the queue again when the timeout completes if it is not + * deleted. + *

+ * To get a list of multiple messages from the head of the queue, call the + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listMessages(String, ListMessagesOptions)} method + * with options set specifying the number of messages to return. + * + * @param queue + * A {@link String} containing the name of the queue to get the + * message from. + * @return A {@link ListMessagesResult} reference to the message result + * returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + ListMessagesResult listMessages(String queue) throws ServiceException; + + /** + * Retrieves up to 32 messages from the head of the named queue in the + * storage account, using the specified options. Use the + * {@link ListMessagesOptions options} parameter to specify the server + * timeout for the operation, the number of messages to retrieve, and the + * visibility timeout to set on the retrieved messages. When message + * processing is complete, each message must be deleted with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract#deleteMessage(String, String, String, QueueServiceOptions) + * deleteMessage}. If message processing takes longer than the default + * timeout period, use the + * {@link com.microsoft.windowsazure.services.queue.QueueContract#updateMessage(String, String, String, String, int, QueueServiceOptions) + * updateMessage} method to extend the visibility timeout. Each message will + * become visible in the queue again when the timeout completes if it is not + * deleted. + * + * @param queue + * A {@link String} containing the name of the queue to get the + * messages from. + * @param options + * A {@link ListMessagesOptions} instance containing options for + * the request. + * @return A {@link ListMessagesResult} reference to the message result + * returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + ListMessagesResult listMessages(String queue, ListMessagesOptions options) + throws ServiceException; + + /** + * Peeks a message from the named queue. A peek request retrieves a message + * from the head of the queue without changing its visibility. + * + * @param queue + * A {@link String} containing the name of the queue to peek the + * message from. + * @return A {@link PeekMessagesResult} reference to the message result + * returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + PeekMessagesResult peekMessages(String queue) throws ServiceException; + + /** + * Peeks messages from the named queue, using the specified options. A peek + * request retrieves messages from the head of the queue without changing + * their visibility. Use the {@link PeekMessagesOptions options} parameter + * to specify the server timeout for the operation and the number of + * messages to retrieve. + * + * @param queue + * A {@link String} containing the name of the queue to peek the + * message from. + * @param options + * A {@link PeekMessagesOptions} instance containing options for + * the request. + * @return A {@link PeekMessagesResult} reference to the message result + * returned. + * @throws ServiceException + * if an error occurs in the storage service. + */ + PeekMessagesResult peekMessages(String queue, PeekMessagesOptions options) + throws ServiceException; + + /** + * Deletes all messages in the named queue. + * + * @param queue + * A {@link String} containing the name of the queue to delete + * all messages from. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void clearMessages(String queue) throws ServiceException; + + /** + * Deletes all messages in the named queue, using the specified options. Use + * the {@link QueueServiceOptions options} parameter to specify the server + * timeout for the operation. + * + * @param queue + * A {@link String} containing the name of the queue to delete + * all messages from. + * @param options + * A {@link QueueServiceOptions} instance containing options for + * the request. + * @throws ServiceException + * if an error occurs in the storage service. + */ + void clearMessages(String queue, QueueServiceOptions options) + throws ServiceException; + +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java new file mode 100644 index 0000000000000..babf9cadc88b4 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java @@ -0,0 +1,102 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue; + +import com.microsoft.windowsazure.Configuration; + +/** + * A class for static factory methods that return instances implementing + * {@link com.microsoft.windowsazure.services.queue.QueueContract}. + */ +public final class QueueService { + /** + * Private default constructor. + */ + private QueueService() { + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.queue.QueueContract} using default values for initializing a + * {@link Configuration} instance. Note that the returned interface will not + * work unless storage account credentials have been added to the + * "META-INF/com.microsoft.windowsazure.properties" resource file. + * + * @return An instance implementing {@link com.microsoft.windowsazure.services.queue.QueueContract} for interacting + * with the queue service. + */ + public static QueueContract create() { + return create(null, Configuration.getInstance()); + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.queue.QueueContract} using the specified {@link Configuration} instance. + * The {@link Configuration} instance must have storage account information + * and credentials set before this method is called for the returned + * interface to work. + * + * @param config + * A {@link Configuration} instance configured with storage + * account information and credentials. + * + * @return An instance implementing {@link com.microsoft.windowsazure.services.queue.QueueContract} for interacting + * with the queue service. + */ + public static QueueContract create(Configuration config) { + return create(null, config); + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.queue.QueueContract} using default values for initializing a + * {@link Configuration} instance, and using the specified profile prefix + * for service settings. Note that the returned interface will not work + * unless storage account settings and credentials have been added to the + * "META-INF/com.microsoft.windowsazure.properties" resource file with the + * specified profile prefix. + * + * @param profile + * A string prefix for the account name and credentials settings + * in the {@link Configuration} instance. + * @return An instance implementing {@link com.microsoft.windowsazure.services.queue.QueueContract} for interacting + * with the queue service. + */ + public static QueueContract create(String profile) { + return create(profile, Configuration.getInstance()); + } + + /** + * A static factory method that returns an instance implementing + * {@link com.microsoft.windowsazure.services.queue.QueueContract} using the specified {@link Configuration} instance + * and profile prefix for service settings. The {@link Configuration} + * instance must have storage account information and credentials set with + * the specified profile prefix before this method is called for the + * returned interface to work. + * + * @param profile + * A string prefix for the account name and credentials settings + * in the {@link Configuration} instance. + * @param config + * A {@link Configuration} instance configured with storage + * account information and credentials. + * + * @return An instance implementing {@link com.microsoft.windowsazure.services.queue.QueueContract} for interacting + * with the queue service. + */ + public static QueueContract create(String profile, Configuration config) { + return config.create(profile, QueueContract.class); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueExceptionProcessor.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueExceptionProcessor.java new file mode 100644 index 0000000000000..78906ff62b671 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueExceptionProcessor.java @@ -0,0 +1,412 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.implementation; + +import java.util.HashMap; + +import javax.inject.Inject; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import com.microsoft.windowsazure.services.queue.QueueContract; +import com.microsoft.windowsazure.services.queue.models.CreateMessageOptions; +import com.microsoft.windowsazure.services.queue.models.CreateQueueOptions; +import com.microsoft.windowsazure.services.queue.models.GetQueueMetadataResult; +import com.microsoft.windowsazure.services.queue.models.GetServicePropertiesResult; +import com.microsoft.windowsazure.services.queue.models.ListMessagesOptions; +import com.microsoft.windowsazure.services.queue.models.ListMessagesResult; +import com.microsoft.windowsazure.services.queue.models.ListQueuesOptions; +import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; +import com.microsoft.windowsazure.services.queue.models.PeekMessagesOptions; +import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult; +import com.microsoft.windowsazure.services.queue.models.QueueServiceOptions; +import com.microsoft.windowsazure.services.queue.models.ServiceProperties; +import com.microsoft.windowsazure.services.queue.models.UpdateMessageResult; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class QueueExceptionProcessor implements QueueContract { + private static Log log = LogFactory.getLog(QueueExceptionProcessor.class); + private final QueueContract service; + + @Inject + public QueueExceptionProcessor(QueueRestProxy service) { + this.service = service; + } + + public QueueExceptionProcessor(QueueContract service) { + this.service = service; + } + + public QueueContract withFilter(ServiceFilter filter) { + return new QueueExceptionProcessor(service.withFilter(filter)); + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withRequestFilterFirst + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public QueueContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + return new QueueExceptionProcessor( + service.withRequestFilterFirst(serviceRequestFilter)); + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withRequestFilterLast + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public QueueContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + return new QueueExceptionProcessor( + service.withRequestFilterLast(serviceRequestFilter)); + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withResponseFilterFirst + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public QueueContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + return new QueueExceptionProcessor( + service.withResponseFilterFirst(serviceResponseFilter)); + } + + /* + * (non-Javadoc) + * + * @see com.microsoft.windowsazure.services.core.FilterableService# + * withResponseFilterLast + * (com.microsoft.windowsazure.services.core.ServiceFilter) + */ + @Override + public QueueContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + return new QueueExceptionProcessor( + service.withResponseFilterLast(serviceResponseFilter)); + } + + private ServiceException processCatch(ServiceException e) { + log.warn(e.getMessage(), e.getCause()); + return ServiceExceptionFactory.process("queue", e); + } + + public GetServicePropertiesResult getServiceProperties() + throws ServiceException { + try { + return service.getServiceProperties(); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public GetServicePropertiesResult getServiceProperties( + QueueServiceOptions options) throws ServiceException { + try { + return service.getServiceProperties(options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void setServiceProperties(ServiceProperties serviceProperties) + throws ServiceException { + try { + service.setServiceProperties(serviceProperties); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void setServiceProperties(ServiceProperties serviceProperties, + QueueServiceOptions options) throws ServiceException { + try { + service.setServiceProperties(serviceProperties, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void createQueue(String queue) throws ServiceException { + try { + service.createQueue(queue); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void createQueue(String queue, CreateQueueOptions options) + throws ServiceException { + try { + service.createQueue(queue, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void deleteQueue(String queue) throws ServiceException { + try { + service.deleteQueue(queue); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void deleteQueue(String queue, QueueServiceOptions options) + throws ServiceException { + try { + service.deleteQueue(queue, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public ListQueuesResult listQueues() throws ServiceException { + try { + return service.listQueues(); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public ListQueuesResult listQueues(ListQueuesOptions options) + throws ServiceException { + try { + return service.listQueues(options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public GetQueueMetadataResult getQueueMetadata(String queue) + throws ServiceException { + try { + return service.getQueueMetadata(queue); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public GetQueueMetadataResult getQueueMetadata(String queue, + QueueServiceOptions options) throws ServiceException { + try { + return service.getQueueMetadata(queue, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void setQueueMetadata(String queue, HashMap metadata) + throws ServiceException { + try { + service.setQueueMetadata(queue, metadata); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void setQueueMetadata(String queue, + HashMap metadata, QueueServiceOptions options) + throws ServiceException { + try { + service.setQueueMetadata(queue, metadata, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void createMessage(String queue, String messageText) + throws ServiceException { + try { + service.createMessage(queue, messageText); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void createMessage(String queue, String messageText, + CreateMessageOptions options) throws ServiceException { + try { + service.createMessage(queue, messageText, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public UpdateMessageResult updateMessage(String queue, String messageId, + String popReceipt, String messageText, + int visibilityTimeoutInSeconds) throws ServiceException { + try { + return service.updateMessage(queue, messageId, popReceipt, + messageText, visibilityTimeoutInSeconds); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public UpdateMessageResult updateMessage(String queue, String messageId, + String popReceipt, String messageText, + int visibilityTimeoutInSeconds, QueueServiceOptions options) + throws ServiceException { + try { + return service.updateMessage(queue, messageId, popReceipt, + messageText, visibilityTimeoutInSeconds, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public ListMessagesResult listMessages(String queue) + throws ServiceException { + try { + return service.listMessages(queue); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public ListMessagesResult listMessages(String queue, + ListMessagesOptions options) throws ServiceException { + try { + return service.listMessages(queue, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public PeekMessagesResult peekMessages(String queue) + throws ServiceException { + try { + return service.peekMessages(queue); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public PeekMessagesResult peekMessages(String queue, + PeekMessagesOptions options) throws ServiceException { + try { + return service.peekMessages(queue, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void deleteMessage(String queue, String messageId, String popReceipt) + throws ServiceException { + try { + service.deleteMessage(queue, messageId, popReceipt); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void deleteMessage(String queue, String messageId, + String popReceipt, QueueServiceOptions options) + throws ServiceException { + try { + service.deleteMessage(queue, messageId, popReceipt, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void clearMessages(String queue) throws ServiceException { + try { + service.clearMessages(queue); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + public void clearMessages(String queue, QueueServiceOptions options) + throws ServiceException { + try { + service.clearMessages(queue, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueMessage.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueMessage.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueMessage.java rename to media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueMessage.java diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueRestProxy.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueRestProxy.java new file mode 100644 index 0000000000000..97da2aa565015 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueRestProxy.java @@ -0,0 +1,519 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.implementation; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Named; + +import com.microsoft.windowsazure.core.RFC1123DateConverter; +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.core.pipeline.PipelineHelpers; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterRequestAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterResponseAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.HttpURLConnectionClient; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.queue.QueueConfiguration; +import com.microsoft.windowsazure.services.queue.QueueContract; +import com.microsoft.windowsazure.services.queue.models.CreateMessageOptions; +import com.microsoft.windowsazure.services.queue.models.CreateQueueOptions; +import com.microsoft.windowsazure.services.queue.models.GetQueueMetadataResult; +import com.microsoft.windowsazure.services.queue.models.GetServicePropertiesResult; +import com.microsoft.windowsazure.services.queue.models.ListMessagesOptions; +import com.microsoft.windowsazure.services.queue.models.ListMessagesResult; +import com.microsoft.windowsazure.services.queue.models.ListQueuesOptions; +import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; +import com.microsoft.windowsazure.services.queue.models.PeekMessagesOptions; +import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult; +import com.microsoft.windowsazure.services.queue.models.QueueServiceOptions; +import com.microsoft.windowsazure.services.queue.models.ServiceProperties; +import com.microsoft.windowsazure.services.queue.models.UpdateMessageResult; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class QueueRestProxy implements QueueContract { + // private static Log log = LogFactory.getLog(QueueRestProxy.class); + + private static final String API_VERSION = "2011-08-18"; + private final HttpURLConnectionClient channel; + private final String accountName; + private final String url; + private final RFC1123DateConverter dateMapper; + private final ClientFilter[] filters; + private final SharedKeyFilter sharedKeyFilter; + + @Inject + public QueueRestProxy(HttpURLConnectionClient channel, + @Named(QueueConfiguration.ACCOUNT_NAME) String accountName, + @Named(QueueConfiguration.URI) String url, + SharedKeyFilter sharedKeyFilter, UserAgentFilter userAgentFilter) { + + this.channel = channel; + this.accountName = accountName; + this.url = url; + this.sharedKeyFilter = sharedKeyFilter; + this.dateMapper = new RFC1123DateConverter(); + this.filters = new ClientFilter[0]; + channel.addFilter(sharedKeyFilter); + channel.addFilter(new ClientFilterRequestAdapter(userAgentFilter)); + } + + public QueueRestProxy(HttpURLConnectionClient channel, + ClientFilter[] filters, String accountName, String url, + SharedKeyFilter filter, RFC1123DateConverter dateMapper) { + + this.channel = channel; + this.filters = filters; + this.accountName = accountName; + this.url = url; + this.sharedKeyFilter = filter; + this.dateMapper = dateMapper; + } + + @Override + public QueueContract withFilter(ServiceFilter filter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterAdapter(filter); + return new QueueRestProxy(this.channel, newFilters, this.accountName, + this.url, this.sharedKeyFilter, this.dateMapper); + } + + @Override + public QueueContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterRequestAdapter(serviceRequestFilter); + return new QueueRestProxy(this.channel, newFilters, this.accountName, + this.url, this.sharedKeyFilter, this.dateMapper); + } + + @Override + public QueueContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterRequestAdapter( + serviceRequestFilter); + return new QueueRestProxy(this.channel, newFilters, this.accountName, + this.url, this.sharedKeyFilter, this.dateMapper); + } + + @Override + public QueueContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterResponseAdapter(serviceResponseFilter); + return new QueueRestProxy(this.channel, newFilters, this.accountName, + this.url, this.sharedKeyFilter, this.dateMapper); + } + + @Override + public QueueContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterResponseAdapter( + serviceResponseFilter); + return new QueueRestProxy(this.channel, newFilters, this.accountName, + this.url, this.sharedKeyFilter, this.dateMapper); + } + + private void throwIfError(ClientResponse r) { + PipelineHelpers.throwIfError(r); + } + + private WebResource addOptionalQueryParam(WebResource webResource, + String key, Object value) { + return PipelineHelpers.addOptionalQueryParam(webResource, key, value); + } + + private WebResource addOptionalQueryParam(WebResource webResource, + String key, int value, int defaultValue) { + return PipelineHelpers.addOptionalQueryParam(webResource, key, value, + defaultValue); + } + + private Builder addOptionalMetadataHeader(Builder builder, + Map metadata) { + return PipelineHelpers.addOptionalMetadataHeader(builder, metadata); + } + + private HashMap getMetadataFromHeaders( + ClientResponse response) { + return PipelineHelpers.getMetadataFromHeaders(response); + } + + private WebResource getResource(QueueServiceOptions options) { + WebResource webResource = channel.resource(url).path("/"); + webResource = addOptionalQueryParam(webResource, "timeout", + options.getTimeout()); + for (ClientFilter filter : filters) { + webResource.addFilter(filter); + } + + return webResource; + } + + @Override + public GetServicePropertiesResult getServiceProperties() + throws ServiceException { + return getServiceProperties(new QueueServiceOptions()); + } + + @Override + public GetServicePropertiesResult getServiceProperties( + QueueServiceOptions options) throws ServiceException { + WebResource webResource = getResource(options).path("/") + .queryParam("resType", "service") + .queryParam("comp", "properties"); + + WebResource.Builder builder = webResource.header("x-ms-version", + API_VERSION); + + GetServicePropertiesResult result = new GetServicePropertiesResult(); + result.setValue(builder.get(ServiceProperties.class)); + return result; + } + + @Override + public void setServiceProperties(ServiceProperties serviceProperties) + throws ServiceException { + setServiceProperties(serviceProperties, new QueueServiceOptions()); + } + + @Override + public void setServiceProperties(ServiceProperties serviceProperties, + QueueServiceOptions options) throws ServiceException { + WebResource webResource = getResource(options).path("/") + .queryParam("resType", "service") + .queryParam("comp", "properties"); + + WebResource.Builder builder = webResource.header("x-ms-version", + API_VERSION); + + builder.put(serviceProperties); + } + + @Override + public void createQueue(String queue) throws ServiceException { + createQueue(queue, new CreateQueueOptions()); + + } + + @Override + public void createQueue(String queue, CreateQueueOptions options) + throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue); + + WebResource.Builder builder = webResource.header("x-ms-version", + API_VERSION); + builder = addOptionalMetadataHeader(builder, options.getMetadata()); + + builder.put(); + } + + @Override + public void deleteQueue(String queue) throws ServiceException { + deleteQueue(queue, new QueueServiceOptions()); + } + + @Override + public void deleteQueue(String queue, QueueServiceOptions options) + throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue); + + WebResource.Builder builder = webResource.header("x-ms-version", + API_VERSION); + + builder.delete(); + } + + @Override + public ListQueuesResult listQueues() throws ServiceException { + return listQueues(new ListQueuesOptions()); + } + + @Override + public ListQueuesResult listQueues(ListQueuesOptions options) + throws ServiceException { + WebResource webResource = getResource(options).path("/").queryParam( + "comp", "list"); + webResource = addOptionalQueryParam(webResource, "prefix", + options.getPrefix()); + webResource = addOptionalQueryParam(webResource, "marker", + options.getMarker()); + webResource = addOptionalQueryParam(webResource, "maxresults", + options.getMaxResults(), 0); + if (options.isIncludeMetadata()) { + webResource = webResource.queryParam("include", "metadata"); + } + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + return builder.get(ListQueuesResult.class); + } + + @Override + public GetQueueMetadataResult getQueueMetadata(String queue) + throws ServiceException { + return getQueueMetadata(queue, new QueueServiceOptions()); + } + + @Override + public GetQueueMetadataResult getQueueMetadata(String queue, + QueueServiceOptions options) throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue).queryParam( + "comp", "metadata"); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + ClientResponse response = builder.get(ClientResponse.class); + throwIfError(response); + + GetQueueMetadataResult result = new GetQueueMetadataResult(); + result.setApproximateMessageCount(Integer.parseInt(response + .getHeaders().getFirst("x-ms-approximate-messages-count"))); + result.setMetadata(getMetadataFromHeaders(response)); + + return result; + } + + @Override + public void setQueueMetadata(String queue, HashMap metadata) + throws ServiceException { + setQueueMetadata(queue, metadata, new QueueServiceOptions()); + } + + @Override + public void setQueueMetadata(String queue, + HashMap metadata, QueueServiceOptions options) + throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue).queryParam( + "comp", "metadata"); + + WebResource.Builder builder = webResource.header("x-ms-version", + API_VERSION); + builder = addOptionalMetadataHeader(builder, metadata); + + builder.put(); + } + + @Override + public void createMessage(String queue, String messageText) + throws ServiceException { + createMessage(queue, messageText, new CreateMessageOptions()); + } + + @Override + public void createMessage(String queue, String messageText, + CreateMessageOptions options) throws ServiceException { + if (queue == null) { + throw new NullPointerException("queue"); + } + if (messageText == null) { + throw new NullPointerException("messageText"); + } + + WebResource webResource = getResource(options).path(queue).path( + "messages"); + webResource = addOptionalQueryParam(webResource, "visibilitytimeout", + options.getVisibilityTimeoutInSeconds()); + webResource = addOptionalQueryParam(webResource, "messagettl", + options.getTimeToLiveInSeconds()); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + QueueMessage queueMessage = new QueueMessage(); + queueMessage.setMessageText(messageText); + + builder.post(queueMessage); + } + + @Override + public UpdateMessageResult updateMessage(String queue, String messageId, + String popReceipt, String messageText, + int visibilityTimeoutInSeconds) throws ServiceException { + return updateMessage(queue, messageId, popReceipt, messageText, + visibilityTimeoutInSeconds, new QueueServiceOptions()); + } + + @Override + public UpdateMessageResult updateMessage(String queue, String messageId, + String popReceipt, String messageText, + int visibilityTimeoutInSeconds, QueueServiceOptions options) + throws ServiceException { + if (queue == null) { + throw new NullPointerException("queue"); + } + if (messageId == null) { + throw new NullPointerException("messageId"); + } + if (messageText == null) { + throw new NullPointerException("messageText"); + } + + WebResource webResource = getResource(options).path(queue) + .path("messages").path(messageId); + webResource = addOptionalQueryParam(webResource, "popreceipt", + popReceipt); + webResource = addOptionalQueryParam(webResource, "visibilitytimeout", + visibilityTimeoutInSeconds); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + QueueMessage queueMessage = new QueueMessage(); + queueMessage.setMessageText(messageText); + + ClientResponse response = builder.put(ClientResponse.class, + queueMessage); + throwIfError(response); + + UpdateMessageResult result = new UpdateMessageResult(); + result.setPopReceipt(response.getHeaders().getFirst("x-ms-popreceipt")); + result.setTimeNextVisible(dateMapper.parse(response.getHeaders() + .getFirst("x-ms-time-next-visible"))); + return result; + } + + @Override + public ListMessagesResult listMessages(String queue) + throws ServiceException { + return listMessages(queue, new ListMessagesOptions()); + } + + @Override + public ListMessagesResult listMessages(String queue, + ListMessagesOptions options) throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue).path( + "messages"); + webResource = addOptionalQueryParam(webResource, "visibilitytimeout", + options.getVisibilityTimeoutInSeconds()); + webResource = addOptionalQueryParam(webResource, "numofmessages", + options.getNumberOfMessages()); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + return builder.get(ListMessagesResult.class); + } + + @Override + public PeekMessagesResult peekMessages(String queue) + throws ServiceException { + return peekMessages(queue, new PeekMessagesOptions()); + } + + @Override + public PeekMessagesResult peekMessages(String queue, + PeekMessagesOptions options) throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue) + .path("messages").queryParam("peekonly", "true"); + webResource = addOptionalQueryParam(webResource, "numofmessages", + options.getNumberOfMessages()); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + return builder.get(PeekMessagesResult.class); + } + + @Override + public void deleteMessage(String queue, String messageId, String popReceipt) + throws ServiceException { + deleteMessage(queue, messageId, popReceipt, new QueueServiceOptions()); + } + + @Override + public void deleteMessage(String queue, String messageId, + String popReceipt, QueueServiceOptions options) + throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + if (messageId == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue) + .path("messages").path(messageId); + webResource = addOptionalQueryParam(webResource, "popreceipt", + popReceipt); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + builder.delete(); + } + + @Override + public void clearMessages(String queue) throws ServiceException { + clearMessages(queue, new QueueServiceOptions()); + } + + @Override + public void clearMessages(String queue, QueueServiceOptions options) + throws ServiceException { + if (queue == null) { + throw new NullPointerException(); + } + + WebResource webResource = getResource(options).path(queue).path( + "messages"); + + Builder builder = webResource.header("x-ms-version", API_VERSION); + + builder.delete(); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyFilter.java new file mode 100644 index 0000000000000..b788775c244ff --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyFilter.java @@ -0,0 +1,28 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.implementation; + +import javax.inject.Named; + +import com.microsoft.windowsazure.services.queue.QueueConfiguration; + +public class SharedKeyFilter extends + com.microsoft.windowsazure.services.blob.implementation.SharedKeyFilter { + public SharedKeyFilter( + @Named(QueueConfiguration.ACCOUNT_NAME) String accountName, + @Named(QueueConfiguration.ACCOUNT_KEY) String accountKey) { + super(accountName, accountKey); + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyLiteFilter.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyLiteFilter.java new file mode 100644 index 0000000000000..589dd1c6bc75c --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyLiteFilter.java @@ -0,0 +1,29 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.implementation; + +import javax.inject.Named; + +import com.microsoft.windowsazure.services.queue.QueueConfiguration; + +public class SharedKeyLiteFilter + extends + com.microsoft.windowsazure.services.blob.implementation.SharedKeyLiteFilter { + public SharedKeyLiteFilter( + @Named(QueueConfiguration.ACCOUNT_NAME) String accountName, + @Named(QueueConfiguration.ACCOUNT_KEY) String accountKey) { + super(accountName, accountKey); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/package.html b/media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/queue/implementation/package.html diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateMessageOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateMessageOptions.java new file mode 100644 index 0000000000000..9520eaf05ce98 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateMessageOptions.java @@ -0,0 +1,118 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + + +/** + * Represents the options that may be set on the Queue service for + * {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions) + * createMessage} requests. These options include a server response timeout for + * the request, the visibility timeout to set on the created message, and the + * time-to-live value to set on the message. + */ +public class CreateMessageOptions extends QueueServiceOptions { + private Integer visibilityTimeoutInSeconds; + private Integer timeToLiveInSeconds; + + /** + * Sets the server request timeout value associated with this + * {@link CreateMessageOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CreateMessageOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CreateMessageOptions} instance. + */ + @Override + public CreateMessageOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the message visibility timeout in seconds value in this + * {@link CreateMessageOptions} instance. to set on messages when making a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions) + * createMessage} request. + * + * @return The message visibility timeout in seconds. + */ + public Integer getVisibilityTimeoutInSeconds() { + return visibilityTimeoutInSeconds; + } + + /** + * Sets the message visibility timeout in seconds value to set on messages + * when making a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions) + * createMessage} request. This allows messages to be loaded into the queue + * but not become visible until the visibility timeout has passed. Valid + * visibility timeout values range from 0 to 604800 seconds (0 to 7 days), + * and must be less than the time-to-live value. + *

+ * The visibilityTimeoutInSeconds value only affects calls made on + * methods where this {@link CreateMessageOptions} instance is passed as a + * parameter. + * + * @param visibilityTimeoutInSeconds + * The length of time during which the message will be invisible, + * starting when it is added to the queue, or 0 to make the + * message visible immediately. This value must be greater than + * or equal to zero and less than or equal to the time-to-live + * value. + * @return A reference to this {@link CreateMessageOptions} instance. + */ + public CreateMessageOptions setVisibilityTimeoutInSeconds( + Integer visibilityTimeoutInSeconds) { + this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds; + return this; + } + + /** + * Gets the message time-to-live in seconds value associated with this + * {@link CreateMessageOptions} instance. + * + * @return The message time-to-live value in seconds. + */ + public Integer getTimeToLiveInSeconds() { + return timeToLiveInSeconds; + } + + /** + * Sets the message time-to-live timeout value to set on messages when + * making a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#createMessage(String, String, CreateMessageOptions) + * createMessage} request. This is the maximum duration in seconds for the + * message to remain in the queue after it is created. Valid + * timeToLiveInSeconds values range from 0 to 604800 seconds (0 to + * 7 days), with the default value set to seven days. + *

+ * The timeToLiveInSeconds value only affects calls made on methods + * where this {@link CreateMessageOptions} instance is passed as a + * parameter. + * + * @param timeToLiveInSeconds + * The maximum time to allow the message to be in the queue, in + * seconds. + * @return A reference to this {@link CreateMessageOptions} instance. + */ + public CreateMessageOptions setTimeToLiveInSeconds( + Integer timeToLiveInSeconds) { + this.timeToLiveInSeconds = timeToLiveInSeconds; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateQueueOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateQueueOptions.java new file mode 100644 index 0000000000000..0f31007b37130 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateQueueOptions.java @@ -0,0 +1,96 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + +import java.util.HashMap; + +/** + * Represents the options that may be set on a queue when created in the storage + * service with a {@link com.microsoft.windowsazure.services.queue.QueueContract#createQueue(String, CreateQueueOptions) + * createQueue} request. These options include a server response timeout for the + * request and the metadata to associate with the created queue. + */ +public class CreateQueueOptions extends QueueServiceOptions { + private HashMap metadata = new HashMap(); + + /** + * Sets the server request timeout value associated with this + * {@link CreateQueueOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link CreateQueueOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link CreateQueueOptions} instance. + */ + @Override + public CreateQueueOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the metadata collection of key-value {@link String} pairs to set on + * a queue when the queue is created. + * + * @return A {@link java.util.HashMap} of key-value {@link String} pairs + * containing the metadata to set on the queue. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Sets the metadata collection of key-value {@link String} pairs to set on + * a queue when the queue is created. Queue metadata is a user-defined + * collection of key-value pairs that is opaque to the server. + *

+ * The metadata value is only added to a newly created queue where + * this {@link CreateQueueOptions} instance is passed as a parameter. + * + * @param metadata + * The {@link java.util.HashMap} of key-value {@link String} + * pairs containing the metadata to set on the queue. + * @return A reference to this {@link CreateQueueOptions} instance. + */ + public CreateQueueOptions setMetadata(HashMap metadata) { + this.metadata = metadata; + return this; + } + + /** + * Adds a key-value pair of {@link String} to the metadata collection to set + * on a queue when the queue is created. Queue metadata is a user-defined + * collection of key-value pairs that is opaque to the server. If the key + * already exists in the metadata collection, the value parameter will + * overwrite the existing value paired with that key without notification. + *

+ * The updated metadata is only added to a newly created queue where this + * {@link CreateQueueOptions} instance is passed as a parameter. + * + * @param key + * A {@link String} containing the key part of the key-value pair + * to add to the metadata. + * @param value + * A {@link String} containing the value part of the key-value + * pair to add to the metadata. + * @return A reference to this {@link CreateQueueOptions} instance. + */ + public CreateQueueOptions addMetadata(String key, String value) { + this.metadata.put(key, value); + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/GetQueueMetadataResult.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/GetQueueMetadataResult.java new file mode 100644 index 0000000000000..c8729f40f97d0 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/GetQueueMetadataResult.java @@ -0,0 +1,79 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + +import java.util.HashMap; + +/** + * A wrapper class for the result returned from a Queue Service REST API + * operation to get queue metadata. This is returned by calls to implementations + * of {@link com.microsoft.windowsazure.services.queue.QueueContract#getQueueMetadata(String)} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#getQueueMetadata(String, QueueServiceOptions)}. + *

+ * See the Get + * Queue Metadata documentation on MSDN for details of the underlying Queue + * Service REST API operation. + */ +public class GetQueueMetadataResult { + private long approximateMessageCount; + private HashMap metadata; + + /** + * Gets the queue's approximate message count, as reported by the server. + * + * @return The queue's approximate message count. + */ + public long getApproximateMessageCount() { + return approximateMessageCount; + } + + /** + * Reserved for internal use. This method is invoked by the API as part of + * the response generation from the Queue Service REST API operation to set + * the value for the approximate message count returned by the server. + * + * @param approximateMessageCount + * The queue's approximate message count to set. + */ + public void setApproximateMessageCount(long approximateMessageCount) { + this.approximateMessageCount = approximateMessageCount; + } + + /** + * Gets the metadata collection of key-value {@link String} pairs currently + * set on a queue. Queue metadata is a user-defined collection of key-value + * pairs that is opaque to the server. + * + * @return A {@link java.util.HashMap} of key-value {@link String} pairs + * containing the metadata set on the queue. + */ + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. This method is invoked by the API as part of + * the response generation from the Queue Service REST API operation to set + * the value from the queue metadata returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of key-value {@link String} pairs + * containing the metadata set on the queue. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/GetServicePropertiesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/GetServicePropertiesResult.java new file mode 100644 index 0000000000000..bc2144dfdde9b --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/GetServicePropertiesResult.java @@ -0,0 +1,63 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + + +/** + * A wrapper class for the service properties returned in response to Queue + * Service REST API operations. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.queue.QueueContract#getServiceProperties()} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#getServiceProperties(QueueServiceOptions)}. + *

+ * See the Get + * Queue Service Properties documentation on MSDN for details of the + * underlying Queue Service REST API operation. + */ +public class GetServicePropertiesResult { + private ServiceProperties value; + + /** + * Gets a {@link ServiceProperties} instance containing the service property + * values associated with the storage account. + *

+ * Modifying the values in the {@link ServiceProperties} instance returned + * does not affect the values associated with the storage account. To change + * the values in the storage account, call the + * {@link com.microsoft.windowsazure.services.queue.QueueContract#setServiceProperties} method and pass the modified + * {@link ServiceProperties} instance as a parameter. + * + * @return A {@link ServiceProperties} instance containing the property + * values associated with the storage account. + */ + public ServiceProperties getValue() { + return value; + } + + /** + * Reserved for internal use. Sets the value of the + * {@link ServiceProperties} instance associated with a storage service call + * result. This method is invoked by the API to store service properties + * returned by a call to a REST operation and is not intended for public + * use. + * + * @param value + * A {@link ServiceProperties} instance containing the property + * values associated with the storage account. + */ + public void setValue(ServiceProperties value) { + this.value = value; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesOptions.java new file mode 100644 index 0000000000000..7e6515df37009 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesOptions.java @@ -0,0 +1,101 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listMessages(String, ListMessagesOptions) listMessages} + * request. These options include a server response timeout for the request, the + * number of messages to retrieve from the queue, and the visibility timeout to + * set on the retrieved messages. + */ +public class ListMessagesOptions extends QueueServiceOptions { + private Integer numberOfMessages; + private Integer visibilityTimeoutInSeconds; + + /** + * Sets the server request timeout value associated with this + * {@link ListMessagesOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link ListMessagesOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link ListMessagesOptions} instance. + */ + @Override + public ListMessagesOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the number of messages to request from the queue with this + * {@link ListMessagesOptions} instance. + * + * @return The number of messages requested. + */ + public Integer getNumberOfMessages() { + return numberOfMessages; + } + + /** + * Sets the number of messages to request from the queue with this + * {@link ListMessagesOptions} instance. + *

+ * The numberOfMessages value is only used for requests where this + * {@link ListMessagesOptions} instance is passed as a parameter. + * + * @param numberOfMessages + * The number of messages to request. The valid range of values + * is 0 to 32. + * @return A reference to this {@link ListMessagesOptions} instance. + */ + public ListMessagesOptions setNumberOfMessages(Integer numberOfMessages) { + this.numberOfMessages = numberOfMessages; + return this; + } + + /** + * Gets the visibility timeout to set on the messages requested from the + * queue with this {@link ListMessagesOptions} instance. + * + * @return The visibility timeout to set on the messages requested from the + * queue. + */ + public Integer getVisibilityTimeoutInSeconds() { + return visibilityTimeoutInSeconds; + } + + /** + * Sets the visibility timeout value to set on the messages requested from + * the queue with this {@link ListMessagesOptions} instance. + *

+ * The visibilityTimeoutInSeconds value is only used for requests + * where this {@link ListMessagesOptions} instance is passed as a parameter. + * + * @param visibilityTimeoutInSeconds + * The visibility timeout to set on the messages requested from + * the queue. The valid range of values is 0 to 604800 seconds. + * @return A reference to this {@link ListMessagesOptions} instance. + */ + public ListMessagesOptions setVisibilityTimeoutInSeconds( + Integer visibilityTimeoutInSeconds) { + this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesResult.java new file mode 100644 index 0000000000000..1d2b26f26d1df --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesResult.java @@ -0,0 +1,262 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.core.RFC1123DateAdapter; + +/** + * A wrapper class for the result returned from a Queue Service REST API + * operation to get a list of messages. This is returned by calls to + * implementations of {@link com.microsoft.windowsazure.services.queue.QueueContract#listMessages(String)} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listMessages(String, ListMessagesOptions)}. + *

+ * See the Get + * Messages documentation on MSDN for details of the underlying Queue + * Service REST API operation. + */ +@XmlRootElement(name = "QueueMessagesList") +public class ListMessagesResult { + private List queueMessages = new ArrayList(); + + /** + * Gets the list of queue messages returned by a {@link com.microsoft.windowsazure.services.queue.QueueContract} + * .listMessages request. The queue messages returned have their + * visibility timeout set to allow for processing by the client. The client + * must delete the messages once processing is complete, or they will become + * visible in the queue when the visibility timeout period is over. + * + * @return A {@link List} of {@link QueueMessage} instances representing the + * messages returned by the request. + */ + @XmlElement(name = "QueueMessage") + public List getQueueMessages() { + return queueMessages; + } + + /** + * Reserved for internal use. Sets the list of queue messages returned by a + * {@link com.microsoft.windowsazure.services.queue.QueueContract} .listMessages request. This method is + * invoked by the API as part of the response generation from the Queue + * Service REST API operation to set the value from the queue message list + * returned by the server. + * + * @param queueMessages + * A {@link List} of {@link QueueMessage} instances representing + * the messages returned by the request. + */ + public void setQueueMessages(List queueMessages) { + this.queueMessages = queueMessages; + } + + /** + * Represents a message in the queue returned by the server. A + * {@link QueueMessage} instance contains a copy of the queue message data + * in the storage service as of the time the message was requested. + */ + public static class QueueMessage { + private String messageId; + private Date insertionDate; + private Date expirationDate; + private String popReceipt; + private Date timeNextVisible; + private int dequeueCount; + private String messageText; + + /** + * Gets the message ID for the message in the queue. The message ID is a + * value that is opaque to the client that must be used along with the + * pop receipt to validate an update message or delete message + * operation. + * + * @return A {@link String} containing the message ID. + */ + @XmlElement(name = "MessageId") + public String getMessageId() { + return messageId; + } + + /** + * Reserved for internal use. Sets the value of the message ID for the + * queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the message ID returned by the server. + * + * @param messageId + * A {@link String} containing the message ID. + */ + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + /** + * Gets the {@link Date} when this message was added to the queue. + * + * @return The {@link Date} when this message was added to the queue. + */ + @XmlElement(name = "InsertionTime") + @XmlJavaTypeAdapter(RFC1123DateAdapter.class) + public Date getInsertionDate() { + return insertionDate; + } + + /** + * Reserved for internal use. Sets the value of the insertion time for + * the queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the insertion time returned by the server. + * + * @param insertionDate + * The {@link Date} when this message was added to the queue. + */ + public void setInsertionDate(Date insertionDate) { + this.insertionDate = insertionDate; + } + + /** + * Gets the {@link Date} when this message will expire and be + * automatically removed from the queue. + * + * @return The {@link Date} when this message will expire. + */ + @XmlElement(name = "ExpirationTime") + @XmlJavaTypeAdapter(RFC1123DateAdapter.class) + public Date getExpirationDate() { + return expirationDate; + } + + /** + * Reserved for internal use. Sets the value of the expiration time for + * the queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the expiration time returned by the server. + * + * @param expirationDate + * The {@link Date} when this message will expire. + */ + public void setExpirationDate(Date expirationDate) { + this.expirationDate = expirationDate; + } + + /** + * Gets the pop receipt value for the queue message. The pop receipt is + * a value that is opaque to the client that must be used along with the + * message ID to validate an update message or delete message operation. + * + * @return A {@link String} containing the pop receipt value for the + * queue message. + */ + @XmlElement(name = "PopReceipt") + public String getPopReceipt() { + return popReceipt; + } + + /** + * Reserved for internal use. Sets the value of the pop receipt for the + * queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the pop receipt returned by the server. + * + * @param popReceipt + * A {@link String} containing the pop receipt value for the + * queue message. + */ + public void setPopReceipt(String popReceipt) { + this.popReceipt = popReceipt; + } + + /** + * Gets the {@link Date} when this message will become visible in the + * queue. + * + * @return The {@link Date} when this message will become visible in the + * queue. + */ + @XmlElement(name = "TimeNextVisible") + @XmlJavaTypeAdapter(RFC1123DateAdapter.class) + public Date getTimeNextVisible() { + return timeNextVisible; + } + + /** + * Reserved for internal use. Sets the value of the time the message + * will become visible. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the time next visible returned by the server. + * + * @param timeNextVisible + * The {@link Date} when this message will become visible in + * the queue. + */ + public void setTimeNextVisible(Date timeNextVisible) { + this.timeNextVisible = timeNextVisible; + } + + /** + * Gets the number of times this queue message has been retrieved with a + * list messages operation. + * + * @return The number of times this queue message has been retrieved. + */ + @XmlElement(name = "DequeueCount") + public int getDequeueCount() { + return dequeueCount; + } + + /** + * Reserved for internal use. Sets the value of the dequeue count of the + * message. This method is invoked by the API as part of the response + * generation from the Queue Service REST API operation to set the value + * with the queue message dequeue count returned by the server. + * + * @param dequeueCount + * The number of times this queue message has been retrieved. + */ + public void setDequeueCount(int dequeueCount) { + this.dequeueCount = dequeueCount; + } + + /** + * Gets the {@link String} containing the content of the queue message. + * + * @return A {@link String} containing the content of the queue message. + */ + @XmlElement(name = "MessageText") + public String getMessageText() { + return messageText; + } + + /** + * Reserved for internal use. Sets the {@link String} containing the + * content of the message. This method is invoked by the API as part of + * the response generation from the Queue Service REST API operation to + * set the value with the queue message content returned by the server. + * + * @param messageText + * A {@link String} containing the content of the message. + */ + public void setMessageText(String messageText) { + this.messageText = messageText; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesOptions.java new file mode 100644 index 0000000000000..3b6e1deee6b74 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesOptions.java @@ -0,0 +1,175 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + + +/** + * Represents the options that may be set on the Queue service for + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions)} requests. These options + * include a server response timeout for the request, a prefix to match queue + * names to return, a marker to specify where to resume a list queues query, the + * maximum number of queues to return in a single response, and whether to + * include queue metadata with the response. + */ +public class ListQueuesOptions extends QueueServiceOptions { + private String prefix; + private String marker; + private int maxResults; + private boolean includeMetadata; + + /** + * Sets the server request timeout value associated with this + * {@link ListQueuesOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link ListQueuesOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link ListQueuesOptions} instance. + */ + @Override + public ListQueuesOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the prefix {@link String} used to match queue names to return in a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + * + * @return The prefix {@link String} used to match queue names to return in + * a {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * request. + */ + public String getPrefix() { + return prefix; + } + + /** + * Sets the prefix {@link String} to use to match queue names to return in a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + *

+ * The prefix value only affects calls made on methods where this + * {@link ListQueuesOptions} instance is passed as a parameter. + * + * @param prefix + * The prefix {@link String} to use to match queue names to + * return in a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * request. + * @return A reference to this {@link ListQueuesOptions} instance. + */ + public ListQueuesOptions setPrefix(String prefix) { + this.prefix = prefix; + return this; + } + + /** + * Gets a {@link String} value that identifies the beginning of the list of + * queues to be returned with a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + *

+ * The {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} method + * returns a NextMarker element within the response if the + * list returned was not complete, which can be accessed with the + * {@link ListQueuesResult#getNextMarker()} method. This opaque value may + * then be set on a {@link ListQueuesOptions} instance with a call to + * {@link ListQueuesOptions#setMarker(String) setMarker} to be used in a + * subsequent {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * call to request the next portion of the list of queues. + * + * @return The marker value that identifies the beginning of the list of + * queues to be returned. + */ + public String getMarker() { + return marker; + } + + /** + * Sets a {@link String} marker value that identifies the beginning of the + * list of queues to be returned with a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + *

+ * The {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} method + * returns a NextMarker element within the response if the + * list returned was not complete, which can be accessed with the + * {@link ListQueuesResult#getNextMarker()} method. This opaque value may + * then be set on a {@link ListQueuesOptions} instance with a call to + * {@link ListQueuesOptions#setMarker(String) setMarker} to be used in a + * subsequent {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * call to request the next portion of the list of queues. + * + * @param marker + * The {@link String} marker value to set. + * @return A reference to this {@link ListQueuesOptions} instance. + */ + public ListQueuesOptions setMarker(String marker) { + this.marker = marker; + return this; + } + + /** + * Gets the maximum number of queues to return with a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + * If the value is not specified, the server will return up to 5,000 items. + * + * @return The maximum number of queues to return. + */ + public int getMaxResults() { + return maxResults; + } + + /** + * Sets the maximum number of queues to return with a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + * If the value is not specified, by default the server will return up to + * 5,000 items. + *

+ * The maxResults value only affects calls made on methods where this + * {@link ListQueuesOptions} instance is passed as a parameter. + * + * @param maxResults + * The maximum number of queues to return. + * @return A reference to this {@link ListQueuesOptions} instance. + */ + public ListQueuesOptions setMaxResults(int maxResults) { + this.maxResults = maxResults; + return this; + } + + /** + * Gets a flag indicating whether to return metadata with a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + * + * @return true to return metadata. + */ + public boolean isIncludeMetadata() { + return includeMetadata; + } + + /** + * Sets a flag indicating whether to return metadata with a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} request. + * + * @param includeMetadata + * true to return metadata. + * @return A reference to this {@link ListQueuesOptions} instance. + */ + public ListQueuesOptions setIncludeMetadata(boolean includeMetadata) { + this.includeMetadata = includeMetadata; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesResult.java new file mode 100644 index 0000000000000..bba9354d417e8 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesResult.java @@ -0,0 +1,332 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.services.blob.implementation.MetadataAdapter; + +/** + * A wrapper class for the results returned in response to Queue service REST + * API operations to list queues. This is returned by calls to implementations + * of {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues()} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions)}. + *

+ * See the List Queues documentation on MSDN for details of the underlying Queue + * service REST API operation. + */ +@XmlRootElement(name = "EnumerationResults") +public class ListQueuesResult { + private List queues = new ArrayList(); + private String accountName; + private String prefix; + private String marker; + private String nextMarker; + private int maxResults; + + /** + * Gets the list of queues returned by a {@link com.microsoft.windowsazure.services.queue.QueueContract} + * .listQueues request. + * + * @return A {@link List} of {@link Queue} instances representing the queues + * returned by the request. + */ + @XmlElementWrapper(name = "Queues") + @XmlElement(name = "Queue") + public List getQueues() { + return queues; + } + + /** + * Reserved for internal use. Sets the list of queues returned by a + * {@link com.microsoft.windowsazure.services.queue.QueueContract}.listQueues request. This method is invoked + * by the API as part of the response generation from the Queue service REST + * API operation to set the value from the queue list returned by the + * server. + * + * @param value + * A {@link List} of {@link Queue} instances representing the + * queues returned by the request. + */ + public void setQueues(List value) { + this.queues = value; + } + + /** + * Gets the base URI for Queue service REST API operations on the storage + * account. The URI consists of the protocol along with the DNS prefix name + * for the account followed by ".queue.core.windows.net". For example, if + * the DNS prefix name for the storage account is "myaccount" then the value + * returned by this method is "http://myaccount.queue.core.windows.net". + * + * @return A {@link String} containing the base URI for Queue service REST + * API operations on the storage account. + */ + @XmlAttribute(name = "AccountName") + public String getAccountName() { + return accountName; + } + + /** + * Reserved for internal use. Sets the base URI for Queue service REST API + * operations on the storage account. This method is invoked by the API as + * part of the response generation from the Queue service REST API operation + * to set the value from the response returned by the server. + * + * @param accountName + * A {@link String} containing the base URI for Queue service + * REST API operations on the storage account. + */ + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + /** + * Gets the prefix {@link String} used to qualify the results returned by + * the {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * request. Only queues with names that start with the prefix are returned + * by the request. By default, the prefix is empty and all queues are + * returned. + * + * @return The {@link String} prefix used to qualify the names of the queues + * returned. + */ + @XmlElement(name = "Prefix") + public String getPrefix() { + return prefix; + } + + /** + * Reserved for internal use. Sets the prefix {@link String} used to qualify + * the results returned by the Queue service REST API list queues operation + * invoked with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues}. This + * method is invoked by the API as part of the response generation from the + * Queue service REST API operation to set the value from the + * Prefix element returned by the server. + * + * @param prefix + * The {@link String} prefix used to qualify the names of the + * queues returned. + */ + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + /** + * Gets the marker value for the beginning of the queue results returned by + * the {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * request. The marker is used by the server to specify the place to resume + * a query for queues. The marker value is a {@link String} opaque to the + * client. A {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * request response may include a NextMarker value if there + * are more queue results than can be returned in a single response. Call + * the {@link ListQueuesResult#getNextMarker() getNextMarker} method to get + * this value. The client can request the next set of queue results by + * setting the marker to this value in the {@link ListQueuesOptions} + * parameter. By default, this value is empty and the server responds with + * the first queues that match the request. + * + * @return A {@link String} containing the marker value used for the + * response. + */ + @XmlElement(name = "Marker") + public String getMarker() { + return marker; + } + + /** + * Reserved for internal use. Sets the marker value specifying the beginning + * of the results returned by the Queue service REST API list queues + * operation invoked with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues}. This + * method is invoked by the API as part of the response generation from the + * Queue service REST API operation to set the value from the + * Marker element returned by the server. + * + * @param marker + * A {@link String} containing the marker value used for the + * response. + */ + public void setMarker(String marker) { + this.marker = marker; + } + + /** + * Gets the next marker value needed to retrieve additional queues. If more + * queues are available that satisfy a listQueues request than can + * be returned in the response, the server generates a marker value to + * specify the beginning of the queues to return in a subsequent request. + * The client can request the next set of queue results by setting the + * marker to this value in the {@link ListQueuesOptions} parameter. This + * value is empty if there are no more queues that satisfy the request than + * are included in the response. + * + * @return A {@link String} containing the marker value to use to resume the + * list queues request. + */ + @XmlElement(name = "NextMarker") + public String getNextMarker() { + return nextMarker; + } + + /** + * Reserved for internal use. Sets the next marker value specifying the + * place to resume a list queues query if more results are available than + * have been returned by the Queue service REST API list queues operation + * response. This method is invoked by the API as part of the response + * generation from the Queue service REST API operation to set the value + * from the NextMarker element returned by the server. + * + * @param nextMarker + * A {@link String} containing the marker value to use to resume + * the list queues request. + */ + public void setNextMarker(String nextMarker) { + this.nextMarker = nextMarker; + } + + /** + * Gets the value specified for the number of queue results to return for + * the {@link com.microsoft.windowsazure.services.queue.QueueContract#listQueues(ListQueuesOptions) listQueues} + * request. The server will not return more than this number of queues in + * the response. If the value is not specified, the server will return up to + * 5,000 items. + *

+ * If there are more queues available that match the request than the number + * returned, the response will include a next marker value to specify the + * beginning of the queues to return in a subsequent request. Call the + * {@link ListQueuesResult#getNextMarker() getNextMarker} method to get this + * value. The client can request the next set of queue results by setting + * the marker to this value in the {@link ListQueuesOptions} parameter. + * + * @return The maximum number of results to return specified by the request. + */ + @XmlElement(name = "MaxResults") + public int getMaxResults() { + return maxResults; + } + + /** + * Reserved for internal use. Sets the value returned by the Queue service + * REST API list queues operation response for the maximum number of queues + * to return. This method is invoked by the API as part of the response + * generation from the Queue service REST API operation to set the value + * from the MaxResults element returned by the server. + * + * @param maxResults + * The maximum number of results to return specified by the + * request. + */ + public void setMaxResults(int maxResults) { + this.maxResults = maxResults; + } + + /** + * Represents a queue in the storage account returned by the server. A + * {@link Queue} instance contains a copy of the queue name, URI, and + * metadata in the storage service as of the time the queue was requested. + */ + public static class Queue { + private String name; + private String url; + private HashMap metadata = new HashMap(); + + /** + * Gets the name of this queue. + * + * @return A {@link String} containing the name of this queue. + */ + @XmlElement(name = "Name") + public String getName() { + return name; + } + + /** + * Reserved for internal use. Sets the name of this queue. This method + * is invoked by the API as part of the response generation from the + * Queue service REST API operation to set the value from the + * Name element returned by the server. + * + * @param name + * A {@link String} containing the name of this queue. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the URI for Queue service REST API operations on this queue. + * + * @return A {@link String} containing the URI for Queue service REST + * API operations on this queue. + */ + @XmlElement(name = "Url") + public String getUrl() { + return url; + } + + /** + * Reserved for internal use. Sets the URI of this queue. This method is + * invoked by the API as part of the response generation from the Queue + * service REST API operation to set the value from the + * Url element returned by the server. + * + * @param url + * A {@link String} containing the URI for Queue service REST + * API operations on this queue. + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * Gets the metadata collection of key-value {@link String} pairs + * associated with this queue. + * + * @return A {@link java.util.HashMap} of key-value {@link String} pairs + * containing the queue metadata. + */ + @XmlElement(name = "Metadata") + @XmlJavaTypeAdapter(MetadataAdapter.class) + public HashMap getMetadata() { + return metadata; + } + + /** + * Reserved for internal use. Sets the metadata of this queue. This + * method is invoked by the API as part of the response generation from + * the Queue service REST API operation to set the value from the + * Metadata element returned by the server. + * + * @param metadata + * A {@link java.util.HashMap} of key-value {@link String} + * pairs containing the queue metadata. + */ + public void setMetadata(HashMap metadata) { + this.metadata = metadata; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesOptions.java new file mode 100644 index 0000000000000..a4f7c0dca2083 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesOptions.java @@ -0,0 +1,73 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + + +/** + * Represents the options that may be set on a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#peekMessages(String, PeekMessagesOptions) peekMessages} + * request. These options include a server response timeout for the request and + * the number of messages to peek from the queue. + */ +public class PeekMessagesOptions extends QueueServiceOptions { + private Integer numberOfMessages; + + /** + * Sets the server request timeout value associated with this + * {@link PeekMessagesOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link PeekMessagesOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link PeekMessagesOptions} instance. + */ + @Override + public PeekMessagesOptions setTimeout(Integer timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * Gets the number of messages to return in the response to a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#peekMessages(String, PeekMessagesOptions) + * peekMessages} request specified in this instance. + * + * @return The number of messages to return in the response. + */ + public Integer getNumberOfMessages() { + return numberOfMessages; + } + + /** + * Sets the number of messages to return in the response to a + * {@link com.microsoft.windowsazure.services.queue.QueueContract#peekMessages(String, PeekMessagesOptions) + * peekMessages} request. + *

+ * The numberOfMessages value only affects calls made on methods + * where this {@link PeekMessagesOptions} instance is passed as a parameter. + * + * + * @param numberOfMessages + * The number of messages to return in the response. This value + * must be in the range from 0 to 32. + * @return A reference to this {@link PeekMessagesOptions} instance. + */ + public PeekMessagesOptions setNumberOfMessages(Integer numberOfMessages) { + this.numberOfMessages = numberOfMessages; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesResult.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesResult.java new file mode 100644 index 0000000000000..2c02b7c1f2c2a --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesResult.java @@ -0,0 +1,202 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.microsoft.windowsazure.core.RFC1123DateAdapter; + +/** + * A wrapper class for the results returned in response to Queue Service REST + * API operations to peek messages. This is returned by calls to implementations + * of {@link com.microsoft.windowsazure.services.queue.QueueContract#peekMessages(String)} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#peekMessages(String, PeekMessagesOptions)}. + *

+ * See the Peek Messages documentation on MSDN for details of the underlying Queue + * Service REST API operation. + */ +@XmlRootElement(name = "QueueMessagesList") +public class PeekMessagesResult { + private List queueMessages = new ArrayList(); + + /** + * Gets the list of queue messages returned by a {@link com.microsoft.windowsazure.services.queue.QueueContract} + * .peekMessages request. The queue messages returned do not have a + * visibility timeout set, and they can be retrieved by other clients for + * processing. + * + * @return A {@link List} of {@link QueueMessage} instances representing the + * messages returned by the request. + */ + @XmlElement(name = "QueueMessage") + public List getQueueMessages() { + return queueMessages; + } + + /** + * Reserved for internal use. Sets the list of queue messages returned by a + * {@link com.microsoft.windowsazure.services.queue.QueueContract} .peekMessages request. This method is + * invoked by the API as part of the response generation from the Queue + * Service REST API operation to set the value from the queue message list + * returned by the server. + * + * @param queueMessages + * A {@link List} of {@link QueueMessage} instances representing + * the messages returned by the request. + */ + public void setQueueMessages(List queueMessages) { + this.queueMessages = queueMessages; + } + + /** + * Represents a message in the queue returned by the server. A + * {@link QueueMessage} instance contains a copy of the queue message data + * in the storage service as of the time the message was requested. + */ + public static class QueueMessage { + private String messageId; + private Date insertionDate; + private Date expirationDate; + private int dequeueCount; + private String messageText; + + /** + * Gets the message ID for the message in the queue. * + * + * @return A {@link String} containing the message ID. + */ + @XmlElement(name = "MessageId") + public String getMessageId() { + return messageId; + } + + /** + * Reserved for internal use. Sets the value of the message ID for the + * queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the message ID returned by the server. + * + * @param messageId + * A {@link String} containing the message ID. + */ + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + /** + * Gets the {@link Date} when this message was added to the queue. + * + * @return The {@link Date} when this message was added to the queue. + */ + @XmlElement(name = "InsertionTime") + @XmlJavaTypeAdapter(RFC1123DateAdapter.class) + public Date getInsertionDate() { + return insertionDate; + } + + /** + * Reserved for internal use. Sets the value of the insertion time for + * the queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the insertion time returned by the server. + * + * @param insertionDate + * The {@link Date} when this message was added to the queue. + */ + public void setInsertionDate(Date insertionDate) { + this.insertionDate = insertionDate; + } + + /** + * Gets the {@link Date} when this message will expire and be + * automatically removed from the queue. + * + * @return The {@link Date} when this message will expire. + */ + @XmlElement(name = "ExpirationTime") + @XmlJavaTypeAdapter(RFC1123DateAdapter.class) + public Date getExpirationDate() { + return expirationDate; + } + + /** + * Reserved for internal use. Sets the value of the expiration time for + * the queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set + * the value with the expiration time returned by the server. + * + * @param expirationDate + * The {@link Date} when this message will expire. + */ + public void setExpirationDate(Date expirationDate) { + this.expirationDate = expirationDate; + } + + /** + * Gets the number of times this queue message has been retrieved with a + * list messages operation. + * + * @return The number of times this queue message has been retrieved. + */ + @XmlElement(name = "DequeueCount") + public int getDequeueCount() { + return dequeueCount; + } + + /** + * Reserved for internal use. Sets the value of the dequeue count of the + * message. This method is invoked by the API as part of the response + * generation from the Queue Service REST API operation to set the value + * with the queue message dequeue count returned by the server. + * + * @param dequeueCount + * The number of times this queue message has been retrieved. + */ + public void setDequeueCount(int dequeueCount) { + this.dequeueCount = dequeueCount; + } + + /** + * Gets the {@link String} containing the content of the queue message. + * + * @return A {@link String} containing the content of the queue message. + */ + @XmlElement(name = "MessageText") + public String getMessageText() { + return messageText; + } + + /** + * Reserved for internal use. Sets the {@link String} containing the + * content of the message. This method is invoked by the API as part of + * the response generation from the Queue Service REST API operation to + * set the value with the queue message content returned by the server. + * + * @param messageText + * A {@link String} containing the content of the message. + */ + public void setMessageText(String messageText) { + this.messageText = messageText; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/QueueServiceOptions.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/QueueServiceOptions.java new file mode 100644 index 0000000000000..d273936c84878 --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/QueueServiceOptions.java @@ -0,0 +1,56 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + + +/** + * Represents the base class for options that may be set on Queue Service REST + * API operations invoked through the {@link com.microsoft.windowsazure.services.queue.QueueContract} interface. This + * class defines a server request timeout, which can be applied to all + * operations. + */ +public class QueueServiceOptions { + // Nullable because it is optional + private Integer timeout; + + /** + * Gets the current server request timeout value associated with this + * {@link QueueServiceOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link QueueServiceOptions} instance is passed as a parameter. + * + * @return The server request timeout value in milliseconds. + */ + public Integer getTimeout() { + return timeout; + } + + /** + * Sets the server request timeout value associated with this + * {@link QueueServiceOptions} instance. + *

+ * The timeout value only affects calls made on methods where this + * {@link QueueServiceOptions} instance is passed as a parameter. + * + * @param timeout + * The server request timeout value to set in milliseconds. + * @return A reference to this {@link QueueServiceOptions} instance. + */ + public QueueServiceOptions setTimeout(Integer timeout) { + this.timeout = timeout; + return this; + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ServiceProperties.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ServiceProperties.java new file mode 100644 index 0000000000000..0723e6f4fbabd --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/ServiceProperties.java @@ -0,0 +1,480 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * A wrapper class for the Queue service properties set or retrieved with Queue + * Service REST API operations. This is returned by calls to implementations of + * {@link com.microsoft.windowsazure.services.queue.QueueContract#getServiceProperties()} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#getServiceProperties(QueueServiceOptions)} and passed to + * the server with calls to + * {@link com.microsoft.windowsazure.services.queue.QueueContract#setServiceProperties(ServiceProperties)} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#setServiceProperties(ServiceProperties, QueueServiceOptions)} + * . + *

+ * See the Get + * Queue Service Properties and Set + * Queue Service Properties documentation on MSDN for details of the + * underlying Queue Service REST API operations. See the Storage Analytics Overview documentation on MSDN for more information + * about logging and metrics. + */ +@XmlRootElement(name = "StorageServiceProperties") +public class ServiceProperties { + private Logging logging = new Logging(); + private Metrics metrics = new Metrics(); + + /** + * Gets a reference to the {@link Logging} instance in this + * {@link ServiceProperties} instance. + *

+ * This {@link ServiceProperties} instance holds a local copy of the Queue + * service properties when returned by a call to {@link com.microsoft.windowsazure.services.queue.QueueContract} + * .getServiceProperties. + *

+ * Note that changes to this value are not reflected in the Queue service + * properties until they have been set on the storage account with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract}.setServiceProperties. + * + * @return A reference to the {@link Logging} instance in this + * {@link ServiceProperties} instance. + */ + @XmlElement(name = "Logging") + public Logging getLogging() { + return logging; + } + + /** + * Sets the {@link Logging} instance in this {@link ServiceProperties} + * instance. + *

+ * Note that changes to this value are not reflected in the Queue service + * properties until they have been set on the storage account with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract}.setServiceProperties. + * + * @param logging + * The {@link Logging} instance to set in this + * {@link ServiceProperties} instance. + * @return A reference to this {@link ServiceProperties} instance. + */ + public ServiceProperties setLogging(Logging logging) { + this.logging = logging; + return this; + } + + /** + * Gets a reference to the {@link Metrics} instance in this + * {@link ServiceProperties} instance. + *

+ * This {@link ServiceProperties} instance holds a local copy of the Queue + * service properties when returned by a call to {@link com.microsoft.windowsazure.services.queue.QueueContract} + * .getServiceProperties. + *

+ * Note that changes to this value are not reflected in the Queue service + * properties until they have been set on the storage account with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract}.setServiceProperties. + * + * @return A reference to the {@link Metrics} instance in this + * {@link ServiceProperties} instance. + */ + @XmlElement(name = "Metrics") + public Metrics getMetrics() { + return metrics; + } + + /** + * Sets the {@link Metrics} instance in this {@link ServiceProperties} + * instance. + *

+ * Note that changes to this value are not reflected in the Queue service + * properties until they have been set on the storage account with a call to + * {@link com.microsoft.windowsazure.services.queue.QueueContract}.setServiceProperties. + * + * @param metrics + * The {@link Metrics} instance to set in this + * {@link ServiceProperties} instance. + * @return A reference to this {@link ServiceProperties} instance. + */ + public ServiceProperties setMetrics(Metrics metrics) { + this.metrics = metrics; + return this; + } + + /** + * This inner class represents the settings for logging on the Queue service + * of the storage account. These settings include the Storage Analytics + * version, whether to log delete requests, read requests, or write + * requests, and a {@link RetentionPolicy} instance for retention policy + * settings. + */ + public static class Logging { + private String version; + private Boolean delete; + private Boolean read; + private Boolean write; + private RetentionPolicy retentionPolicy; + + /** + * Gets a reference to the {@link RetentionPolicy} instance in this + * {@link Logging} instance. + * + * @return A reference to the {@link RetentionPolicy} instance in this + * {@link Logging} instance. + */ + @XmlElement(name = "RetentionPolicy") + public RetentionPolicy getRetentionPolicy() { + return retentionPolicy; + } + + /** + * Sets the {@link RetentionPolicy} instance in this {@link Logging} + * instance. + * + * @param retentionPolicy + * The {@link RetentionPolicy} instance to set in this + * {@link Logging} instance. + * @return A reference to this {@link Logging} instance. + */ + public Logging setRetentionPolicy(RetentionPolicy retentionPolicy) { + this.retentionPolicy = retentionPolicy; + return this; + } + + /** + * Gets a flag indicating whether queue write operations are logged. If + * this value is true then all requests that write to the + * Queue service will be logged. These requests include adding a + * message, updating a message, setting queue metadata, and creating a + * queue. + * + * @return true if queue write operations are logged, + * otherwise false. + */ + @XmlElement(name = "Write") + public boolean isWrite() { + return write; + } + + /** + * Sets a flag indicating whether queue write operations are logged. If + * this value is true then all requests that write to the + * Queue service will be logged. These requests include adding a + * message, updating a message, setting queue metadata, and creating a + * queue. + * + * @param write + * true to enable logging of queue write + * operations, otherwise false. + * @return A reference to this {@link Logging} instance. + */ + public Logging setWrite(boolean write) { + this.write = write; + return this; + } + + /** + * Gets a flag indicating whether queue read operations are logged. If + * this value is true then all requests that read from the + * Queue service will be logged. These requests include listing queues, + * getting queue metadata, listing messages, and peeking messages. + * + * @return true if queue read operations are logged, + * otherwise false. + */ + @XmlElement(name = "Read") + public boolean isRead() { + return read; + } + + /** + * Sets a flag indicating whether queue read operations are logged. If + * this value is true then all requests that read from the + * Queue service will be logged. These requests include listing queues, + * getting queue metadata, listing messages, and peeking messages. + * + * @param read + * true to enable logging of queue read + * operations, otherwise false. + * @return A reference to this {@link Logging} instance. + */ + public Logging setRead(boolean read) { + this.read = read; + return this; + } + + /** + * Gets a flag indicating whether queue delete operations are logged. If + * this value is true then all requests that delete from + * the Queue service will be logged. These requests include deleting + * queues, deleting messages, and clearing messages. + * + * @return true if queue delete operations are logged, + * otherwise false. + */ + @XmlElement(name = "Delete") + public boolean isDelete() { + return delete; + } + + /** + * Sets a flag indicating whether queue delete operations are logged. If + * this value is true then all requests that delete from + * the Queue service will be logged. These requests include deleting + * queues, deleting messages, and clearing messages. + * + * @param delete + * true to enable logging of queue delete + * operations, otherwise false. + * @return A reference to this {@link Logging} instance. + */ + public Logging setDelete(boolean delete) { + this.delete = delete; + return this; + } + + /** + * Gets the Storage Analytics version number associated with this + * {@link Logging} instance. + * + * @return A {@link String} containing the Storage Analytics version + * number. + */ + @XmlElement(name = "Version") + public String getVersion() { + return version; + } + + /** + * Sets the Storage Analytics version number to associate with this + * {@link Logging} instance. The current supported version number is + * "1.0". + *

+ * See the Storage Analytics Overview documentation on MSDN for more + * information. + * + * @param version + * A {@link String} containing the Storage Analytics version + * number to set. + * @return A reference to this {@link Logging} instance. + */ + public Logging setVersion(String version) { + this.version = version; + return this; + } + } + + /** + * This inner class represents the settings for metrics on the Queue service + * of the storage account. These settings include the Storage Analytics + * version, whether metrics are enabled, whether to include API operation + * summary statistics, and a {@link RetentionPolicy} instance for retention + * policy settings. + */ + public static class Metrics { + private String version; + private boolean enabled; + private Boolean includeAPIs; + private RetentionPolicy retentionPolicy; + + /** + * Gets a reference to the {@link RetentionPolicy} instance in this + * {@link Metrics} instance. + * + * @return A reference to the {@link RetentionPolicy} instance in this + * {@link Metrics} instance. + */ + @XmlElement(name = "RetentionPolicy") + public RetentionPolicy getRetentionPolicy() { + return retentionPolicy; + } + + /** + * Sets the {@link RetentionPolicy} instance in this {@link Metrics} + * instance. + * + * @param retentionPolicy + * The {@link RetentionPolicy} instance to set in this + * {@link Metrics} instance. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setRetentionPolicy(RetentionPolicy retentionPolicy) { + this.retentionPolicy = retentionPolicy; + return this; + } + + /** + * Gets a flag indicating whether metrics should generate summary + * statistics for called API operations. If this value is + * true then all Queue service REST API operations will be + * included in the metrics. + * + * @return true if Queue service REST API operations are + * included in metrics, otherwise false. + */ + @XmlElement(name = "IncludeAPIs") + public Boolean isIncludeAPIs() { + return includeAPIs; + } + + /** + * Sets a flag indicating whether metrics should generate summary + * statistics for called API operations. If this value is + * true then all Queue service REST API operations will be + * included in the metrics. + * + * @param includeAPIs + * true to include Queue service REST API + * operations in metrics, otherwise false. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setIncludeAPIs(Boolean includeAPIs) { + this.includeAPIs = includeAPIs; + return this; + } + + /** + * Gets a flag indicating whether metrics is enabled for the Queue + * storage service. + * + * @return A flag indicating whether metrics is enabled for the Queue + * storage service. + */ + @XmlElement(name = "Enabled") + public boolean isEnabled() { + return enabled; + } + + /** + * Sets a flag indicating whether to enable metrics for the Queue + * storage service. + * + * @param enabled + * true to enable metrics for the Queue storage + * service, otherwise false. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Gets the Storage Analytics version number associated with this + * {@link Metrics} instance. + * + * @return A {@link String} containing the Storage Analytics version + * number. + */ + @XmlElement(name = "Version") + public String getVersion() { + return version; + } + + /** + * Sets the Storage Analytics version number to associate with this + * {@link Metrics} instance. The current supported version number is + * "1.0". + *

+ * See the Storage Analytics Overview documentation on MSDN for more + * information. + * + * @param version + * A {@link String} containing the Storage Analytics version + * number to set. + * @return A reference to this {@link Metrics} instance. + */ + public Metrics setVersion(String version) { + this.version = version; + return this; + } + } + + /** + * This inner class represents the retention policy settings for logging or + * metrics on the Queue service of the storage account. These settings + * include whether a retention policy is enabled for the data, and the + * number of days that metrics or logging data should be retained. + */ + public static class RetentionPolicy { + private boolean enabled; + private Integer days; // nullable, because optional if "enabled" is + // false + + /** + * Gets the number of days that metrics or logging data should be + * retained. All data older than this value will be deleted. The value + * may be null if a retention policy is not enabled. + * + * @return The number of days that metrics or logging data should be + * retained. + */ + @XmlElement(name = "Days") + public Integer getDays() { + return days; + } + + /** + * Sets the number of days that metrics or logging data should be + * retained. All data older than this value will be deleted. The value + * must be in the range from 1 to 365. This value must be set if a + * retention policy is enabled, but is not required if a retention + * policy is not enabled. + * + * @param days + * The number of days that metrics or logging data should be + * retained. + * @return A reference to this {@link RetentionPolicy} instance. + */ + public RetentionPolicy setDays(Integer days) { + this.days = days; + return this; + } + + /** + * Gets a flag indicating whether a retention policy is enabled for the + * storage service. + * + * @return true if data retention is enabled, otherwise + * false. + */ + @XmlElement(name = "Enabled") + public boolean isEnabled() { + return enabled; + } + + /** + * Sets a flag indicating whether a retention policy is enabled for the + * storage service. + * + * @param enabled + * Set true to enable data retention. + * @return A reference to this {@link RetentionPolicy} instance. + */ + public RetentionPolicy setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + } +} diff --git a/media/src/main/java/com/microsoft/windowsazure/services/queue/models/UpdateMessageResult.java b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/UpdateMessageResult.java new file mode 100644 index 0000000000000..f8a7decde7b8f --- /dev/null +++ b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/UpdateMessageResult.java @@ -0,0 +1,86 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue.models; + +import java.util.Date; + +/** + * A wrapper class for the results returned in response to Queue Service REST + * API operations to update a message. This is returned by calls to + * implementations of + * {@link com.microsoft.windowsazure.services.queue.QueueContract#updateMessage(String, String, String, String, int)} and + * {@link com.microsoft.windowsazure.services.queue.QueueContract#updateMessage(String, String, String, String, int, QueueServiceOptions)} + * . + *

+ * See the Update Message documentation on MSDN for details of the underlying Queue + * Service REST API operation. + */ +public class UpdateMessageResult { + private String popReceipt; + private Date timeNextVisible; + + /** + * Gets the pop receipt value for the updated queue message. The pop receipt + * is a value that is opaque to the client that must be used along with the + * message ID to validate an update message or delete message operation. + * + * @return A {@link String} containing the pop receipt value for the queue + * message. + */ + public String getPopReceipt() { + return popReceipt; + } + + /** + * Reserved for internal use. Sets the value of the pop receipt for the + * updated queue message. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set the + * value with the pop receipt returned by the server. + * + * @param popReceipt + * A {@link String} containing the pop receipt value for the + * queue message. + */ + public void setPopReceipt(String popReceipt) { + this.popReceipt = popReceipt; + } + + /** + * Gets the {@link Date} when the updated message will become visible in the + * queue. + * + * @return The {@link Date} when the updated message will become visible in + * the queue. + */ + public Date getTimeNextVisible() { + return timeNextVisible; + } + + /** + * Reserved for internal use. Sets the value of the time the updated message + * will become visible. This method is invoked by the API as part of the + * response generation from the Queue Service REST API operation to set the + * value with the time next visible returned by the server. + * + * @param timeNextVisible + * The {@link Date} when the updated message will become visible + * in the queue. + */ + public void setTimeNextVisible(Date timeNextVisible) { + this.timeNextVisible = timeNextVisible; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/package.html b/media/src/main/java/com/microsoft/windowsazure/services/queue/models/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/queue/models/package.html diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/package.html b/media/src/main/java/com/microsoft/windowsazure/services/queue/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/package.html rename to media/src/main/java/com/microsoft/windowsazure/services/queue/package.html diff --git a/media/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/media/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..834120dd4c167 --- /dev/null +++ b/media/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1,3 @@ +com.microsoft.windowsazure.services.blob.Exports +com.microsoft.windowsazure.services.queue.Exports +com.microsoft.windowsazure.services.media.Exports \ No newline at end of file diff --git a/media/src/test/java/com/microsoft/windowsazure/services/blob/BlobServiceIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/blob/BlobServiceIntegrationTest.java new file mode 100644 index 0000000000000..05a4a5fc44536 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/blob/BlobServiceIntegrationTest.java @@ -0,0 +1,782 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringWriter; +import java.io.Writer; +import java.util.HashSet; +import java.util.Set; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import com.microsoft.windowsazure.core.pipeline.jersey.ExponentialRetryPolicy; +import com.microsoft.windowsazure.core.pipeline.jersey.RetryPolicyFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.blob.models.BlobProperties; +import com.microsoft.windowsazure.services.blob.models.BlockList; +import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; +import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; +import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; +import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; +import com.microsoft.windowsazure.services.blob.models.GetBlobResult; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; +import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; +import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; +import com.microsoft.windowsazure.services.blob.models.ListContainersResult; +import com.microsoft.windowsazure.services.blob.models.ListContainersResult.Container; + +public class BlobServiceIntegrationTest extends IntegrationTestBase { + private static final String testContainersPrefix = "sdktest-"; + private static final String createableContainersPrefix = "csdktest-"; + private static String CREATEABLE_CONTAINER_1; + private static String TEST_CONTAINER_FOR_BLOBS; + private static String[] creatableContainers; + private static String[] testContainers; + private static boolean createdRoot; + + @BeforeClass + public static void setup() throws Exception { + // Setup container names array (list of container names used by + // integration tests) + testContainers = new String[10]; + for (int i = 0; i < testContainers.length; i++) { + testContainers[i] = String.format("%s%d", testContainersPrefix, + i + 1); + } + + creatableContainers = new String[10]; + for (int i = 0; i < creatableContainers.length; i++) { + creatableContainers[i] = String.format("%s%d", + createableContainersPrefix, i + 1); + } + + CREATEABLE_CONTAINER_1 = creatableContainers[0]; + TEST_CONTAINER_FOR_BLOBS = testContainers[0]; + // Create all test containers and their content + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + createContainers(service, testContainersPrefix, testContainers); + + try { + service.createContainer("$root"); + createdRoot = true; + } catch (ServiceException e) { + // e.printStackTrace(); + } + } + + @AfterClass + public static void cleanup() throws Exception { + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + deleteContainers(service, testContainersPrefix, testContainers); + deleteContainers(service, createableContainersPrefix, + creatableContainers); + + // If container was created, delete it + if (createdRoot) { + try { + service.deleteContainer("$root"); + createdRoot = false; + } catch (ServiceException e) { + // e.printStackTrace(); + } + } + } + + private static void createContainers(BlobContract service, String prefix, + String[] list) throws Exception { + Set containers = listContainers(service, prefix); + for (String item : list) { + if (!containers.contains(item)) { + service.createContainer(item); + } + } + } + + private static void deleteContainers(BlobContract service, String prefix, + String[] list) throws Exception { + Set containers = listContainers(service, prefix); + for (String item : list) { + if (containers.contains(item)) { + service.deleteContainer(item); + } + } + } + + private static Set listContainers(BlobContract service, + String prefix) throws Exception { + HashSet result = new HashSet(); + ListContainersResult list = service + .listContainers(new ListContainersOptions().setPrefix(prefix)); + for (Container item : list.getContainers()) { + result.add(item.getName()); + } + return result; + } + + @Test + public void createContainerWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + service.createContainer(CREATEABLE_CONTAINER_1); + + // Assert + } + + @Test(expected = IllegalArgumentException.class) + public void createNullContainerFail() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + service.createContainer(null); + + // Assert + assertTrue(false); + } + + @Test + public void deleteContainerWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + String containerName = "deletecontainerworks"; + service.createContainer(containerName, new CreateContainerOptions() + .setPublicAccess("blob").addMetadata("test", "bar") + .addMetadata("blah", "bleah")); + + // Act + service.deleteContainer(containerName); + ListContainersResult listContainerResult = service.listContainers(); + + // Assert + for (Container container : listContainerResult.getContainers()) { + assertTrue(!container.getName().equals(containerName)); + } + } + + @Test(expected = IllegalArgumentException.class) + public void deleteNullContainerFail() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + service.deleteContainer(null); + + // Assert + assertTrue(false); + } + + @Test + public void listContainersWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + ListContainersResult results = service.listContainers(); + + // Assert + assertNotNull(results); + assertTrue(testContainers.length <= results.getContainers().size()); + assertNotNull(results.getContainers().get(0).getName()); + assertNotNull(results.getContainers().get(0).getMetadata()); + assertNotNull(results.getContainers().get(0).getProperties()); + assertNotNull(results.getContainers().get(0).getProperties().getEtag()); + assertNotNull(results.getContainers().get(0).getProperties() + .getLastModified()); + assertNotNull(results.getContainers().get(0).getUrl()); + } + + @Test + public void listContainersWithPaginationWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + ListContainersResult results = service + .listContainers(new ListContainersOptions().setMaxResults(3)); + ListContainersResult results2 = service + .listContainers(new ListContainersOptions().setMarker(results + .getNextMarker())); + + // Assert + assertNotNull(results); + assertEquals(3, results.getContainers().size()); + assertNotNull(results.getNextMarker()); + assertEquals(3, results.getMaxResults()); + + assertNotNull(results2); + assertTrue(testContainers.length - 3 <= results2.getContainers().size()); + assertEquals("", results2.getNextMarker()); + assertEquals(0, results2.getMaxResults()); + } + + @Test + public void listContainersWithPrefixWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + ListContainersResult results = service + .listContainers(new ListContainersOptions().setPrefix( + testContainersPrefix).setMaxResults(3)); + // Assert + assertNotNull(results); + assertEquals(3, results.getContainers().size()); + assertNotNull(results.getNextMarker()); + assertEquals(3, results.getMaxResults()); + + // Act + ListContainersResult results2 = service + .listContainers(new ListContainersOptions().setPrefix( + testContainersPrefix) + .setMarker(results.getNextMarker())); + + // Assert + assertNotNull(results2); + assertNotNull(results2.getNextMarker()); + assertEquals(0, results2.getMaxResults()); + + // Act + ListContainersResult results3 = service + .listContainers(new ListContainersOptions() + .setPrefix(testContainersPrefix)); + + // Assert + assertEquals(results.getContainers().size() + + results2.getContainers().size(), results3.getContainers() + .size()); + } + + @Test + public void listBlockBlobWithNoCommittedBlocksWorks() throws Exception { + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + String container = TEST_CONTAINER_FOR_BLOBS; + String blob = "listBlockBlobWithNoCommittedBlocksWorks"; + + service.createBlockBlob(container, blob, null); + service.createBlobBlock(container, blob, "01", + new ByteArrayInputStream(new byte[] { 0x00 })); + service.deleteBlob(container, blob); + + try { + // Note: This next two lines should give a 404, because the blob no + // longer + // exists. However, the service sometimes allow this improper + // access, so + // the SDK has to handle the situation gracefully. + service.createBlobBlock(container, blob, "01", + new ByteArrayInputStream(new byte[] { 0x00 })); + ListBlobBlocksResult result = service.listBlobBlocks(container, + blob); + assertEquals(0, result.getCommittedBlocks().size()); + } catch (ServiceException ex) { + assertEquals(404, ex.getHttpStatusCode()); + } + } + + @Test + public void listBlobBlocksOnEmptyBlobWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String container = TEST_CONTAINER_FOR_BLOBS; + String blob = "test13"; + String content = new String(new char[512]); + service.createBlockBlob(container, blob, new ByteArrayInputStream( + content.getBytes("UTF-8"))); + + ListBlobBlocksResult result = service.listBlobBlocks(container, blob); + + // Assert + assertNotNull(result); + assertNotNull(result.getLastModified()); + assertNotNull(result.getEtag()); + assertEquals(512, result.getContentLength()); + assertNotNull(result.getCommittedBlocks()); + assertEquals(0, result.getCommittedBlocks().size()); + assertNotNull(result.getUncommittedBlocks()); + assertEquals(0, result.getUncommittedBlocks().size()); + } + + @Test + public void listBlobBlocksWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String container = TEST_CONTAINER_FOR_BLOBS; + String blob = "test14"; + service.createBlockBlob(container, blob, null); + service.createBlobBlock(container, blob, "123", + new ByteArrayInputStream(new byte[256])); + service.createBlobBlock(container, blob, "124", + new ByteArrayInputStream(new byte[512])); + service.createBlobBlock(container, blob, "125", + new ByteArrayInputStream(new byte[195])); + + ListBlobBlocksResult result = service.listBlobBlocks(container, blob, + new ListBlobBlocksOptions().setCommittedList(true) + .setUncommittedList(true)); + + // Assert + assertNotNull(result); + assertNotNull(result.getLastModified()); + assertNotNull(result.getEtag()); + assertEquals(0, result.getContentLength()); + assertNotNull(result.getCommittedBlocks()); + assertEquals(0, result.getCommittedBlocks().size()); + assertNotNull(result.getUncommittedBlocks()); + assertEquals(3, result.getUncommittedBlocks().size()); + assertEquals("123", result.getUncommittedBlocks().get(0).getBlockId()); + assertEquals(256, result.getUncommittedBlocks().get(0).getBlockLength()); + assertEquals("124", result.getUncommittedBlocks().get(1).getBlockId()); + assertEquals(512, result.getUncommittedBlocks().get(1).getBlockLength()); + assertEquals("125", result.getUncommittedBlocks().get(2).getBlockId()); + assertEquals(195, result.getUncommittedBlocks().get(2).getBlockLength()); + } + + @Test + public void listBlobBlocksWithOptionsWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String container = TEST_CONTAINER_FOR_BLOBS; + String blob = "test14"; + service.createBlockBlob(container, blob, null); + service.createBlobBlock(container, blob, "123", + new ByteArrayInputStream(new byte[256])); + + BlockList blockList = new BlockList(); + blockList.addUncommittedEntry("123"); + service.commitBlobBlocks(container, blob, blockList); + + service.createBlobBlock(container, blob, "124", + new ByteArrayInputStream(new byte[512])); + service.createBlobBlock(container, blob, "125", + new ByteArrayInputStream(new byte[195])); + + ListBlobBlocksResult result1 = service.listBlobBlocks(container, blob, + new ListBlobBlocksOptions().setCommittedList(true) + .setUncommittedList(true)); + ListBlobBlocksResult result2 = service.listBlobBlocks(container, blob, + new ListBlobBlocksOptions().setCommittedList(true)); + ListBlobBlocksResult result3 = service.listBlobBlocks(container, blob, + new ListBlobBlocksOptions().setUncommittedList(true)); + + // Assert + assertEquals(1, result1.getCommittedBlocks().size()); + assertEquals(2, result1.getUncommittedBlocks().size()); + + assertEquals(1, result2.getCommittedBlocks().size()); + assertEquals(0, result2.getUncommittedBlocks().size()); + + assertEquals(0, result3.getCommittedBlocks().size()); + assertEquals(2, result3.getUncommittedBlocks().size()); + } + + @Test + public void commitBlobBlocksWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String container = TEST_CONTAINER_FOR_BLOBS; + String blob = "test14"; + String blockId1 = "1fedcba"; + String blockId2 = "2abcdef"; + String blockId3 = "3zzzzzz"; + service.createBlockBlob(container, blob, null); + service.createBlobBlock(container, blob, blockId1, + new ByteArrayInputStream(new byte[256])); + service.createBlobBlock(container, blob, blockId2, + new ByteArrayInputStream(new byte[512])); + service.createBlobBlock(container, blob, blockId3, + new ByteArrayInputStream(new byte[195])); + + BlockList blockList = new BlockList(); + blockList.addUncommittedEntry(blockId1).addLatestEntry(blockId3); + service.commitBlobBlocks(container, blob, blockList); + + ListBlobBlocksResult result = service.listBlobBlocks(container, blob, + new ListBlobBlocksOptions().setCommittedList(true) + .setUncommittedList(true)); + + // Assert + assertNotNull(result); + assertNotNull(result.getLastModified()); + assertNotNull(result.getEtag()); + assertEquals(256 + 195, result.getContentLength()); + + assertNotNull(result.getCommittedBlocks()); + assertEquals(2, result.getCommittedBlocks().size()); + assertEquals(blockId1, result.getCommittedBlocks().get(0).getBlockId()); + assertEquals(256, result.getCommittedBlocks().get(0).getBlockLength()); + assertEquals(blockId3, result.getCommittedBlocks().get(1).getBlockId()); + assertEquals(195, result.getCommittedBlocks().get(1).getBlockLength()); + + assertNotNull(result.getUncommittedBlocks()); + assertEquals(0, result.getUncommittedBlocks().size()); + } + + @Test + public void createBlobBlockWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String container = TEST_CONTAINER_FOR_BLOBS; + String blob = "test13"; + String content = new String(new char[512]); + service.createBlockBlob(container, blob, new ByteArrayInputStream( + content.getBytes("UTF-8"))); + service.createBlobBlock(container, blob, "123", + new ByteArrayInputStream(content.getBytes("UTF-8"))); + service.createBlobBlock(container, blob, "124", + new ByteArrayInputStream(content.getBytes("UTF-8"))); + + // Assert + } + + @Test + public void createBlobBlockNullContainerWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String container = null; + String blob = "createblobblocknullcontainerworks"; + String content = new String(new char[512]); + service.createBlockBlob(container, blob, new ByteArrayInputStream( + content.getBytes("UTF-8"))); + GetBlobPropertiesResult result = service.getBlobProperties(null, blob); + GetBlobResult getBlobResult = service.getBlob(null, blob); + + // Assert + assertNotNull(result); + assertNotNull(result.getMetadata()); + assertEquals(0, result.getMetadata().size()); + BlobProperties props = result.getProperties(); + assertNotNull(props); + + assertEquals(content, + inputStreamToString(getBlobResult.getContentStream(), "UTF-8")); + } + + @Test + public void createBlockBlobWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test2", + new ByteArrayInputStream("some content".getBytes())); + + // Assert + } + + @Test + public void createBlockBlobWithValidEtag() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + CreateBlobResult createBlobResult = service.createBlockBlob( + TEST_CONTAINER_FOR_BLOBS, "test2", new ByteArrayInputStream( + "some content".getBytes())); + + // Assert + assertNotNull(createBlobResult); + assertNotNull(createBlobResult.getEtag()); + } + + @Test + public void createBlockBlobWithOptionsWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String content = "some content"; + service.createBlockBlob( + TEST_CONTAINER_FOR_BLOBS, + "test2", + new ByteArrayInputStream(content.getBytes("UTF-8")), + new CreateBlobOptions() + .setBlobCacheControl("test") + .setBlobContentEncoding("UTF-8") + .setBlobContentLanguage("en-us") + /* .setBlobContentMD5("1234") */.setBlobContentType( + "text/plain") + .setCacheControl("test") + .setContentEncoding("UTF-8") + /* .setContentMD5("1234") */.setContentType( + "text/plain")); + + GetBlobPropertiesResult result = service.getBlobProperties( + TEST_CONTAINER_FOR_BLOBS, "test2"); + + // Assert + assertNotNull(result); + + assertNotNull(result.getMetadata()); + assertEquals(0, result.getMetadata().size()); + + BlobProperties props = result.getProperties(); + assertNotNull(props); + assertEquals("test", props.getCacheControl()); + assertEquals("UTF-8", props.getContentEncoding()); + assertEquals("en-us", props.getContentLanguage()); + assertEquals("text/plain", props.getContentType()); + assertEquals(content.length(), props.getContentLength()); + assertNotNull(props.getEtag()); + assertNull(props.getContentMD5()); + assertNotNull(props.getLastModified()); + assertEquals("BlockBlob", props.getBlobType()); + assertEquals("unlocked", props.getLeaseStatus()); + assertEquals(0, props.getSequenceNumber()); + } + + @Test + public void getBlockBlobWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String content = "some content"; + service.createBlockBlob( + TEST_CONTAINER_FOR_BLOBS, + "test2", + new ByteArrayInputStream(content.getBytes("UTF-8")), + new CreateBlobOptions() + .setBlobCacheControl("test") + .setBlobContentEncoding("UTF-8") + .setBlobContentLanguage("en-us") + /* .setBlobContentMD5("1234") */.setBlobContentType( + "text/plain") + .setCacheControl("test") + .setContentEncoding("UTF-8") + /* .setContentMD5("1234") */.setContentType( + "text/plain")); + + GetBlobResult result = service.getBlob(TEST_CONTAINER_FOR_BLOBS, + "test2"); + + // Assert + assertNotNull(result); + + assertNotNull(result.getMetadata()); + assertEquals(0, result.getMetadata().size()); + + BlobProperties props = result.getProperties(); + assertNotNull(props); + assertEquals("test", props.getCacheControl()); + assertEquals("UTF-8", props.getContentEncoding()); + assertEquals("en-us", props.getContentLanguage()); + assertEquals("text/plain", props.getContentType()); + assertEquals(content.length(), props.getContentLength()); + assertNotNull(props.getEtag()); + assertNull(props.getContentMD5()); + assertNotNull(props.getLastModified()); + assertEquals("BlockBlob", props.getBlobType()); + assertEquals("unlocked", props.getLeaseStatus()); + assertEquals(0, props.getSequenceNumber()); + assertEquals(content, + inputStreamToString(result.getContentStream(), "UTF-8")); + } + + @Test + public void deleteBlobWorks() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + String content = "some content"; + service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test2", + new ByteArrayInputStream(content.getBytes("UTF-8"))); + + service.deleteBlob(TEST_CONTAINER_FOR_BLOBS, "test2"); + + // Assert + } + + class RetryPolicyObserver implements ServiceFilter { + public int requestCount; + + @Override + public ServiceResponseContext handle(ServiceRequestContext request, + Next next) throws Exception { + requestCount++; + return next.handle(request); + } + } + + private class NonResetableInputStream extends FilterInputStream { + + protected NonResetableInputStream(InputStream in) { + super(in); + } + + @Override + public boolean markSupported() { + return false; + } + } + + @Test + public void retryPolicyThrowsOnInvalidInputStream() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + service = service.withFilter(new RetryPolicyFilter( + new ExponentialRetryPolicy(100/* deltaBackoff */, + 3/* maximumAttempts */, new int[] { 400, 500, 503 }))); + + Exception error = null; + try { + String content = "foo"; + InputStream contentStream = new ByteArrayInputStream( + content.getBytes("UTF-8")); + InputStream stream = new NonResetableInputStream(contentStream); + + service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "testretry", + stream); + } catch (Exception e) { + error = e; + } + + // Assert + assertNotNull(error); + } + + private class ResetableInputStream extends FilterInputStream { + private boolean resetCalled; + + protected ResetableInputStream(InputStream in) { + super(in); + } + + @Override + public void reset() throws IOException { + super.reset(); + setResetCalled(true); + } + + public boolean isResetCalled() { + return resetCalled; + } + + public void setResetCalled(boolean resetCalled) { + this.resetCalled = resetCalled; + } + } + + @Test + public void retryPolicyCallsResetOnValidInputStream() throws Exception { + // Arrange + Configuration config = createConfiguration(); + BlobContract service = BlobService.create(config); + + // Act + service = service.withFilter(new RetryPolicyFilter( + new ExponentialRetryPolicy(100/* deltaBackoff */, + 3/* maximumAttempts */, new int[] { 403 }))); + + ServiceException error = null; + ResetableInputStream stream = null; + try { + String content = "foo"; + InputStream contentStream = new ByteArrayInputStream( + content.getBytes("UTF-8")); + stream = new ResetableInputStream(contentStream); + + service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, + "invalidblobname @#$#@$@", stream); + } catch (ServiceException e) { + error = e; + } + + // Assert + assertNotNull(error); + assertEquals(403, error.getHttpStatusCode()); + assertNotNull(stream); + assertTrue(stream.isResetCalled()); + } + + private String inputStreamToString(InputStream inputStream, String encoding) + throws IOException { + Writer writer = new StringWriter(); + + char[] buffer = new char[1024]; + try { + Reader reader = new BufferedReader(new InputStreamReader( + inputStream, encoding)); + while (true) { + int n = reader.read(buffer); + if (n == -1) + break; + writer.write(buffer, 0, n); + } + } finally { + inputStream.close(); + } + return writer.toString(); + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/blob/IntegrationTestBase.java b/media/src/test/java/com/microsoft/windowsazure/services/blob/IntegrationTestBase.java new file mode 100644 index 0000000000000..2d207e5bfa1eb --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/blob/IntegrationTestBase.java @@ -0,0 +1,45 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.blob; + +import com.microsoft.windowsazure.Configuration; + +public abstract class IntegrationTestBase { + protected static Configuration createConfiguration() { + Configuration config = Configuration.getInstance(); + overrideWithEnv(config, BlobConfiguration.ACCOUNT_NAME); + overrideWithEnv(config, BlobConfiguration.ACCOUNT_KEY); + overrideWithEnv(config, BlobConfiguration.URI); + return config; + } + + private static void overrideWithEnv(Configuration config, String key) { + String value = System.getenv(key); + if (value == null) + return; + + config.setProperty(key, value); + } + + protected static boolean isRunningWithEmulator(Configuration config) { + String accountName = "devstoreaccount1"; + String accountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; + + return accountName.equals(config + .getProperty(BlobConfiguration.ACCOUNT_NAME)) + && accountKey.equals(config + .getProperty(BlobConfiguration.ACCOUNT_KEY)); + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/AccessPolicyIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/AccessPolicyIntegrationTest.java new file mode 100644 index 0000000000000..b6a1e5ce37bd7 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/AccessPolicyIntegrationTest.java @@ -0,0 +1,240 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; + +import org.junit.Test; + +import com.microsoft.windowsazure.core.pipeline.jersey.ExponentialRetryPolicy; +import com.microsoft.windowsazure.core.pipeline.jersey.RetryPolicyFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.AccessPolicy; +import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; +import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; + +public class AccessPolicyIntegrationTest extends IntegrationTestBase { + private void verifyInfosEqual(String message, AccessPolicyInfo expected, + AccessPolicyInfo actual) { + verifyPolicyProperties(message, expected.getName(), + expected.getDurationInMinutes(), expected.getPermissions(), + actual); + } + + private void verifyPolicyProperties(String message, String testName, + double duration, AccessPolicyPermission permission, + AccessPolicyInfo policy) { + verifyPolicyProperties(message, testName, duration, + EnumSet.of(permission), policy); + } + + private void verifyPolicyProperties(String message, String testName, + double duration, EnumSet permissions, + AccessPolicyInfo policy) { + assertNotNull(message, policy); + assertEquals(message + " Name", testName, policy.getName()); + assertEquals(message + " DurationInMinutes", duration, + policy.getDurationInMinutes(), 0.00001); + for (AccessPolicyPermission permission : permissions) { + if (permission != AccessPolicyPermission.NONE) { + assertTrue( + message + "permissions should contain " + permission, + policy.getPermissions().contains(permission)); + } + } + assertEquals(message + " Permissions", permissions, + policy.getPermissions()); + + assertNotNull(message + " Id", policy.getId()); + assertNotNull(message + " Created", policy.getCreated()); + assertNotNull(message + " LastModified", policy.getLastModified()); + assertEquals(message + " Created & LastModified", policy.getCreated(), + policy.getLastModified()); + } + + @Test + public void canCreateAccessPolicy() throws Exception { + String testName = testPolicyPrefix + "CanCreate"; + double duration = 5; + + AccessPolicyInfo policy = service.create(AccessPolicy.create(testName, + duration, EnumSet.of(AccessPolicyPermission.WRITE))); + + verifyPolicyProperties("policy", testName, duration, + AccessPolicyPermission.WRITE, policy); + } + + @Test + public void canCreateAccessPolicyWithReadPermissions() throws Exception { + String testName = testPolicyPrefix + "CanCreateRead"; + double duration = 5; + + AccessPolicyInfo policy = service.create(AccessPolicy.create(testName, + duration, EnumSet.of(AccessPolicyPermission.READ))); + + verifyPolicyProperties("policy", testName, duration, + AccessPolicyPermission.READ, policy); + } + + @Test + public void canGetSinglePolicyById() throws Exception { + String expectedName = testPolicyPrefix + "GetOne"; + double duration = 1; + AccessPolicyInfo policyToGet = service.create(AccessPolicy.create( + expectedName, duration, + EnumSet.of(AccessPolicyPermission.WRITE))); + + AccessPolicyInfo retrievedPolicy = service.get(AccessPolicy + .get(policyToGet.getId())); + + assertEquals(policyToGet.getId(), retrievedPolicy.getId()); + verifyPolicyProperties("retrievedPolicy", expectedName, duration, + AccessPolicyPermission.WRITE, retrievedPolicy); + } + + @Test + public void canGetSinglePolicyByInvalidId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.get(AccessPolicy.get(invalidId)); + } + + @Test + public void canGetSinglePolicyByNonexistId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(AccessPolicy.get(validButNonexistAccessPolicyId)); + } + + @Test + public void canRetrieveListOfAccessPolicies() throws Exception { + String[] policyNames = new String[] { testPolicyPrefix + "ListOne", + testPolicyPrefix + "ListTwo" }; + double duration = 3; + EnumSet permissions = EnumSet.of( + AccessPolicyPermission.WRITE, AccessPolicyPermission.LIST); + + List expectedAccessPolicies = new ArrayList(); + for (int i = 0; i < policyNames.length; i++) { + AccessPolicyInfo policy = service.create(AccessPolicy.create( + policyNames[i], duration, permissions)); + expectedAccessPolicies.add(policy); + } + + List actualAccessPolicies = service.list(AccessPolicy + .list()); + + verifyListResultContains("listAccessPolicies", expectedAccessPolicies, + actualAccessPolicies, new ComponentDelegate() { + @Override + public void verifyEquals(String message, Object expected, + Object actual) { + verifyInfosEqual(message, (AccessPolicyInfo) expected, + (AccessPolicyInfo) actual); + } + }); + } + + @Test + public void canUseQueryParametersWhenListingAccessPolicies() + throws Exception { + String[] policyNames = new String[] { testPolicyPrefix + "ListThree", + testPolicyPrefix + "ListFour", testPolicyPrefix + "ListFive", + testPolicyPrefix + "ListSix", testPolicyPrefix + "ListSeven" }; + + double duration = 3; + EnumSet permissions = EnumSet.of( + AccessPolicyPermission.WRITE, AccessPolicyPermission.LIST); + + List expectedAccessPolicies = new ArrayList(); + for (int i = 0; i < policyNames.length; i++) { + AccessPolicyInfo policy = service.create(AccessPolicy.create( + policyNames[i], duration, permissions)); + expectedAccessPolicies.add(policy); + } + + List actualAccessPolicies = service.list(AccessPolicy + .list().setTop(2)); + + assertEquals(2, actualAccessPolicies.size()); + } + + // Note: Access Policy cannot be updated. + + @Test + public void canDeleteAccessPolicyById() throws Exception { + String policyName = testPolicyPrefix + "ToDelete"; + double duration = 1; + AccessPolicyInfo policyToDelete = service + .create(AccessPolicy.create(policyName, duration, + EnumSet.of(AccessPolicyPermission.WRITE))); + List listPoliciesResult = service.list(AccessPolicy + .list()); + int policyCountBaseline = listPoliciesResult.size(); + + service.delete(AccessPolicy.delete(policyToDelete.getId())); + + listPoliciesResult = service.list(AccessPolicy.list()); + assertEquals("listPoliciesResult.size", policyCountBaseline - 1, + listPoliciesResult.size()); + + for (AccessPolicyInfo policy : service.list(AccessPolicy.list())) { + assertFalse(policyToDelete.getId().equals(policy.getId())); + } + + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(AccessPolicy.get(policyToDelete.getId())); + } + + @Test + public void canDeleteAccessPolicyByInvalidId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.delete(AccessPolicy.delete(invalidId)); + } + + @Test + public void canDeleteAccessPolicyByNonexistId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.delete(AccessPolicy.delete(validButNonexistAccessPolicyId)); + } + + @Test + public void canRetryAccessPolicyCreation() throws Exception { + String name = testPolicyPrefix + "canRetryAccessPolicyCreationPolicy"; + double duration = 1; + EnumSet write = EnumSet + .of(AccessPolicyPermission.WRITE); + service.create(AccessPolicy.create(name + "1", duration, write)); + + ExponentialRetryPolicy forceRetryPolicy = new ExponentialRetryPolicy(1, + 1, new int[] { 201 }); + MediaContract forceRetryService = service + .withFilter(new RetryPolicyFilter(forceRetryPolicy)); + + forceRetryService.create(AccessPolicy.create(name + "2", duration, + write)); + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/AssetFileIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/AssetFileIntegrationTest.java new file mode 100644 index 0000000000000..4e7b7cb969b9b --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/AssetFileIntegrationTest.java @@ -0,0 +1,279 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.EnumSet; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.AccessPolicy; +import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; +import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetFile; +import com.microsoft.windowsazure.services.media.models.AssetFileInfo; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; + +public class AssetFileIntegrationTest extends IntegrationTestBase { + + // Some dummy binary data for uploading + private static byte[] firstPrimes = new byte[] { 2, 3, 5, 7, 11, 13, 17, + 19, 23, 29 }; + private static byte[] onesAndZeros = new byte[] { 1, 0, 1, 0, 1, 0, 1, 0 }; + private static byte[] countingUp = new byte[] { 3, 4, 5, 6, 7, 8, 9, 10, 11 }; + + private static final String BLOB_NAME = "primes.bin"; + private static final String BLOB_NAME_2 = "primes2.bin"; + + private static AccessPolicyInfo writePolicy; + + @BeforeClass + public static void setup() throws Exception { + IntegrationTestBase.setup(); + + writePolicy = createWritePolicy("uploadWritePolicy", 30); + } + + @Test + public void canCreateFileForUploadedBlob() throws Exception { + AssetInfo asset = createTestAsset("createFileForUploadedBlob"); + LocatorInfo locator = createLocator(writePolicy, asset, 5); + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locator); + + createAndUploadBlob(blobWriter, BLOB_NAME, firstPrimes); + + service.action(AssetFile.createFileInfos(asset.getId())); + + ListResult files = service.list(AssetFile.list(asset + .getAssetFilesLink())); + + assertEquals(1, files.size()); + AssetFileInfo file = files.get(0); + assertEquals(BLOB_NAME, file.getName()); + } + + @Test + public void canCreateFileEntityDirectly() throws Exception { + AssetInfo asset = createTestAsset("createFileEntityDirectly"); + LocatorInfo locator = createLocator(writePolicy, asset, 5); + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locator); + + createAndUploadBlob(blobWriter, BLOB_NAME_2, firstPrimes); + + service.create(AssetFile.create(asset.getId(), BLOB_NAME_2)); + + ListResult files = service.list(AssetFile.list(asset + .getAssetFilesLink())); + + boolean found = false; + for (AssetFileInfo file : files) { + if (file.getName().equals(BLOB_NAME_2)) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void canCreateAssetWithMultipleFiles() throws Exception { + AssetInfo asset = createTestAsset("createWithMultipleFiles"); + AccessPolicyInfo policy = createWritePolicy("createWithMultipleFiles", + 10); + LocatorInfo locator = createLocator(policy, asset, 5); + + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locator); + + createAndUploadBlob(blobWriter, "blob1.bin", firstPrimes); + createAndUploadBlob(blobWriter, "blob2.bin", onesAndZeros); + createAndUploadBlob(blobWriter, "blob3.bin", countingUp); + + AssetFileInfo file1 = service.create(AssetFile + .create(asset.getId(), "blob1.bin").setIsPrimary(true) + .setIsEncrypted(false) + .setContentFileSize(new Long(firstPrimes.length))); + + AssetFileInfo file2 = service.create(AssetFile + .create(asset.getId(), "blob2.bin").setIsPrimary(false) + .setIsEncrypted(false) + .setContentFileSize(new Long(onesAndZeros.length))); + + AssetFileInfo file3 = service.create(AssetFile + .create(asset.getId(), "blob3.bin").setIsPrimary(false) + .setIsEncrypted(false) + .setContentFileSize(new Long(countingUp.length)) + .setContentChecksum("1234")); + + ListResult files = service.list(AssetFile.list(asset + .getAssetFilesLink())); + + assertEquals(3, files.size()); + + ArrayList results = new ArrayList(files); + Collections.sort(results, new Comparator() { + @Override + public int compare(AssetFileInfo o1, AssetFileInfo o2) { + return o1.getName().compareTo(o2.getName()); + } + }); + + assertAssetFileInfoEquals("results.get(0)", file1, results.get(0)); + assertAssetFileInfoEquals("results.get(1)", file2, results.get(1)); + assertAssetFileInfoEquals("results.get(2)", file3, results.get(2)); + } + + @Test + public void canCreateFileAndThenUpdateIt() throws Exception { + AssetInfo asset = createTestAsset("createAndUpdate"); + AccessPolicyInfo policy = createWritePolicy("createAndUpdate", 10); + LocatorInfo locator = createLocator(policy, asset, 5); + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locator); + + createAndUploadBlob(blobWriter, "toUpdate.bin", firstPrimes); + + AssetFileInfo file = service.create(AssetFile.create(asset.getId(), + "toUpdate.bin")); + + service.update(AssetFile.update(file.getId()).setMimeType( + "application/octet-stream")); + + AssetFileInfo fromServer = service.get(AssetFile.get(file.getId())); + + assertEquals("application/octet-stream", fromServer.getMimeType()); + } + + @Test + public void canDeleteFileFromAsset() throws Exception { + AssetInfo asset = createTestAsset("deleteFile"); + AccessPolicyInfo policy = createWritePolicy("deleteFile", 10); + LocatorInfo locator = createLocator(policy, asset, 5); + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locator); + + createAndUploadBlob(blobWriter, "todelete.bin", firstPrimes); + createAndUploadBlob(blobWriter, "tokeep.bin", onesAndZeros); + + service.action(AssetFile.createFileInfos(asset.getId())); + + ListResult originalFiles = service.list(AssetFile + .list(asset.getAssetFilesLink())); + assertEquals(2, originalFiles.size()); + + for (AssetFileInfo file : originalFiles) { + if (file.getName().equals("todelete.bin")) { + service.delete(AssetFile.delete(file.getId())); + break; + } + } + + ListResult newFiles = service.list(AssetFile.list(asset + .getAssetFilesLink())); + assertEquals(1, newFiles.size()); + assertEquals("tokeep.bin", newFiles.get(0).getName()); + } + + // + // Helper functions to create various media services entities + // + private static AssetInfo createTestAsset(String name) + throws ServiceException { + return service.create(Asset.create().setName(testAssetPrefix + name)); + } + + private static AccessPolicyInfo createWritePolicy(String name, + int durationInMinutes) throws ServiceException { + return service.create(AccessPolicy.create(testPolicyPrefix + name, + durationInMinutes, EnumSet.of(AccessPolicyPermission.WRITE))); + } + + private static void createAndUploadBlob( + WritableBlobContainerContract blobWriter, String blobName, + byte[] data) throws ServiceException { + InputStream blobContent = new ByteArrayInputStream(data); + blobWriter.createBlockBlob(blobName, blobContent); + } + + // + // Assertion helpers + // + + private void assertAssetFileInfoEquals(String message, + AssetFileInfo expected, AssetFileInfo actual) { + verifyAssetInfoProperties(message, expected.getId(), + expected.getName(), expected.getParentAssetId(), + expected.getIsPrimary(), expected.getIsEncrypted(), + expected.getEncryptionKeyId(), expected.getEncryptionScheme(), + expected.getEncryptionVersion(), + expected.getInitializationVector(), expected.getCreated(), + expected.getLastModified(), expected.getContentChecksum(), + expected.getMimeType(), actual); + } + + private void verifyAssetInfoProperties(String message, String id, + String name, String parentAssetId, boolean isPrimary, + boolean isEncrypted, String encryptionKeyId, + String encryptionScheme, String encryptionVersion, + String initializationVector, Date created, Date lastModified, + String contentChecksum, String mimeType, AssetFileInfo assetFile) { + assertNotNull(message, assetFile); + + assertEquals(message + ".getId", id, assetFile.getId()); + assertEquals(message + ".getName", name, assetFile.getName()); + assertEquals(message + ".getParentAssetId", parentAssetId, + assetFile.getParentAssetId()); + assertEquals(message + ".getIsPrimary", isPrimary, + assetFile.getIsPrimary()); + + assertEquals(message + ".getIsEncrypted", isEncrypted, + assetFile.getIsEncrypted()); + assertEquals(message + ".getEncryptionKeyId", encryptionKeyId, + assetFile.getEncryptionKeyId()); + assertEquals(message + ".getEncryptionScheme", encryptionScheme, + assetFile.getEncryptionScheme()); + assertEquals(message + ".getEncryptionVersion", encryptionVersion, + assetFile.getEncryptionVersion()); + assertEquals(message + ".getInitializationVector", + initializationVector, assetFile.getInitializationVector()); + + assertDateApproxEquals(message + ".getCreated", created, + assetFile.getCreated()); + assertDateApproxEquals(message + ".getLastModified", lastModified, + assetFile.getLastModified()); + assertEquals(message + ".getContentChecksum", contentChecksum, + assetFile.getContentChecksum()); + assertEquals(message + ".getMimeType", mimeType, + assetFile.getMimeType()); + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/AssetIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/AssetIntegrationTest.java new file mode 100644 index 0000000000000..e887fc2fe3c27 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/AssetIntegrationTest.java @@ -0,0 +1,412 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.InputStream; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; + +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.AccessPolicy; +import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; +import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetFile; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.AssetOption; +import com.microsoft.windowsazure.services.media.models.AssetState; +import com.microsoft.windowsazure.services.media.models.ContentKey; +import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; +import com.microsoft.windowsazure.services.media.models.ContentKeyType; +import com.microsoft.windowsazure.services.media.models.Job; +import com.microsoft.windowsazure.services.media.models.JobInfo; +import com.microsoft.windowsazure.services.media.models.LinkInfo; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.Locator; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; +import com.microsoft.windowsazure.services.media.models.LocatorType; +import com.microsoft.windowsazure.services.media.models.ProtectionKey; +import com.microsoft.windowsazure.services.media.models.Task; +import com.microsoft.windowsazure.services.media.models.Task.CreateBatchOperation; + +public class AssetIntegrationTest extends IntegrationTestBase { + + private void verifyInfosEqual(String message, AssetInfo expected, + AssetInfo actual) { + verifyAssetProperties(message, expected.getName(), + expected.getAlternateId(), expected.getOptions(), + expected.getState(), actual); + } + + private void verifyAssetProperties(String message, String testName, + String altId, AssetOption encryptionOption, AssetState assetState, + AssetInfo actualAsset) { + verifyAssetProperties(message, testName, altId, encryptionOption, + assetState, null, null, null, actualAsset); + } + + private void verifyAssetProperties(String message, String testName, + String altId, AssetOption encryptionOption, AssetState assetState, + String id, Date created, Date lastModified, AssetInfo actualAsset) { + assertNotNull(message, actualAsset); + assertEquals(message + " Name", testName, actualAsset.getName()); + assertEquals(message + " AlternateId", altId, + actualAsset.getAlternateId()); + assertEquals(message + " Options", encryptionOption, + actualAsset.getOptions()); + assertEquals(message + " State", assetState, actualAsset.getState()); + if (id != null) { + assertEquals(message + " Id", id, actualAsset.getId()); + } + if (created != null) { + assertEquals(message + " Created", created, + actualAsset.getCreated()); + } + if (lastModified != null) { + assertEquals(message + " LastModified", lastModified, + actualAsset.getLastModified()); + } + } + + @Test + public void createAssetOptionsSuccess() throws Exception { + // Arrange + String testName = testAssetPrefix + "createAssetOptionsSuccess"; + String altId = "altId"; + AssetOption encryptionOption = AssetOption.StorageEncrypted; + AssetState assetState = AssetState.Published; + + // Act + AssetInfo actualAsset = service.create(Asset.create() + .setAlternateId(altId).setOptions(encryptionOption) + .setState(assetState).setName(testName)); + + // Assert + verifyAssetProperties("actualAsset", testName, altId, encryptionOption, + assetState, actualAsset); + } + + @Test + public void createAssetMeanString() throws Exception { + // Arrange + String meanString = "'\"(?++\\+&==/&?''$@:// +ne " + + "{\"jsonLike\":\"Created\":\"\\/Date(1336368841597)\\/\",\"Name\":null,cksum value\"}}" + + "Some unicode: \uB2E4\uB974\uB2E4\uB294\u0625 \u064A\u062F\u064A\u0648\u0009\r\n"; + + String testName = testAssetPrefix + "createAssetMeanString" + + meanString; + + // Act + AssetInfo actualAsset = service + .create(Asset.create().setName(testName)); + + // Assert + assertEquals("actualAsset Name", testName, actualAsset.getName()); + } + + @Test + public void createAssetNullNameSuccess() throws Exception { + // Arrange + + // Act + AssetInfo actualAsset = null; + try { + actualAsset = service.create(Asset.create()); + // Assert + verifyAssetProperties("actualAsset", "", "", AssetOption.None, + AssetState.Initialized, actualAsset); + } finally { + // Clean up the anonymous asset now while we have the id, because we + // do not want to delete all anonymous assets in the bulk-cleanup + // code. + try { + if (actualAsset != null) { + service.delete(Asset.delete(actualAsset.getId())); + } + } catch (ServiceException ex) { + // ex.printStackTrace(); + } + } + } + + @Test + public void getAssetSuccess() throws Exception { + // Arrange + String testName = testAssetPrefix + "GetAssetSuccess"; + String altId = "altId"; + AssetOption encryptionOption = AssetOption.StorageEncrypted; + AssetState assetState = AssetState.Published; + + AssetInfo assetInfo = service.create(Asset.create().setName(testName) + .setAlternateId(altId).setOptions(encryptionOption) + .setState(assetState)); + + // Act + AssetInfo actualAsset = service.get(Asset.get(assetInfo.getId())); + + // Assert + verifyInfosEqual("actualAsset", assetInfo, actualAsset); + } + + @Test + public void getAssetInvalidId() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.get(Asset.get(invalidId)); + } + + @Test + public void getAssetNonexistId() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(Asset.get(validButNonexistAssetId)); + } + + @Test + public void listAssetSuccess() throws ServiceException { + // Arrange + String altId = "altId"; + AssetOption encryptionOption = AssetOption.StorageEncrypted; + AssetState assetState = AssetState.Published; + + String[] assetNames = new String[] { testAssetPrefix + "assetA", + testAssetPrefix + "assetB" }; + List expectedAssets = new ArrayList(); + for (int i = 0; i < assetNames.length; i++) { + String name = assetNames[i]; + expectedAssets.add(service.create(Asset.create().setName(name) + .setAlternateId(altId).setOptions(encryptionOption) + .setState(assetState))); + } + + // Act + Collection listAssetResult = service.list(Asset.list()); + + // Assert + + verifyListResultContains("listAssets", expectedAssets, listAssetResult, + new ComponentDelegate() { + @Override + public void verifyEquals(String message, Object expected, + Object actual) { + verifyInfosEqual(message, (AssetInfo) expected, + (AssetInfo) actual); + } + }); + } + + @Test + public void canListAssetsWithOptions() throws ServiceException { + String[] assetNames = new String[] { + testAssetPrefix + "assetListOptionsA", + testAssetPrefix + "assetListOptionsB", + testAssetPrefix + "assetListOptionsC", + testAssetPrefix + "assetListOptionsD" }; + List expectedAssets = new ArrayList(); + for (int i = 0; i < assetNames.length; i++) { + String name = assetNames[i]; + expectedAssets.add(service.create(Asset.create().setName(name))); + } + + Collection listAssetResult = service.list(Asset.list() + .setTop(2)); + + // Assert + + assertEquals(2, listAssetResult.size()); + } + + @Test + public void updateAssetSuccess() throws Exception { + // Arrange + String originalTestName = testAssetPrefix + + "updateAssetSuccessOriginal"; + AssetOption originalEncryptionOption = AssetOption.StorageEncrypted; + AssetState originalAssetState = AssetState.Initialized; + AssetInfo originalAsset = service.create(Asset.create() + .setName(originalTestName).setAlternateId("altId") + .setOptions(originalEncryptionOption)); + + String updatedTestName = testAssetPrefix + "updateAssetSuccessUpdated"; + String altId = "otherAltId"; + + // Act + service.update(Asset.update(originalAsset.getId()) + .setName(updatedTestName).setAlternateId(altId)); + AssetInfo updatedAsset = service.get(Asset.get(originalAsset.getId())); + + // Assert + verifyAssetProperties("updatedAsset", updatedTestName, altId, + originalEncryptionOption, originalAssetState, updatedAsset); + } + + @Test + public void updateAssetNoChangesSuccess() throws Exception { + // Arrange + String originalTestName = testAssetPrefix + + "updateAssetNoChangesSuccess"; + String altId = "altId"; + AssetInfo originalAsset = service.create(Asset.create() + .setName(originalTestName).setAlternateId(altId)); + + // Act + service.update(Asset.update(originalAsset.getId())); + AssetInfo updatedAsset = service.get(Asset.get(originalAsset.getId())); + + // Assert + verifyInfosEqual("updatedAsset", originalAsset, updatedAsset); + } + + @Test + public void updateAssetFailedWithInvalidId() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.update(Asset.update(validButNonexistAssetId)); + } + + @Test + public void deleteAssetSuccess() throws Exception { + // Arrange + String assetName = testAssetPrefix + "deleteAssetSuccess"; + AssetInfo assetInfo = service.create(Asset.create().setName(assetName)); + List listAssetsResult = service.list(Asset.list()); + int assetCountBaseline = listAssetsResult.size(); + + // Act + service.delete(Asset.delete(assetInfo.getId())); + + // Assert + listAssetsResult = service.list(Asset.list()); + assertEquals("listAssetsResult.size", assetCountBaseline - 1, + listAssetsResult.size()); + + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(Asset.get(assetInfo.getId())); + } + + @Test + public void deleteAssetFailedWithInvalidId() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.delete(Asset.delete(validButNonexistAssetId)); + } + + @Test + public void linkAssetContentKeySuccess() throws ServiceException, + URISyntaxException { + // Arrange + String originalTestName = testAssetPrefix + + "linkAssetContentKeySuccess"; + AssetInfo assetInfo = service.create(Asset.create() + .setName(originalTestName) + .setOptions(AssetOption.StorageEncrypted)); + + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(ContentKeyType.StorageEncryption)); + String contentKeyId = String + .format("nb:kid:UUID:%s", UUID.randomUUID()); + String encryptedContentKey = "dummyEncryptedContentKey"; + service.create(ContentKey.create(contentKeyId, + ContentKeyType.StorageEncryption, encryptedContentKey) + .setProtectionKeyId(protectionKeyId)); + + // Act + service.action(Asset.linkContentKey(assetInfo.getId(), contentKeyId)); + + // Assert + + List contentKeys = service.list(ContentKey + .list(assetInfo.getContentKeysLink())); + assertEquals(1, contentKeys.size()); + assertEquals(contentKeyId, contentKeys.get(0).getId()); + } + + @Test + public void linkAssetContentKeyInvalidIdFailed() throws ServiceException, + URISyntaxException { + // Arrange + + // Act + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.action(Asset.linkContentKey(validButNonexistAssetId, + "nb:kid:UUID:invalidContentKeyId")); + + // Assert + } + + @Test + public void canGetParentBackFromAsset() throws ServiceException, + InterruptedException { + // Arrange + String originalAssetName = testAssetPrefix + + "canGetParentBackFromAsset"; + AssetInfo originalAsset = service.create(Asset.create().setName( + originalAssetName)); + + int durationInMinutes = 10; + AccessPolicyInfo accessPolicyInfo = service.create(AccessPolicy.create( + testPolicyPrefix + "uploadAesPortectedAssetSuccess", + durationInMinutes, EnumSet.of(AccessPolicyPermission.WRITE))); + + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfo.getId(), originalAsset.getId(), + LocatorType.SAS)); + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locatorInfo); + + InputStream mpeg4H264InputStream = getClass().getResourceAsStream( + "/media/MPEG4-H264.mp4"); + blobWriter.createBlockBlob("MPEG4-H264.mp4", mpeg4H264InputStream); + service.action(AssetFile.createFileInfos(originalAsset.getId())); + + String jobName = testJobPrefix + "createJobSuccess"; + CreateBatchOperation taskCreator = Task + .create(MEDIA_ENCODER_MEDIA_PROCESSOR_ID, + "" + + "JobInputAsset(0)" + + "JobOutputAsset(0)" + + "") + .setConfiguration("H.264 256k DSL CBR") + .setName("My encoding Task"); + JobInfo jobInfo = service.create(Job.create().setName(jobName) + .addInputMediaAsset(originalAsset.getId()) + .addTaskCreator(taskCreator)); + + // Act + ListResult outputAssets = service.list(Asset.list(jobInfo + .getOutputAssetsLink())); + assertEquals(1, outputAssets.size()); + AssetInfo childAsset = outputAssets.get(0); + + LinkInfo parentAssetLink = childAsset.getParentAssetsLink(); + AssetInfo parentAsset = service.get(Asset.get(parentAssetLink)); + + // Assert + assertEquals(originalAsset.getId(), parentAsset.getId()); + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/ContentKeyIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/ContentKeyIntegrationTest.java new file mode 100644 index 0000000000000..0ce3970b0fae1 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/ContentKeyIntegrationTest.java @@ -0,0 +1,374 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.ContentKey; +import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; +import com.microsoft.windowsazure.services.media.models.ContentKeyType; +import com.microsoft.windowsazure.services.media.models.ProtectionKey; +import com.microsoft.windowsazure.services.media.models.ProtectionKeyType; + +public class ContentKeyIntegrationTest extends IntegrationTestBase { + + private final String validButNonexistContentKeyId = "nb:kid:UUID:80dfe751-e5a1-4b29-a992-4a75276473af"; + private final ContentKeyType testContentKeyType = ContentKeyType.CommonEncryption; + private final String testEncryptedContentKey = "bFE4M/kZrKi00AoLOVpbQ4R9xja5P/pfBv9SC9I1Gw8yx+OIWdazGNpT7MgpeOLSebkxO5iDAIUKX5Es6oRUiH6pTNAMEtiHFBrKywODKnTQ09pCAMmdIA4q1gLeEUpsXPY/YXaLsTrBGbmRtlUYyaZEjestsngV8JpkJemCGjmMF0bHCoQRKt0LCVl/cqyWawzBuyaJniUCDdU8jem7sjrw8BbgCDmTAUmaj9TYxEP98d3wEJcL4pzDzOloYWXqzNB9assXgcQ0eouT7onSHa1d76X2E5q16AIIoOndLyIuAxlwFqpzF6LFy3X9mNGEY1iLXeFA89DE0PPx8EHtyg=="; + + private void assertByteArrayEquals(byte[] source, byte[] target) { + assertEquals(source.length, target.length); + for (int i = 0; i < source.length; i++) { + assertEquals(source[i], target[i]); + } + } + + private ContentKeyInfo createTestContentKey(String contentKeyNameSuffix) + throws ServiceException { + String testContentKeyId = createRandomContentKeyId(); + String testContentKeyName = testContentKeyPrefix + contentKeyNameSuffix; + + ContentKeyInfo contentKeyInfo = service.create(ContentKey.create( + testContentKeyId, testContentKeyType, testEncryptedContentKey) + .setName(testContentKeyName)); + return contentKeyInfo; + } + + private ContentKeyInfo createValidTestContentKeyWithAesKey( + String contentKeyNameSuffix, byte[] aesKey) throws Exception { + String testContnetKeyName = testContentKeyPrefix + contentKeyNameSuffix; + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(ContentKeyType.StorageEncryption)); + String protectionKey = service.action(ProtectionKey + .getProtectionKey(protectionKeyId)); + + String testContentKeyIdUuid = UUID.randomUUID().toString(); + String testContentKeyId = String.format("nb:kid:UUID:%s", + testContentKeyIdUuid); + + byte[] encryptedContentKey = EncryptionHelper.encryptSymmetricKey( + protectionKey, aesKey); + String encryptedContentKeyString = Base64.encode(encryptedContentKey); + String checksum = EncryptionHelper.calculateContentKeyChecksum( + testContentKeyIdUuid, aesKey); + + ContentKeyInfo contentKeyInfo = service.create(ContentKey + .create(testContentKeyId, ContentKeyType.StorageEncryption, + encryptedContentKeyString).setChecksum(checksum) + .setProtectionKeyId(protectionKeyId) + .setName(testContnetKeyName)); + + return contentKeyInfo; + } + + private ContentKeyInfo createValidTestContentKey(String contentKeyNameSuffix) + throws Exception { + byte[] aesKey = createTestAesKey(); + return createValidTestContentKeyWithAesKey(contentKeyNameSuffix, aesKey); + } + + private byte[] createTestAesKey() { + byte[] aesKey = new byte[32]; + int i; + for (i = 0; i < 32; i++) { + aesKey[i] = 1; + } + + return aesKey; + } + + private String createRandomContentKeyId() { + UUID uuid = UUID.randomUUID(); + String randomContentKey = String.format("nb:kid:UUID:%s", uuid); + return randomContentKey; + } + + private void verifyInfosEqual(String message, ContentKeyInfo expected, + ContentKeyInfo actual) { + verifyContentKeyProperties(message, expected.getId(), + expected.getContentKeyType(), + expected.getEncryptedContentKey(), expected.getName(), + expected.getProtectionKeyId(), expected.getProtectionKeyType(), + expected.getChecksum(), actual); + } + + private void verifyContentKeyProperties(String message, String id, + ContentKeyType contentKeyType, String encryptedContentKey, + String name, String protectionKeyId, + ProtectionKeyType protectionKeyType, String checksum, + ContentKeyInfo actual) { + assertNotNull(message, actual); + assertEquals(message + " Id", id, actual.getId()); + assertEquals(message + " ContentKeyType", contentKeyType, + actual.getContentKeyType()); + assertEquals(message + " EncryptedContentKey", encryptedContentKey, + actual.getEncryptedContentKey()); + assertEquals(message + " Name", name, actual.getName()); + assertEquals(message + " ProtectionKeyId", protectionKeyId, + actual.getProtectionKeyId()); + assertEquals(message + " ProtectionKeyType", protectionKeyType, + actual.getProtectionKeyType()); + assertEquals(message + " Checksum", checksum, actual.getChecksum()); + } + + @BeforeClass + public static void Setup() { + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + } + + @Test + public void canCreateContentKey() throws Exception { + // Arrange + String testCanCreateContentKeyId = createRandomContentKeyId(); + String testCanCreateContentKeyName = testContentKeyPrefix + + "testCanCreateContentKey"; + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(testContentKeyType)); + + // Act + ContentKeyInfo contentKeyInfo = service.create(ContentKey + .create(testCanCreateContentKeyId, testContentKeyType, + testEncryptedContentKey) + .setName(testCanCreateContentKeyName) + .setProtectionKeyId(protectionKeyId)); + + // Assert + verifyContentKeyProperties("ContentKey", testCanCreateContentKeyId, + testContentKeyType, testEncryptedContentKey, + testCanCreateContentKeyName, protectionKeyId, + ProtectionKeyType.fromCode(0), "", contentKeyInfo); + } + + @Test + public void canGetSingleContentKeyById() throws Exception { + // Arrange + String expectedName = testContentKeyPrefix + "GetOne"; + String testGetSingleContentKeyByIdId = createRandomContentKeyId(); + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(testContentKeyType)); + ContentKeyInfo ContentKeyToGet = service.create(ContentKey + .create(testGetSingleContentKeyByIdId, testContentKeyType, + testEncryptedContentKey).setName(expectedName) + .setProtectionKeyId(protectionKeyId)); + + // Act + ContentKeyInfo retrievedContentKeyInfo = service.get(ContentKey + .get(ContentKeyToGet.getId())); + + // Assert + assertEquals(ContentKeyToGet.getId(), retrievedContentKeyInfo.getId()); + verifyContentKeyProperties("ContentKey", testGetSingleContentKeyByIdId, + testContentKeyType, testEncryptedContentKey, expectedName, + protectionKeyId, ProtectionKeyType.fromCode(0), "", + retrievedContentKeyInfo); + } + + @Test + public void cannotGetSingleContentKeyByInvalidId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.get(ContentKey.get(invalidId)); + } + + @Test + public void canRetrieveListOfContentKeys() throws Exception { + // Arrange + String[] ContentKeyNames = new String[] { + testContentKeyPrefix + "ListOne", + testContentKeyPrefix + "ListTwo" }; + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(testContentKeyType)); + + List expectedContentKeys = new ArrayList(); + for (int i = 0; i < ContentKeyNames.length; i++) { + String testCanRetrieveListOfContentKeysId = createRandomContentKeyId(); + ContentKeyInfo contentKey = service.create(ContentKey.create( + testCanRetrieveListOfContentKeysId, testContentKeyType, + testEncryptedContentKey) + .setProtectionKeyId(protectionKeyId)); + expectedContentKeys.add(contentKey); + } + + // Act + List actualContentKeys = service + .list(ContentKey.list()); + + // Assert + verifyListResultContains("listContentKeyss", expectedContentKeys, + actualContentKeys, new ComponentDelegate() { + @Override + public void verifyEquals(String message, Object expected, + Object actual) { + verifyInfosEqual(message, (ContentKeyInfo) expected, + (ContentKeyInfo) actual); + } + }); + } + + @Test + public void canUseQueryParametersWhenListingContentKeys() throws Exception { + // Arrange + String[] ContentKeyNames = new String[] { + testContentKeyPrefix + "ListThree", + testContentKeyPrefix + "ListFour", + testContentKeyPrefix + "ListFive", + testContentKeyPrefix + "ListSix", + testContentKeyPrefix + "ListSeven" }; + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(testContentKeyType)); + + List expectedContentKeys = new ArrayList(); + for (int i = 0; i < ContentKeyNames.length; i++) { + ContentKeyInfo contentKeyInfo = service.create(ContentKey.create( + createRandomContentKeyId(), testContentKeyType, + testEncryptedContentKey) + .setProtectionKeyId(protectionKeyId)); + expectedContentKeys.add(contentKeyInfo); + } + + // Act + List actualContentKeys = service.list(ContentKey.list() + .setTop(2)); + + // Assert + assertEquals(2, actualContentKeys.size()); + } + + @Test + public void canDeleteContentKeyById() throws Exception { + // Arrange + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(testContentKeyType)); + String contentKeyName = testContentKeyPrefix + "ToDelete"; + ContentKeyInfo contentKeyToDelete = service.create(ContentKey + .create(createRandomContentKeyId(), testContentKeyType, + testEncryptedContentKey).setName(contentKeyName) + .setProtectionKeyId(protectionKeyId)); + List listContentKeysResult = service.list(ContentKey + .list()); + int ContentKeyCountBaseline = listContentKeysResult.size(); + + // Act + service.delete(ContentKey.delete(contentKeyToDelete.getId())); + + // Assert + listContentKeysResult = service.list(ContentKey.list()); + assertEquals("listPoliciesResult.size", ContentKeyCountBaseline - 1, + listContentKeysResult.size()); + + for (ContentKeyInfo contentKey : service.list(ContentKey.list())) { + assertFalse(contentKeyToDelete.getId().equals(contentKey.getId())); + } + + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(ContentKey.get(contentKeyToDelete.getId())); + } + + @Test + public void cannotDeleteContentKeyByInvalidId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.delete(ContentKey.delete(invalidId)); + } + + @Test + public void cannotDeleteContentKeyByNonexistId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.delete(ContentKey.delete(validButNonexistContentKeyId)); + } + + @Test + public void rebindContentKeyNoX509CertificateSuccess() throws Exception { + + ContentKeyInfo contentKeyInfo = createValidTestContentKey("rebindContentKeyNoX509Success"); + + String contentKey = service.action(ContentKey.rebind(contentKeyInfo + .getId())); + assertNotNull(contentKey); + + } + + @Test + public void rebindInvalidContentKeyNoX509CertificateFail() + throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + ContentKeyInfo contentKeyInfo = createTestContentKey("rebindInvalidContentKeyNoX509Fail"); + + service.action(ContentKey.rebind(contentKeyInfo.getId())); + + } + + @Test + public void rebindContentKeyWithX509CertficateSuccess() throws Exception { + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + byte[] aesKey = createTestAesKey(); + ContentKeyInfo contentKeyInfo = createValidTestContentKeyWithAesKey( + "rebindContentKeyWithX509Success", aesKey); + URL serverCertificateUri = getClass().getResource( + "/certificate/server.crt"); + X509Certificate x509Certificate = EncryptionHelper + .loadX509Certificate(URLDecoder.decode( + serverCertificateUri.getFile(), "UTF-8")); + URL serverPrivateKey = getClass() + .getResource("/certificate/server.der"); + PrivateKey privateKey = EncryptionHelper.getPrivateKey(URLDecoder + .decode(serverPrivateKey.getFile(), "UTF-8")); + + String rebindedContentKey = service.action(ContentKey.rebind( + contentKeyInfo.getId(), URLEncoder.encode( + Base64.encode(x509Certificate.getEncoded()), "UTF-8"))); + byte[] decryptedAesKey = EncryptionHelper.decryptSymmetricKey( + rebindedContentKey, privateKey); + assertByteArrayEquals(aesKey, decryptedAesKey); + } + + @Test + public void rebindContentKeyWithIncorrectContentKeyIdFailed() + throws ServiceException { + expectedException.expect(ServiceException.class); + service.action(ContentKey.rebind("invalidContentKeyId")); + } + + @Test + public void rebindContentKeyWithIncorrectX509CertificateFailed() + throws ServiceException { + expectedException.expect(ServiceException.class); + ContentKeyInfo contentKeyInfo = createTestContentKey("rebindContentKeyWithIncorrectX509CertficateFailed"); + + service.action(ContentKey.rebind(contentKeyInfo.getId(), + "InvalidX509Certificate")); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EncryptionHelper.java b/media/src/test/java/com/microsoft/windowsazure/services/media/EncryptionHelper.java similarity index 75% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EncryptionHelper.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/EncryptionHelper.java index 823163c9bbf01..ecf9f4727d276 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EncryptionHelper.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/EncryptionHelper.java @@ -34,7 +34,7 @@ import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; +import com.microsoft.windowsazure.core.utils.Base64; class EncryptionHelper { public static boolean canUseStrongCrypto() { @@ -42,27 +42,33 @@ public static boolean canUseStrongCrypto() { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec secretKeySpec = new SecretKeySpec(new byte[32], "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - } - catch (Exception e) { + } catch (Exception e) { return false; } return true; } - public static byte[] encryptSymmetricKey(String protectionKey, byte[] inputData) throws Exception { + public static byte[] encryptSymmetricKey(String protectionKey, + byte[] inputData) throws Exception { byte[] protectionKeyBytes = Base64.decode(protectionKey); return encryptSymmetricKey(protectionKeyBytes, inputData); } - public static byte[] encryptSymmetricKey(byte[] protectionKey, byte[] inputData) throws Exception { - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(protectionKey); - Certificate certificate = certificateFactory.generateCertificate(byteArrayInputStream); + public static byte[] encryptSymmetricKey(byte[] protectionKey, + byte[] inputData) throws Exception { + CertificateFactory certificateFactory = CertificateFactory + .getInstance("X.509"); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( + protectionKey); + Certificate certificate = certificateFactory + .generateCertificate(byteArrayInputStream); return encryptSymmetricKey(certificate, inputData); } - public static byte[] encryptSymmetricKey(Certificate certificate, byte[] inputData) throws Exception { - Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC"); + public static byte[] encryptSymmetricKey(Certificate certificate, + byte[] inputData) throws Exception { + Cipher cipher = Cipher.getInstance( + "RSA/None/OAEPWithSHA1AndMGF1Padding", "BC"); Key publicKey = certificate.getPublicKey(); SecureRandom secureRandom = new SecureRandom(); cipher.init(Cipher.ENCRYPT_MODE, publicKey, secureRandom); @@ -70,7 +76,8 @@ public static byte[] encryptSymmetricKey(Certificate certificate, byte[] inputDa return cipherText; } - public static String calculateContentKeyChecksum(String uuid, byte[] aesKey) throws Exception { + public static String calculateContentKeyChecksum(String uuid, byte[] aesKey) + throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); @@ -81,54 +88,68 @@ public static String calculateContentKeyChecksum(String uuid, byte[] aesKey) thr return checksum; } - public static InputStream encryptFile(InputStream inputStream, byte[] key, byte[] iv) throws Exception { + public static InputStream encryptFile(InputStream inputStream, byte[] key, + byte[] iv) throws Exception { Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec); - CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher); + CipherInputStream cipherInputStream = new CipherInputStream( + inputStream, cipher); return cipherInputStream; } - public static byte[] decryptSymmetricKey(String encryptedContent, PrivateKey privateKey) throws Exception { + public static byte[] decryptSymmetricKey(String encryptedContent, + PrivateKey privateKey) throws Exception { byte[] encryptedContentByteArray = Base64.decode(encryptedContent); return decryptSymmetricKey(encryptedContentByteArray, privateKey); } - public static byte[] decryptSymmetricKey(byte[] encryptedContent, PrivateKey privateKey) throws Exception { + public static byte[] decryptSymmetricKey(byte[] encryptedContent, + PrivateKey privateKey) throws Exception { if (encryptedContent == null) { - throw new IllegalArgumentException("The encrypted content cannot be null."); + throw new IllegalArgumentException( + "The encrypted content cannot be null."); } if (encryptedContent.length == 0) { - throw new IllegalArgumentException("The encrypted content cannot be empty."); + throw new IllegalArgumentException( + "The encrypted content cannot be empty."); } if (privateKey == null) { - throw new IllegalArgumentException("The private key cannot be null."); + throw new IllegalArgumentException( + "The private key cannot be null."); } - Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC"); + Cipher cipher = Cipher.getInstance( + "RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decrypted = cipher.doFinal(encryptedContent); return decrypted; } - public static X509Certificate loadX509Certificate(String certificateFileName) throws Exception { + public static X509Certificate loadX509Certificate(String certificateFileName) + throws Exception { if ((certificateFileName == null) || certificateFileName.isEmpty()) { - throw new IllegalArgumentException("certificate file name cannot be null or empty."); + throw new IllegalArgumentException( + "certificate file name cannot be null or empty."); } - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - FileInputStream certificateInputStream = new FileInputStream(certificateFileName); + CertificateFactory certificateFactory = CertificateFactory + .getInstance("X.509"); + FileInputStream certificateInputStream = new FileInputStream( + certificateFileName); X509Certificate x509Certificate = (X509Certificate) certificateFactory .generateCertificate(certificateInputStream); return x509Certificate; } - public static PrivateKey getPrivateKey(String certificateFileName) throws Exception { + public static PrivateKey getPrivateKey(String certificateFileName) + throws Exception { if ((certificateFileName == null) || certificateFileName.isEmpty()) { - throw new IllegalArgumentException("certificate file name cannot be null or empty."); + throw new IllegalArgumentException( + "certificate file name cannot be null or empty."); } File file = new File(certificateFileName); @@ -138,7 +159,8 @@ public static PrivateKey getPrivateKey(String certificateFileName) throws Except dataInputStream.readFully(keyBytes); dataInputStream.close(); - PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes); + PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( + keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(pkcs8EncodedKeySpec); } diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/EncryptionIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/EncryptionIntegrationTest.java new file mode 100644 index 0000000000000..75e195968f07f --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/EncryptionIntegrationTest.java @@ -0,0 +1,376 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.net.URL; +import java.net.URLDecoder; +import java.security.Key; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; +import java.util.UUID; + +import javax.crypto.Cipher; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.AccessPolicy; +import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; +import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetFile; +import com.microsoft.windowsazure.services.media.models.AssetFileInfo; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.AssetOption; +import com.microsoft.windowsazure.services.media.models.ContentKey; +import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; +import com.microsoft.windowsazure.services.media.models.ContentKeyType; +import com.microsoft.windowsazure.services.media.models.Job; +import com.microsoft.windowsazure.services.media.models.JobInfo; +import com.microsoft.windowsazure.services.media.models.JobState; +import com.microsoft.windowsazure.services.media.models.LinkInfo; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.Locator; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; +import com.microsoft.windowsazure.services.media.models.LocatorType; +import com.microsoft.windowsazure.services.media.models.MediaProcessor; +import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo; +import com.microsoft.windowsazure.services.media.models.ProtectionKey; +import com.microsoft.windowsazure.services.media.models.Task; +import com.microsoft.windowsazure.services.media.models.TaskInfo; +import com.microsoft.windowsazure.services.media.models.TaskState; + +public class EncryptionIntegrationTest extends IntegrationTestBase { + private final String storageDecryptionProcessor = "Storage Decryption"; + + private void assertByteArrayEquals(byte[] source, byte[] target) { + assertEquals(source.length, target.length); + for (int i = 0; i < source.length; i++) { + assertEquals(source[i], target[i]); + } + } + + @BeforeClass + public static void Setup() { + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + } + + @Test + public void uploadAesProtectedAssetAndDownloadSuccess() throws Exception { + // Arrange + if (!EncryptionHelper.canUseStrongCrypto()) { + throw new UnsupportedOperationException("JVM does not support the required encryption. Please download unlimited strength jurisdiction policy files."); + } + + // Media Services requires 256-bit (32-byte) keys and + // 128-bit (16-byte) initialization vectors (IV) for AES encryption, + // and also requires that only the first 8 bytes of the IV is filled. + Random random = new Random(); + byte[] aesKey = new byte[32]; + random.nextBytes(aesKey); + byte[] effectiveIv = new byte[8]; + random.nextBytes(effectiveIv); + byte[] iv = new byte[16]; + System.arraycopy(effectiveIv, 0, iv, 0, effectiveIv.length); + + InputStream mpeg4H264InputStream = getClass().getResourceAsStream( + "/media/MPEG4-H264.mp4"); + InputStream encryptedContent = EncryptionHelper.encryptFile( + mpeg4H264InputStream, aesKey, iv); + int durationInMinutes = 10; + + // Act + AssetInfo assetInfo = service.create(Asset.create() + .setName(testAssetPrefix + "uploadAesProtectedAssetSuccess") + .setOptions(AssetOption.StorageEncrypted)); + WritableBlobContainerContract blobWriter = getBlobWriter( + assetInfo.getId(), durationInMinutes); + + // gets the public key for storage encryption. + String contentKeyId = createContentKey(aesKey); + + // link the content key with the asset. + service.action(Asset.linkContentKey(assetInfo.getId(), contentKeyId)); + + // upload the encrypted file to the server. + uploadEncryptedAssetFile(assetInfo, blobWriter, "MPEG4-H264.mp4", + encryptedContent, contentKeyId, iv); + + // submit and execute the decoding job. + JobInfo jobInfo = decodeAsset(testJobPrefix + + "uploadAesProtectedAssetSuccess", assetInfo.getId()); + + // assert + LinkInfo taskLinkInfo = jobInfo.getTasksLink(); + List taskInfos = service.list(Task.list(taskLinkInfo)); + for (TaskInfo taskInfo : taskInfos) { + assertEquals(TaskState.Completed, taskInfo.getState()); + ListResult outputs = service.list(Asset.list(taskInfo + .getOutputAssetsLink())); + assertEquals(1, outputs.size()); + } + assertEquals(JobState.Finished, jobInfo.getState()); + + // Verify that the contents match + InputStream expected = getClass().getResourceAsStream( + "/media/MPEG4-H264.mp4"); + + ListResult outputAssets = service.list(Asset.list(jobInfo + .getOutputAssetsLink())); + assertEquals(1, outputAssets.size()); + AssetInfo outputAsset = outputAssets.get(0); + ListResult assetFiles = service.list(AssetFile + .list(assetInfo.getAssetFilesLink())); + assertEquals(1, assetFiles.size()); + AssetFileInfo outputFile = assetFiles.get(0); + + InputStream actual = getFileContents(outputAsset.getId(), + outputFile.getName(), durationInMinutes); + assertStreamsEqual(expected, actual); + } + + @Test + public void testEncryptedContentCanBeDecrypted() throws Exception { + byte[] aesKey = new byte[32]; + for (int i = 0; i < 32; i++) { + aesKey[i] = 1; + } + URL serverCertificateUri = getClass().getResource( + "/certificate/server.crt"); + X509Certificate x509Certificate = EncryptionHelper + .loadX509Certificate(URLDecoder.decode( + serverCertificateUri.getFile(), "UTF-8")); + URL serverPrivateKey = getClass() + .getResource("/certificate/server.der"); + PrivateKey privateKey = EncryptionHelper.getPrivateKey(URLDecoder + .decode(serverPrivateKey.getFile(), "UTF-8")); + byte[] encryptedAesKey = EncryptionHelper.encryptSymmetricKey( + x509Certificate, aesKey); + byte[] decryptedAesKey = EncryptionHelper.decryptSymmetricKey( + encryptedAesKey, privateKey); + + assertByteArrayEquals(aesKey, decryptedAesKey); + } + + @Test + public void testEncryptedContentCanBeDecryptedUsingPreGeneratedKeyPair() + throws Exception { + byte[] input = "abc".getBytes(); + Cipher cipher = Cipher.getInstance( + "RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC"); + SecureRandom random = new SecureRandom(); + URL serverCertificateUri = getClass().getResource( + "/certificate/server.crt"); + X509Certificate x509Certificate = EncryptionHelper + .loadX509Certificate(URLDecoder.decode( + serverCertificateUri.getFile(), "UTF-8")); + URL serverPrivateKey = getClass() + .getResource("/certificate/server.der"); + PrivateKey privateKey = EncryptionHelper.getPrivateKey(URLDecoder + .decode(serverPrivateKey.getFile(), "UTF-8")); + Key pubKey = x509Certificate.getPublicKey(); + cipher.init(Cipher.ENCRYPT_MODE, pubKey, random); + byte[] cipherText = cipher.doFinal(input); + cipher.init(Cipher.DECRYPT_MODE, privateKey); + + // Act + byte[] plainText = cipher.doFinal(cipherText); + + // Assert + assertByteArrayEquals(input, plainText); + } + + @Test + public void testEncryptionDecryptionFunctionUsingGeneratedKeyPair() + throws Exception { + // Arrange + byte[] input = "abc".getBytes(); + Cipher cipher = Cipher.getInstance( + "RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC"); + SecureRandom random = new SecureRandom(); + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC"); + generator.initialize(386, random); + KeyPair pair = generator.generateKeyPair(); + Key pubKey = pair.getPublic(); + Key privKey = pair.getPrivate(); + cipher.init(Cipher.ENCRYPT_MODE, pubKey, random); + byte[] cipherText = cipher.doFinal(input); + cipher.init(Cipher.DECRYPT_MODE, privKey); + + // Act + byte[] plainText = cipher.doFinal(cipherText); + + // Assert + assertByteArrayEquals(input, plainText); + } + + private JobInfo decodeAsset(String name, String inputAssetId) + throws ServiceException, InterruptedException { + MediaProcessorInfo mediaProcessorInfo = service.list( + MediaProcessor.list().set("$filter", + "Name eq '" + storageDecryptionProcessor + "'")).get(0); + + String taskBody = "" + + "JobInputAsset(0)JobOutputAsset(0)"; + JobInfo jobInfo = service.create(Job + .create() + .addInputMediaAsset(inputAssetId) + .addTaskCreator( + Task.create(mediaProcessorInfo.getId(), taskBody) + .setName(name))); + + JobInfo currentJobInfo = jobInfo; + int retryCounter = 0; + while (currentJobInfo.getState().getCode() < 3 && retryCounter < 30) { + Thread.sleep(10000); + currentJobInfo = service.get(Job.get(jobInfo.getId())); + retryCounter++; + } + return currentJobInfo; + } + + private String createContentKey(byte[] aesKey) throws ServiceException, + Exception { + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(ContentKeyType.StorageEncryption)); + String protectionKey = service.action(ProtectionKey + .getProtectionKey(protectionKeyId)); + + String contentKeyIdUuid = UUID.randomUUID().toString(); + String contentKeyId = String.format("nb:kid:UUID:%s", contentKeyIdUuid); + + byte[] encryptedContentKey = EncryptionHelper.encryptSymmetricKey( + protectionKey, aesKey); + String encryptedContentKeyString = Base64.encode(encryptedContentKey); + String checksum = EncryptionHelper.calculateContentKeyChecksum( + contentKeyIdUuid, aesKey); + + ContentKeyInfo contentKeyInfo = service.create(ContentKey + .create(contentKeyId, ContentKeyType.StorageEncryption, + encryptedContentKeyString).setChecksum(checksum) + .setProtectionKeyId(protectionKeyId)); + return contentKeyInfo.getId(); + } + + private void uploadEncryptedAssetFile(AssetInfo asset, + WritableBlobContainerContract blobWriter, String blobName, + InputStream blobContent, String encryptionKeyId, byte[] iv) + throws ServiceException { + blobWriter.createBlockBlob(blobName, blobContent); + service.action(AssetFile.createFileInfos(asset.getId())); + ListResult files = service.list(AssetFile.list( + asset.getAssetFilesLink()).set("$filter", + "Name eq '" + blobName + "'")); + assertEquals(1, files.size()); + AssetFileInfo file = files.get(0); + byte[] sub = new byte[9]; + // Offset bytes to ensure that the sign-bit is not set. + // Media Services expects unsigned Int64 values. + System.arraycopy(iv, 0, sub, 1, 8); + BigInteger longIv = new BigInteger(sub); + String initializationVector = longIv.toString(); + + service.update(AssetFile.update(file.getId()).setIsEncrypted(true) + .setEncryptionKeyId(encryptionKeyId) + .setEncryptionScheme("StorageEncryption") + .setEncryptionVersion("1.0") + .setInitializationVector(initializationVector)); + } + + private WritableBlobContainerContract getBlobWriter(String assetId, + int durationInMinutes) throws ServiceException { + AccessPolicyInfo accessPolicyInfo = service.create(AccessPolicy.create( + testPolicyPrefix + "uploadAesPortectedAssetSuccess", + durationInMinutes, EnumSet.of(AccessPolicyPermission.WRITE))); + + // creates locator for the input media asset + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfo.getId(), assetId, LocatorType.SAS)); + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locatorInfo); + return blobWriter; + } + + private InputStream getFileContents(String assetId, String fileName, + int availabilityWindowInMinutes) throws ServiceException, + InterruptedException, IOException { + AccessPolicyInfo readAP = service.create(AccessPolicy.create( + testPolicyPrefix + "tempAccessPolicy", + availabilityWindowInMinutes, + EnumSet.of(AccessPolicyPermission.READ))); + LocatorInfo readLocator = service.create(Locator.create(readAP.getId(), + assetId, LocatorType.SAS)); + URL file = new URL(readLocator.getBaseUri() + "/" + fileName + + readLocator.getContentAccessToken()); + + // There can be a delay before a new read locator is applied for the + // asset files. + InputStream reader = null; + for (int counter = 0; true; counter++) { + try { + reader = file.openConnection().getInputStream(); + break; + } catch (IOException e) { + System.out.println("Got error, wait a bit and try again"); + if (counter < 6) { + Thread.sleep(10000); + } else { + // No more retries. + throw e; + } + } + } + + return reader; + } + + private void assertStreamsEqual(InputStream inputStream1, + InputStream inputStream2) throws IOException { + byte[] buffer1 = new byte[1024]; + byte[] buffer2 = new byte[1024]; + try { + while (true) { + int n1 = inputStream1.read(buffer1); + int n2 = inputStream2.read(buffer2); + assertEquals("number of bytes read from streams", n1, n2); + if (n1 == -1) { + break; + } + for (int i = 0; i < n1; i++) { + assertEquals("byte " + i + " read from streams", + buffer1[i], buffer2[i]); + } + } + } finally { + inputStream1.close(); + inputStream2.close(); + } + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EntityProxyTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/EntityProxyTest.java similarity index 84% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EntityProxyTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/EntityProxyTest.java index 0d1ca0c78999b..f9b29118eb6cc 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EntityProxyTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/EntityProxyTest.java @@ -15,7 +15,9 @@ package com.microsoft.windowsazure.services.media; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.Set; @@ -53,7 +55,8 @@ public void canCreateAssetOnServerWithNameAndAltId() throws Exception { String name = testAssetPrefix + "AName"; String altId = "unit test alt id"; - AssetInfo asset = entityService.create(Asset.create().setName(name).setAlternateId(altId)); + AssetInfo asset = entityService.create(Asset.create().setName(name) + .setAlternateId(altId)); assertNotNull(asset.getId()); assertEquals(name, asset.getName()); @@ -62,9 +65,11 @@ public void canCreateAssetOnServerWithNameAndAltId() throws Exception { @Test public void canRetrieveAssetById() throws Exception { - AssetInfo createdAsset = entityService.create(Asset.create().setName(testAssetPrefix + "canRetrieveAssetById")); + AssetInfo createdAsset = entityService.create(Asset.create().setName( + testAssetPrefix + "canRetrieveAssetById")); - AssetInfo retrieved = entityService.get(Asset.get(createdAsset.getId())); + AssetInfo retrieved = entityService + .get(Asset.get(createdAsset.getId())); assertEquals(createdAsset.getId(), retrieved.getId()); assertEquals(createdAsset.getName(), retrieved.getName()); @@ -74,7 +79,8 @@ public void canRetrieveAssetById() throws Exception { @Test public void canListAllAssets() throws Exception { int numAssetsToCreate = 4; - Set expectedAssets = createTestAssets(numAssetsToCreate, "canList"); + Set expectedAssets = createTestAssets(numAssetsToCreate, + "canList"); ListResult assets = entityService.list(Asset.list()); @@ -92,7 +98,8 @@ public void canListAllAssets() throws Exception { public void canListAssetsWithQueryParameters() throws Exception { createTestAssets(4, "withQuery"); - ListResult assets = entityService.list(Asset.list().setTop(2)); + ListResult assets = entityService.list(Asset.list() + .setTop(2)); assertEquals(2, assets.size()); } @@ -102,11 +109,14 @@ public void canUpdateAssetNameAndAltId() throws Exception { String newName = testAssetPrefix + "newName"; String newAltId = "updated alt id"; - AssetInfo initialAsset = entityService.create(Asset.create().setName(testAssetPrefix + "originalName")); + AssetInfo initialAsset = entityService.create(Asset.create().setName( + testAssetPrefix + "originalName")); - entityService.update(Asset.update(initialAsset.getId()).setName(newName).setAlternateId(newAltId)); + entityService.update(Asset.update(initialAsset.getId()) + .setName(newName).setAlternateId(newAltId)); - AssetInfo updatedAsset = entityService.get(Asset.get(initialAsset.getId())); + AssetInfo updatedAsset = entityService.get(Asset.get(initialAsset + .getId())); assertEquals(initialAsset.getId(), updatedAsset.getId()); assertEquals(newName, updatedAsset.getName()); @@ -124,9 +134,11 @@ public void canDeleteAssetsById() throws Exception { entityService.delete(Asset.delete(id)); } - ListResult afterDeleteAssets = entityService.list(Asset.list()); + ListResult afterDeleteAssets = entityService.list(Asset + .list()); - assertEquals(currentAssets.size() - numToDelete, afterDeleteAssets.size()); + assertEquals(currentAssets.size() - numToDelete, + afterDeleteAssets.size()); for (AssetInfo asset : afterDeleteAssets) { assetsToDelete.remove(asset.getId()); @@ -135,7 +147,8 @@ public void canDeleteAssetsById() throws Exception { assertEquals(numToDelete, assetsToDelete.size()); } - private Set createTestAssets(int numAssets, String namePart) throws Exception { + private Set createTestAssets(int numAssets, String namePart) + throws Exception { Set expectedAssets = new HashSet(); for (int i = 0; i < numAssets; ++i) { diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ExportsTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/ExportsTest.java similarity index 76% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ExportsTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/ExportsTest.java index 32c54ede596c0..f1f2e390c2a01 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ExportsTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/ExportsTest.java @@ -15,7 +15,8 @@ package com.microsoft.windowsazure.services.media; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.net.URI; @@ -25,16 +26,18 @@ import com.microsoft.windowsazure.services.media.implementation.ResourceLocationManager; /** - * Tests to verify the items exported from media services - * can be resolved from configuration. + * Tests to verify the items exported from media services can be resolved from + * configuration. * */ public class ExportsTest extends IntegrationTestBase { @Test public void canResolveLocationManagerFromConfig() throws Exception { - ResourceLocationManager rlm = config.create(ResourceLocationManager.class); - URI rootUri = new URI((String) config.getProperty(MediaConfiguration.URI)); + ResourceLocationManager rlm = config + .create(ResourceLocationManager.class); + URI rootUri = new URI( + (String) config.getProperty(MediaConfiguration.URI)); assertEquals(rootUri, rlm.getBaseURI()); } diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/IntegrationTestBase.java b/media/src/test/java/com/microsoft/windowsazure/services/media/IntegrationTestBase.java new file mode 100644 index 0000000000000..1b6c97589647e --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/IntegrationTestBase.java @@ -0,0 +1,417 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.rules.ExpectedException; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.AccessPolicy; +import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; +import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetFile; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.ContentKey; +import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; +import com.microsoft.windowsazure.services.media.models.Job; +import com.microsoft.windowsazure.services.media.models.JobInfo; +import com.microsoft.windowsazure.services.media.models.JobState; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.Locator; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; +import com.microsoft.windowsazure.services.media.models.LocatorType; +import com.microsoft.windowsazure.services.media.models.MediaProcessor; +import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo; +import com.microsoft.windowsazure.services.media.models.NotificationEndPoint; +import com.microsoft.windowsazure.services.media.models.NotificationEndPointInfo; +import com.microsoft.windowsazure.services.queue.QueueConfiguration; +import com.microsoft.windowsazure.services.queue.QueueContract; +import com.microsoft.windowsazure.services.queue.QueueService; +import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; +import com.microsoft.windowsazure.services.queue.models.ListQueuesResult.Queue; + +public abstract class IntegrationTestBase { + protected static MediaContract service; + protected static QueueContract queueService; + protected static Configuration config; + + protected static final String testAssetPrefix = "testAsset"; + protected static final String testPolicyPrefix = "testPolicy"; + protected static final String testContentKeyPrefix = "testContentKey"; + protected static final String testJobPrefix = "testJobPrefix"; + protected static final String testQueuePrefix = "testqueueprefix"; + protected static final String testChannelPrefix = "testChannel"; + protected static final String testProgramPrefix = "testProgram"; + protected static final String testNotificationEndPointPrefix = "testNotificationEndPointPrefix"; + + + protected static final String validButNonexistAssetId = "nb:cid:UUID:0239f11f-2d36-4e5f-aa35-44d58ccc0973"; + protected static final String validButNonexistAccessPolicyId = "nb:pid:UUID:38dcb3a0-ef64-4ad0-bbb5-67a14c6df2f7"; + protected static final String validButNonexistLocatorId = "nb:lid:UUID:92a70402-fca9-4aa3-80d7-d4de3792a27a"; + + protected static String MEDIA_ENCODER_MEDIA_PROCESSOR_ID = "nb:mpid:UUID:2e7aa8f3-4961-4e0c-b4db-0e0439e524f5"; + protected static final String invalidId = "notAValidId"; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @BeforeClass + public static void setup() throws Exception { + config = Configuration.getInstance(); + overrideWithEnv(config, MediaConfiguration.URI); + overrideWithEnv(config, MediaConfiguration.OAUTH_URI); + overrideWithEnv(config, MediaConfiguration.OAUTH_CLIENT_ID); + overrideWithEnv(config, MediaConfiguration.OAUTH_CLIENT_SECRET); + overrideWithEnv(config, MediaConfiguration.OAUTH_SCOPE); + + overrideWithEnv(config, QueueConfiguration.ACCOUNT_KEY, + "media.queue.account.key"); + overrideWithEnv(config, QueueConfiguration.ACCOUNT_NAME, + "media.queue.account.name"); + overrideWithEnv(config, QueueConfiguration.URI, "media.queue.uri"); + + service = MediaService.create(config); + queueService = QueueService.create(config); + + cleanupEnvironment(); + } + + protected static void getLatestMediaProcessorID() throws Exception { + ListResult listMediaProcessorsResult = service + .list(MediaProcessor.list()); + List ps = listMediaProcessorsResult; + double latestVersion = 0.0; + int position = -1; + for (int i = 0; i < ps.size(); i++) { + MediaProcessorInfo mediaProcessorInfo = ps.get(i); + double d = Double.parseDouble(mediaProcessorInfo.getVersion()); + if (d > latestVersion) { + latestVersion = d; + position = i; + } + } + + if (position != -1) { + MEDIA_ENCODER_MEDIA_PROCESSOR_ID = ps.get(position).getId(); + } + } + + protected static void overrideWithEnv(Configuration config, String key) { + String value = System.getenv(key); + if (value == null) + return; + + config.setProperty(key, value); + } + + protected static void overrideWithEnv(Configuration config, String key, + String enviromentKey) { + String value = System.getenv(enviromentKey); + if (value == null) + return; + + config.setProperty(key, value); + } + + @AfterClass + public static void cleanup() throws Exception { + cleanupEnvironment(); + } + + protected static void cleanupEnvironment() { + removeAllTestLocators(); + removeAllTestAssets(); + removeAllTestAccessPolicies(); + removeAllTestJobs(); + removeAllTestContentKeys(); + removeAllTestQueues(); + removeAllTestNotificationEndPoints(); + } + + private static void removeAllTestNotificationEndPoints() + { + try { + ListResult listNotificationEndPointResult = service.list(NotificationEndPoint.list()); + for (NotificationEndPointInfo notificationEndPoint : listNotificationEndPointResult) { + if (notificationEndPoint.getName().startsWith(testNotificationEndPointPrefix)); + try { + service.delete(NotificationEndPoint.delete(notificationEndPoint.getId())); + } catch (Exception e) { + // e.printStackTrace(); + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + + private static void removeAllTestQueues() { + try { + ListQueuesResult listQueueResult = queueService.listQueues(); + for (Queue queue : listQueueResult.getQueues()) { + try { + queueService.deleteQueue(queue.getName()); + } catch (Exception e) { + // e.printStackTrace(); + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + + private static void removeAllTestContentKeys() { + try { + List contentKeyInfos = service.list(ContentKey + .list()); + + for (ContentKeyInfo contentKeyInfo : contentKeyInfos) { + try { + service.delete(ContentKey.delete(contentKeyInfo.getId())); + } catch (Exception e) { + // e.printStackTrace(); + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + + private static void removeAllTestAccessPolicies() { + try { + List policies = service.list(AccessPolicy.list()); + + for (AccessPolicyInfo policy : policies) { + if (policy.getName().startsWith(testPolicyPrefix)) { + service.delete(AccessPolicy.delete(policy.getId())); + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + + private static void removeAllTestAssets() { + try { + List listAssetsResult = service.list(Asset.list()); + for (AssetInfo assetInfo : listAssetsResult) { + try { + if (assetInfo.getName().startsWith(testAssetPrefix)) { + service.delete(Asset.delete(assetInfo.getId())); + } else if (assetInfo.getName() + .startsWith("JobOutputAsset(") + && assetInfo.getName().contains(testJobPrefix)) { + // Delete the temp assets associated with Job results. + service.delete(Asset.delete(assetInfo.getId())); + } else if (assetInfo.getName().startsWith("Output")) { + service.delete(Asset.delete(assetInfo.getId())); + } else if (assetInfo.getName().isEmpty()) { + service.delete(Asset.delete(assetInfo.getId())); + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + + private static void removeAllTestLocators() { + try { + ListResult listLocatorsResult = service.list(Locator + .list()); + for (LocatorInfo locatorInfo : listLocatorsResult) { + AssetInfo ai = service.get(Asset.get(locatorInfo.getAssetId())); + if (ai.getName().startsWith(testAssetPrefix)) { + service.delete(Locator.delete(locatorInfo.getId())); + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + + private static void removeAllTestJobs() { + try { + ListResult jobs = service.list(Job.list()); + for (JobInfo job : jobs) { + if (job.getName().startsWith(testJobPrefix)) { + // Job can't be deleted when it's state is + // canceling, scheduled,queued or processing + try { + if (isJobBusy(job.getState())) { + service.action(Job.cancel(job.getId())); + job = service.get(Job.get(job.getId())); + } + + int retryCounter = 0; + while (isJobBusy(job.getState()) && retryCounter < 10) { + Thread.sleep(2000); + job = service.get(Job.get(job.getId())); + retryCounter++; + } + + if (!isJobBusy(job.getState())) { + service.delete(Job.delete(job.getId())); + } else { + // Not much to do so except wait. + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + } + } catch (Exception e) { + // e.printStackTrace(); + } + } + + private static boolean isJobBusy(JobState state) { + return state == JobState.Canceling || state == JobState.Scheduled + || state == JobState.Queued || state == JobState.Processing; + } + + interface ComponentDelegate { + void verifyEquals(String message, Object expected, Object actual); + } + + protected static AssetInfo setupAssetWithFile() throws ServiceException { + String name = UUID.randomUUID().toString(); + String testBlobName = "test" + name + ".bin"; + AssetInfo assetInfo = service.create(Asset.create().setName( + testAssetPrefix + name)); + + AccessPolicyInfo accessPolicyInfo = service.create(AccessPolicy.create( + testPolicyPrefix + name, 10, + EnumSet.of(AccessPolicyPermission.WRITE))); + LocatorInfo locator = createLocator(accessPolicyInfo, assetInfo, 5); + WritableBlobContainerContract blobWriter = service + .createBlobWriter(locator); + InputStream blobContent = new ByteArrayInputStream(new byte[] { 4, 8, + 15, 16, 23, 42 }); + blobWriter.createBlockBlob(testBlobName, blobContent); + + service.action(AssetFile.createFileInfos(assetInfo.getId())); + + return assetInfo; + } + + protected static LocatorInfo createLocator(AccessPolicyInfo accessPolicy, + AssetInfo asset, int startDeltaMinutes) throws ServiceException { + + Date now = new Date(); + Date start = new Date(now.getTime() - (startDeltaMinutes * 60 * 1000)); + + return service.create(Locator.create(accessPolicy.getId(), + asset.getId(), LocatorType.SAS).setStartDateTime(start)); + } + + protected void verifyListResultContains(List expectedInfos, + Collection actualInfos, ComponentDelegate delegate) { + verifyListResultContains("", expectedInfos, actualInfos, delegate); + } + + protected void verifyListResultContains(String message, + List expectedInfos, Collection actualInfos, + ComponentDelegate delegate) { + assertNotNull(message + ": actualInfos", actualInfos); + assertTrue( + message + + ": actual size should be same size or larger than expected size", + actualInfos.size() >= expectedInfos.size()); + + List orderedAndFilteredActualInfo = new ArrayList(); + try { + for (T expectedInfo : expectedInfos) { + Method getId = expectedInfo.getClass().getMethod("getId"); + String expectedId = (String) getId.invoke(expectedInfo); + for (T actualInfo : actualInfos) { + if (((String) getId.invoke(actualInfo)).equals(expectedId)) { + orderedAndFilteredActualInfo.add(actualInfo); + break; + } + } + } + } catch (Exception e) { + // Don't worry about problems here. + // e.printStackTrace(); + } + + assertEquals(message + + ": actual filtered size should be same as expected size", + expectedInfos.size(), orderedAndFilteredActualInfo.size()); + + if (delegate != null) { + for (int i = 0; i < expectedInfos.size(); i++) { + delegate.verifyEquals(message + + ": orderedAndFilteredActualInfo " + i, + expectedInfos.get(i), + orderedAndFilteredActualInfo.get(i)); + } + } + } + + protected void assertEqualsNullEmpty(String message, String expected, + String actual) { + if ((expected == null || expected.length() == 0) + && (actual == null || actual.length() == 0)) { + // both nullOrEmpty, so match. + } else { + assertEquals(message, expected, actual); + } + } + + protected void assertDateApproxEquals(Date expected, Date actual) { + assertDateApproxEquals("", expected, actual); + } + + protected void assertDateApproxEquals(String message, Date expected, + Date actual) { + // Default allows for a 30 seconds difference in dates, for clock skew, + // network delays, etc. + long deltaInMilliseconds = 30000; + + if (expected == null || actual == null) { + assertEquals(message, expected, actual); + } else { + long diffInMilliseconds = Math.abs(expected.getTime() + - actual.getTime()); + + if (diffInMilliseconds > deltaInMilliseconds) { + assertEquals(message, expected, actual); + } + } + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java new file mode 100644 index 0000000000000..fc0b86ca191b3 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java @@ -0,0 +1,487 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.EndPointType; +import com.microsoft.windowsazure.services.media.models.ErrorDetail; +import com.microsoft.windowsazure.services.media.models.Job; +import com.microsoft.windowsazure.services.media.models.Job.Creator; +import com.microsoft.windowsazure.services.media.models.JobInfo; +import com.microsoft.windowsazure.services.media.models.JobNotificationSubscription; +import com.microsoft.windowsazure.services.media.models.JobState; +import com.microsoft.windowsazure.services.media.models.LinkInfo; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.NotificationEndPoint; +import com.microsoft.windowsazure.services.media.models.NotificationEndPointInfo; +import com.microsoft.windowsazure.services.media.models.TargetJobState; +import com.microsoft.windowsazure.services.media.models.Task; +import com.microsoft.windowsazure.services.media.models.Task.CreateBatchOperation; +import com.microsoft.windowsazure.services.media.models.TaskHistoricalEvent; +import com.microsoft.windowsazure.services.media.models.TaskInfo; +import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult.QueueMessage; + +public class JobIntegrationTest extends IntegrationTestBase { + + private static AssetInfo assetInfo; + + private void verifyJobInfoEqual(String message, JobInfo expected, + JobInfo actual) throws ServiceException { + verifyJobProperties(message, expected.getName(), + expected.getPriority(), expected.getRunningDuration(), + expected.getState(), expected.getTemplateId(), + expected.getCreated(), expected.getLastModified(), + expected.getStartTime(), expected.getEndTime(), null, actual); + } + + private void verifyJobProperties(String message, String testName, + Integer priority, double runningDuration, JobState state, + String templateId, Date created, Date lastModified, Date startTime, + Date endTime, Integer expectedTaskCount, JobInfo actualJob) + throws ServiceException { + assertNotNull(message, actualJob); + + assertNotNull(message + "Id", actualJob.getId()); + + assertEquals(message + " Name", testName, actualJob.getName()); + // comment out due to issue 464 + // assertEquals(message + " Priority", priority, + // actualJob.getPriority()); + assertEquals(message + " RunningDuration", runningDuration, + actualJob.getRunningDuration(), 0.001); + assertEquals(message + " State", state, actualJob.getState()); + assertEqualsNullEmpty(message + " TemplateId", templateId, + actualJob.getTemplateId()); + + assertDateApproxEquals(message + " Created", created, + actualJob.getCreated()); + assertDateApproxEquals(message + " LastModified", lastModified, + actualJob.getLastModified()); + assertDateApproxEquals(message + " StartTime", startTime, + actualJob.getStartTime()); + assertDateApproxEquals(message + " EndTime", endTime, + actualJob.getEndTime()); + + if (expectedTaskCount != null) { + LinkInfo tasksLink = actualJob.getTasksLink(); + ListResult actualTasks = service.list(Task + .list(tasksLink)); + assertEquals(message + " tasks size", expectedTaskCount.intValue(), + actualTasks.size()); + } + } + + private JobNotificationSubscription getJobNotificationSubscription( + String jobNotificationSubscriptionId, TargetJobState targetJobState) { + return new JobNotificationSubscription(jobNotificationSubscriptionId, + targetJobState); + } + + private JobInfo createJob(String name) throws ServiceException { + return service.create(Job.create().setName(name).setPriority(3) + .addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0))); + } + + private CreateBatchOperation getTaskCreator(int outputAssetPosition) { + return Task + .create(MEDIA_ENCODER_MEDIA_PROCESSOR_ID, + "" + + "JobInputAsset(0)" + + "JobOutputAsset(" + + outputAssetPosition + ")" + + "") + .setConfiguration("H.264 256k DSL CBR") + .setName("My encoding Task"); + } + + @BeforeClass + public static void setup() throws Exception { + IntegrationTestBase.setup(); + assetInfo = setupAssetWithFile(); + } + + @Test + public void createJobSuccess() throws ServiceException { + // Arrange + String name = testJobPrefix + "createJobSuccess"; + int priority = 3; + double duration = 0.0; + JobState state = JobState.Queued; + String templateId = null; + Date created = new Date(); + Date lastModified = new Date(); + Date stateTime = null; + Date endTime = null; + + // Act + JobInfo actualJob = service.create(Job.create().setName(name) + .setPriority(priority).addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0))); + + // Assert + verifyJobProperties("actualJob", name, priority, duration, state, + templateId, created, lastModified, stateTime, endTime, 1, + actualJob); + } + + @Test + public void createJobWithNotificationSuccess() throws ServiceException { + // Arrange + String name = testJobPrefix + "createJobWithNotificationSuccess"; + String queueName = testQueuePrefix + "createjobwithnotificationsuccess"; + int priority = 3; + double duration = 0.0; + JobState state = JobState.Queued; + String templateId = null; + Date created = new Date(); + Date lastModified = new Date(); + Date stateTime = null; + Date endTime = null; + + queueService.createQueue(queueName); + String notificationEndPointName = UUID.randomUUID().toString(); + + service.create(NotificationEndPoint.create(notificationEndPointName, + EndPointType.AzureQueue, queueName)); + ListResult listNotificationEndPointInfos = service + .list(NotificationEndPoint.list()); + String notificationEndPointId = null; + + for (NotificationEndPointInfo notificationEndPointInfo : listNotificationEndPointInfos) { + if (notificationEndPointInfo.getName().equals( + notificationEndPointName)) { + notificationEndPointId = notificationEndPointInfo.getId(); + } + } + + JobNotificationSubscription jobNotificationSubcription = getJobNotificationSubscription( + notificationEndPointId, TargetJobState.All); + + Creator creator = Job.create().setName(name).setPriority(priority) + .addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0)) + .addJobNotificationSubscription(jobNotificationSubcription); + + // Act + JobInfo actualJob = service.create(creator); + + // Assert + verifyJobProperties("actualJob", name, priority, duration, state, + templateId, created, lastModified, stateTime, endTime, 1, + actualJob); + List queueMessages = queueService.peekMessages(queueName) + .getQueueMessages(); + assertEquals(1, queueMessages.size()); + } + + @Test + public void createJobTwoTasksSuccess() throws ServiceException { + // Arrange + String name = testJobPrefix + "createJobSuccess"; + int priority = 3; + double duration = 0.0; + JobState state = JobState.Queued; + String templateId = null; + Date created = new Date(); + Date lastModified = new Date(); + Date stateTime = null; + Date endTime = null; + List tasks = new ArrayList(); + tasks.add(getTaskCreator(0)); + tasks.add(getTaskCreator(1)); + + // Act + JobInfo actualJob = service.create(Job.create().setName(name) + .setPriority(priority).addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(tasks.get(0)).addTaskCreator(tasks.get(1))); + + // Assert + verifyJobProperties("actualJob", name, priority, duration, state, + templateId, created, lastModified, stateTime, endTime, 2, + actualJob); + } + + @Test + public void getJobSuccess() throws ServiceException { + // Arrange + String name = testJobPrefix + "getJobSuccess"; + int priority = 3; + double duration = 0.0; + JobState state = JobState.Queued; + String templateId = null; + String jobId = createJob(name).getId(); + Date created = new Date(); + Date lastModified = new Date(); + Date stateTime = null; + Date endTime = null; + + // Act + JobInfo actualJob = service.get(Job.get(jobId)); + + // Assert + verifyJobProperties("actualJob", name, priority, duration, state, + templateId, created, lastModified, stateTime, endTime, 1, + actualJob); + } + + @Test + public void getJobInvalidIdFailed() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.get(Job.get(invalidId)); + } + + @Test + public void listJobSuccess() throws ServiceException { + // Arrange + JobInfo jobInfo = createJob(testJobPrefix + "listJobSuccess"); + List jobInfos = new ArrayList(); + jobInfos.add(jobInfo); + ListResult expectedListJobsResult = new ListResult( + jobInfos); + + // Act + ListResult actualListJobResult = service.list(Job.list()); + + // Assert + verifyListResultContains("listJobs", expectedListJobsResult, + actualListJobResult, new ComponentDelegate() { + @Override + public void verifyEquals(String message, Object expected, + Object actual) { + try { + verifyJobInfoEqual(message, (JobInfo) expected, + (JobInfo) actual); + } catch (ServiceException e) { + fail(e.getMessage()); + } + } + }); + } + + @Test + public void canListJobsWithOptions() throws ServiceException { + String[] assetNameSuffixes = new String[] { "A", "B", "C", "D" }; + List expectedJobs = new ArrayList(); + for (String suffix : assetNameSuffixes) { + JobInfo jobInfo = createJob(testJobPrefix + "assetListOptions" + + suffix); + expectedJobs.add(jobInfo); + } + + ListResult listJobsResult = service.list(Job.list().setTop(2)); + + // Assert + assertEquals(2, listJobsResult.size()); + } + + @Test + public void cancelJobSuccess() throws ServiceException { + // Arrange + JobInfo jobInfo = createJob(testJobPrefix + "cancelJobSuccess"); + + // Act + service.action(Job.cancel(jobInfo.getId())); + + // Assert + JobInfo canceledJob = service.get(Job.get(jobInfo.getId())); + assertEquals(JobState.Canceling, canceledJob.getState()); + + } + + @Test + public void cancelJobFailedWithInvalidId() throws ServiceException { + // Arrange + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + + // Act + service.action(Job.cancel(invalidId)); + + // Assert + } + + @Test + public void deleteJobSuccess() throws ServiceException, + InterruptedException { + // Arrange + JobInfo jobInfo = createJob(testJobPrefix + "deleteJobSuccess"); + service.action(Job.cancel(jobInfo.getId())); + JobInfo cancellingJobInfo = service.get(Job.get(jobInfo.getId())); + int retryCounter = 0; + while (cancellingJobInfo.getState() == JobState.Canceling + && retryCounter < 10) { + Thread.sleep(2000); + cancellingJobInfo = service.get(Job.get(jobInfo.getId())); + retryCounter++; + } + + // Act + service.delete(Job.delete(jobInfo.getId())); + + // Assert + expectedException.expect(ServiceException.class); + service.get(Job.get(jobInfo.getId())); + + } + + @Test + public void deleteJobInvalidIdFail() throws ServiceException { + // Arrange + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + + // Act + service.delete(Job.delete(invalidId)); + + // Assert + } + + @Test + public void canGetInputOutputAssetsFromJob() throws Exception { + String name = testJobPrefix + "canGetInputOutputAssetsFromJob"; + int priority = 3; + + JobInfo actualJob = service.create(Job.create().setName(name) + .setPriority(priority).addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0))); + + ListResult inputs = service.list(Asset.list(actualJob + .getInputAssetsLink())); + ListResult outputs = service.list(Asset.list(actualJob + .getOutputAssetsLink())); + + assertEquals(1, inputs.size()); + assertEquals(assetInfo.getId(), inputs.get(0).getId()); + + assertEquals(1, outputs.size()); + assertTrue(outputs.get(0).getName().contains(name)); + } + + @Test + public void canGetTasksFromJob() throws Exception { + String name = testJobPrefix + "canGetTaskAssetsFromJob"; + int priority = 3; + + JobInfo actualJob = service.create(Job.create().setName(name) + .setPriority(priority).addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0))); + + ListResult tasks = service.list(Task.list(actualJob + .getTasksLink())); + + assertEquals(1, tasks.size()); + } + + @Test + public void canGetErrorDetailsFromTask() throws Exception { + String name = testJobPrefix + "canGetErrorDetailsFromTask"; + + JobInfo actualJob = service.create(Job.create().setName(name) + .addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0))); + + JobInfo currentJobInfo = actualJob; + int retryCounter = 0; + while (currentJobInfo.getState().getCode() < 3 && retryCounter < 30) { + Thread.sleep(10000); + currentJobInfo = service.get(Job.get(actualJob.getId())); + retryCounter++; + } + + ListResult tasks = service.list(Task.list(actualJob + .getTasksLink())); + TaskInfo taskInfo = tasks.get(0); + List errorDetails = taskInfo.getErrorDetails(); + + assertEquals(1, errorDetails.size()); + ErrorDetail errorDetail = errorDetails.get(0); + assertNotNull(errorDetail.getCode()); + assertNotNull(errorDetail.getMessage()); + } + + @Test + public void canGetInputOutputAssetsFromTask() throws Exception { + String name = testJobPrefix + "canGetInputOutputAssetsFromTask"; + int priority = 3; + + JobInfo actualJob = service.create(Job.create().setName(name) + .setPriority(priority).addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0))); + + ListResult tasks = service.list(Task.list(actualJob + .getTasksLink())); + ListResult inputs = service.list(Asset.list(tasks.get(0) + .getInputAssetsLink())); + ListResult outputs = service.list(Asset.list(tasks.get(0) + .getOutputAssetsLink())); + + assertEquals(1, inputs.size()); + assertEquals(assetInfo.getId(), inputs.get(0).getId()); + + assertEquals(1, outputs.size()); + assertTrue(outputs.get(0).getName().contains(name)); + } + + @Test + public void canGetTaskHistoricalEventsFromTask() throws Exception { + // Arrange + String jobName = testJobPrefix + "canGetTaskHistoricalEventsFromTask"; + int priority = 3; + int retryCounter = 0; + + // Act + JobInfo actualJobInfo = service.create(Job.create().setName(jobName) + .setPriority(priority).addInputMediaAsset(assetInfo.getId()) + .addTaskCreator(getTaskCreator(0))); + + while (actualJobInfo.getState().getCode() < 3 && retryCounter < 30) { + Thread.sleep(10000); + actualJobInfo = service.get(Job.get(actualJobInfo.getId())); + retryCounter++; + } + ListResult tasks = service.list(Task.list(actualJobInfo + .getTasksLink())); + TaskInfo taskInfo = tasks.get(0); + List historicalEvents = taskInfo + .getHistoricalEvents(); + TaskHistoricalEvent historicalEvent = historicalEvents.get(0); + + // Assert + assertTrue(historicalEvents.size() >= 5); + assertNotNull(historicalEvent.getCode()); + assertNotNull(historicalEvent.getTimeStamp()); + assertNull(historicalEvent.getMessage()); + } + +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/LocatorIntegrationTests.java b/media/src/test/java/com/microsoft/windowsazure/services/media/LocatorIntegrationTests.java new file mode 100644 index 0000000000000..f5a951214c147 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/LocatorIntegrationTests.java @@ -0,0 +1,356 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.AccessPolicy; +import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; +import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.Locator; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; +import com.microsoft.windowsazure.services.media.models.LocatorType; + +public class LocatorIntegrationTests extends IntegrationTestBase { + + private static AssetInfo assetInfo; + private static AccessPolicyInfo accessPolicyInfo; + private static AccessPolicyInfo accessPolicyInfoRead; + private static int minuteInMS = 60 * 1000; + private static int tenMinutesInMS = 10 * 60 * 1000; + + private void verifyLocatorInfosEqual(String message, LocatorInfo expected, + LocatorInfo actual) { + verifyLocatorProperties(message, expected.getAccessPolicyId(), + expected.getAssetId(), expected.getLocatorType(), + expected.getStartTime(), expected.getId(), expected.getPath(), + actual); + } + + private void verifyLocatorProperties(String message, String accessPolicyId, + String assetId, LocatorType locatorType, Date startTime, + LocatorInfo actualLocator) { + verifyLocatorProperties(message, accessPolicyId, assetId, locatorType, + startTime, null, null, actualLocator); + } + + private void verifyLocatorProperties(String message, String accessPolicyId, + String assetId, LocatorType locatorType, Date startTime, String id, + String path, LocatorInfo actualLocator) { + assertNotNull(message, actualLocator); + assertEquals(message + " accessPolicyId", accessPolicyId, + actualLocator.getAccessPolicyId()); + assertEquals(message + " assetId", assetId, actualLocator.getAssetId()); + assertEquals(message + " locatorType", locatorType, + actualLocator.getLocatorType()); + + assertDateApproxEquals(message + " startTime", startTime, + actualLocator.getStartTime()); + + if (id == null) { + assertNotNull(message + " Id", actualLocator.getId()); + } else { + assertEquals(message + " Id", id, actualLocator.getId()); + } + if (path == null) { + assertNotNull(message + " path", actualLocator.getPath()); + } else { + assertEquals(message + " path", path, actualLocator.getPath()); + } + } + + @BeforeClass + public static void setup() throws Exception { + IntegrationTestBase.setup(); + accessPolicyInfo = service + .create(AccessPolicy.create( + testPolicyPrefix + "ForLocatorTest", 5, + EnumSet.of(AccessPolicyPermission.WRITE))); + accessPolicyInfoRead = service.create(AccessPolicy.create( + testPolicyPrefix + "ForLocatorTestRead", 15, + EnumSet.of(AccessPolicyPermission.READ))); + } + + @Before + public void instanceSetup() throws Exception { + assetInfo = service.create(Asset.create().setName( + testAssetPrefix + "ForLocatorTest")); + } + + @Test + public void createLocatorSuccess() throws ServiceException { + // Arrange + LocatorType locatorType = LocatorType.SAS; + + // Act + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfoRead.getId(), assetInfo.getId(), locatorType)); + + // Assert + verifyLocatorProperties("locatorInfo", accessPolicyInfoRead.getId(), + assetInfo.getId(), locatorType, null, locatorInfo); + } + + @Test + public void createLocatorWithSpecifiedIdSuccess() throws ServiceException { + // Arrange + LocatorType locatorType = LocatorType.SAS; + + // Act + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfoRead.getId(), assetInfo.getId(), locatorType) + .setId(String.format("nb:lid:UUID:%s", UUID.randomUUID() + .toString()))); + + // Assert + verifyLocatorProperties("locatorInfo", accessPolicyInfoRead.getId(), + assetInfo.getId(), locatorType, null, locatorInfo); + } + + @Test + public void createLocatorOptionsSetStartTimeSuccess() + throws ServiceException { + // Arrange + Date expectedStartDateTime = new Date(); + expectedStartDateTime.setTime(expectedStartDateTime.getTime() + + tenMinutesInMS); + LocatorType locatorType = LocatorType.SAS; + + // Act + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), locatorType) + .setStartDateTime(expectedStartDateTime)); + + // Assert + verifyLocatorProperties("locatorInfo", accessPolicyInfo.getId(), + assetInfo.getId(), locatorType, expectedStartDateTime, + locatorInfo); + } + + @Test + public void getLocatorSuccess() throws ServiceException { + // Arrange + LocatorType locatorType = LocatorType.SAS; + Date expectedStartDateTime = new Date(); + expectedStartDateTime.setTime(expectedStartDateTime.getTime() + + tenMinutesInMS); + + LocatorInfo expectedLocatorInfo = service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), locatorType) + .setStartDateTime(expectedStartDateTime)); + + // Act + LocatorInfo actualLocatorInfo = service.get(Locator + .get(expectedLocatorInfo.getId())); + + // Assert + verifyLocatorInfosEqual("actualLocatorInfo", expectedLocatorInfo, + actualLocatorInfo); + } + + @Test + public void getLocatorInvalidId() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.get(Locator.get(invalidId)); + } + + @Test + public void getLocatorNonexistId() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(Locator.get(validButNonexistLocatorId)); + } + + @Test + public void listLocatorsSuccess() throws ServiceException { + // Arrange + LocatorType locatorType = LocatorType.SAS; + List expectedLocators = new ArrayList(); + for (int i = 0; i < 2; i++) { + expectedLocators.add(service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), locatorType))); + } + + // Act + ListResult listLocatorsResult = service.list(Locator + .list()); + + // Assert + assertNotNull(listLocatorsResult); + verifyListResultContains("listLocatorsResult", expectedLocators, + listLocatorsResult, new ComponentDelegate() { + @Override + public void verifyEquals(String message, Object expected, + Object actual) { + verifyLocatorInfosEqual(message, + (LocatorInfo) expected, (LocatorInfo) actual); + } + }); + } + + @Test + public void listLocatorsWithOptions() throws ServiceException { + List expectedLocators = new ArrayList(); + for (int i = 0; i < 5; i++) { + expectedLocators.add(service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), + LocatorType.SAS))); + } + + ListResult result = service.list(Locator + .list() + .setTop(3) + .set("$filter", + "(Id eq '" + expectedLocators.get(1).getId() + + "') or (" + "Id eq '" + + expectedLocators.get(3).getId() + "')")); + + assertEquals(2, result.size()); + } + + @Test + public void updateLocatorSuccess() throws ServiceException { + // Arrange + LocatorType locatorType = LocatorType.OnDemandOrigin; + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfoRead.getId(), assetInfo.getId(), locatorType)); + + Date startTime = new Date(); + startTime.setTime(startTime.getTime() - tenMinutesInMS); + + // Act + service.update(Locator.update(locatorInfo.getId()).setStartDateTime( + startTime)); + LocatorInfo updatedLocatorInfo = service.get(Locator.get(locatorInfo + .getId())); + + // Assert + Date expectedExpiration = new Date(); + expectedExpiration.setTime(startTime.getTime() + + (long) accessPolicyInfoRead.getDurationInMinutes() + * minuteInMS); + + verifyLocatorProperties("updatedLocatorInfo", + locatorInfo.getAccessPolicyId(), locatorInfo.getAssetId(), + locatorInfo.getLocatorType(), startTime, locatorInfo.getId(), + locatorInfo.getPath(), updatedLocatorInfo); + } + + @Test + public void updateLocatorNoChangesSuccess() throws ServiceException { + // Arrange + LocatorType locatorType = LocatorType.OnDemandOrigin; + Date expirationDateTime = new Date(); + expirationDateTime.setTime(expirationDateTime.getTime() + + tenMinutesInMS); + Date startTime = new Date(); + startTime.setTime(startTime.getTime() - tenMinutesInMS); + + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfoRead.getId(), assetInfo.getId(), locatorType) + .setStartDateTime(startTime)); + + // Act + service.update(Locator.update(locatorInfo.getId())); + LocatorInfo updatedLocatorInfo = service.get(Locator.get(locatorInfo + .getId())); + + // Assert + verifyLocatorInfosEqual("updatedLocatorInfo", locatorInfo, + updatedLocatorInfo); + } + + @Test + public void deleteLocatorSuccess() throws ServiceException { + // Arrange + LocatorType locatorType = LocatorType.SAS; + LocatorInfo locatorInfo = service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), locatorType)); + ListResult listLocatorsResult = service.list(Locator + .list()); + int assetCountBaseline = listLocatorsResult.size(); + + // Act + service.delete(Locator.delete(locatorInfo.getId())); + + // Assert + listLocatorsResult = service.list(Locator.list()); + assertEquals("listLocatorsResult.size", assetCountBaseline - 1, + listLocatorsResult.size()); + + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(Locator.get(locatorInfo.getId())); + } + + @Test + public void deleteLocatorInvalidIdFailed() throws ServiceException { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.delete(Locator.delete(invalidId)); + } + + @Test + public void canGetLocatorBackFromAsset() throws Exception { + LocatorInfo locator = service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), LocatorType.SAS)); + + ListResult locators = service.list(Locator.list(assetInfo + .getLocatorsLink())); + + assertEquals(1, locators.size()); + assertEquals(locator.getId(), locators.get(0).getId()); + + } + + @Test + public void canGetAssetFromLocator() throws Exception { + LocatorInfo locator = service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), LocatorType.SAS)); + + AssetInfo asset = service.get(Asset.get(locator.getAssetLink())); + + assertEquals(assetInfo.getId(), asset.getId()); + } + + @Test + public void canGetAccessPolicyFromLocator() throws Exception { + LocatorInfo locator = service.create(Locator.create( + accessPolicyInfo.getId(), assetInfo.getId(), LocatorType.SAS)); + + AccessPolicyInfo accessPolicy = service.get(AccessPolicy.get(locator + .getAccessPolicyLink())); + + assertEquals(accessPolicyInfo.getId(), accessPolicy.getId()); + + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/MediaConfigurationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/MediaConfigurationTest.java new file mode 100644 index 0000000000000..a99a361d87f13 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/MediaConfigurationTest.java @@ -0,0 +1,102 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.microsoft.windowsazure.Configuration; + +public class MediaConfigurationTest { + + @Test + public void createMediaConfigurationTestSuccess() { + // Arrange + + // Act + Configuration configuration = MediaConfiguration + .configureWithOAuthAuthentication( + "https://testMediaServiceBaseUri", "testOAuthUri", + "testClientId", "testClientSecret", "testScope"); + + // Assert + assertEquals("https://testMediaServiceBaseUri", + configuration.getProperty("media.uri")); + assertEquals("testOAuthUri", + configuration.getProperty("media.oauth.uri")); + assertEquals("testClientId", + configuration.getProperty("media.oauth.client.id")); + assertEquals("testClientSecret", + configuration.getProperty("media.oauth.client.secret")); + assertEquals("testScope", + configuration.getProperty("media.oauth.scope")); + } + + @Test + public void createMediaConfigurationPassingExistingConfigurationSuccess() { + // Arrange + Configuration preConfiguration = new Configuration(); + preConfiguration.setProperty("preexistingName", "preexistingValue"); + + // Act + Configuration configuration = MediaConfiguration + .configureWithOAuthAuthentication(preConfiguration, + "https://testMediaServiceBaseUri", "testOAuthUri", + "testClientId", "testClientSecret", "testScope"); + + // Assert + assertEquals("preexistingValue", + configuration.getProperty("preexistingName")); + assertEquals("https://testMediaServiceBaseUri", + configuration.getProperty("media.uri")); + assertEquals("testOAuthUri", + configuration.getProperty("media.oauth.uri")); + assertEquals("testClientId", + configuration.getProperty("media.oauth.client.id")); + assertEquals("testClientSecret", + configuration.getProperty("media.oauth.client.secret")); + + } + + @Test + public void createMediaConfigurationWithProfileConfigurationSuccess() { + // Arrange + Configuration preConfiguration = new Configuration(); + preConfiguration.setProperty("preexistingName", "preexistingValue"); + + // Act + Configuration configuration = MediaConfiguration + .configureWithOAuthAuthentication("testProfile", + preConfiguration, "https://testMediaServiceBaseUri", + "testOAuthUri", "testClientId", "testClientSecret", + "testScope"); + + // Assert + assertEquals("preexistingValue", + configuration.getProperty("preexistingName")); + assertEquals("https://testMediaServiceBaseUri", + configuration.getProperty("testProfile.media.uri")); + assertEquals("testOAuthUri", + configuration.getProperty("testProfile.media.oauth.uri")); + assertEquals("testClientId", + configuration.getProperty("testProfile.media.oauth.client.id")); + assertEquals("testClientSecret", + configuration + .getProperty("testProfile.media.oauth.client.secret")); + } + +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/MediaProcessorIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/MediaProcessorIntegrationTest.java new file mode 100644 index 0000000000000..83c34ad2da98b --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/MediaProcessorIntegrationTest.java @@ -0,0 +1,101 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.MediaProcessor; +import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo; + +public class MediaProcessorIntegrationTest extends IntegrationTestBase { + + private void verifyMediaProcessorInfo(String message, + MediaProcessorInfo mediaProcessorInfo) { + assertEquals(message + " id length", 49, mediaProcessorInfo.getId() + .length()); + assertTrue(message + " name length > 0", mediaProcessorInfo.getName() + .length() > 0); + assertNotNull(message + " description", + mediaProcessorInfo.getDescription()); + assertNotNull(message + " sku", mediaProcessorInfo.getSku()); + assertTrue(message + " vendor length > 0", mediaProcessorInfo + .getVendor().length() > 0); + assertTrue(message + " version length > 0", mediaProcessorInfo + .getVersion().length() > 0); + } + + private void verifyMediaProcessorInfo(String message, String id, + String name, String description, String sku, String vendor, + MediaProcessorInfo mediaProcessorInfo) { + assertEquals(message + " id", id, mediaProcessorInfo.getId()); + assertEquals(message + " name", name, mediaProcessorInfo.getName()); + assertEquals(message + " description", description, + mediaProcessorInfo.getDescription()); + assertEquals(message + " sku", sku, mediaProcessorInfo.getSku()); + assertEquals(message + " vendor", vendor, + mediaProcessorInfo.getVendor()); + assertTrue(message + "version length > 0", mediaProcessorInfo + .getVersion().length() > 0); + } + + @Test + public void listMediaProcessorsSuccess() throws ServiceException { + // Arrange + + // Act + ListResult listMediaProcessorsResult = service + .list(MediaProcessor.list()); + + // Assert + assertNotNull("listMediaProcessorsResult", listMediaProcessorsResult); + assertTrue("listMediaProcessorsResult size > 0", + listMediaProcessorsResult.size() > 0); + List ps = listMediaProcessorsResult; + for (int i = 0; i < ps.size(); i++) { + MediaProcessorInfo mediaProcessorInfo = ps.get(i); + verifyMediaProcessorInfo("mediaProcessorInfo:" + i, + mediaProcessorInfo); + } + } + + @Test + public void listMediaProcessorWithOptionSuccess() throws ServiceException { + ListResult listMediaProcessorsResult = service + .list(MediaProcessor + .list() + .setTop(2) + .set("$filter", + "Id eq 'nb:mpid:UUID:aec03716-7c5e-4f68-b592-f4850eba9f10'")); + + assertNotNull("listMediaProcessorsResult", listMediaProcessorsResult); + assertEquals("listMediaProcessors size", 1, + listMediaProcessorsResult.size()); + MediaProcessorInfo mediaProcessorInfo = listMediaProcessorsResult + .get(0); + verifyMediaProcessorInfo("mediaProcessorInfo", + "nb:mpid:UUID:aec03716-7c5e-4f68-b592-f4850eba9f10", + "Storage Decryption", "Storage Decryption", "", "Microsoft", + mediaProcessorInfo); + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/MediaServiceTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/MediaServiceTest.java new file mode 100644 index 0000000000000..812217008246f --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/MediaServiceTest.java @@ -0,0 +1,87 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import com.microsoft.windowsazure.Configuration; + +public class MediaServiceTest { + + @Test + public void createMediaContractSuccessTest() { + // Arrange + Configuration configurationInstance = Configuration.getInstance(); + configurationInstance = MediaConfiguration + .configureWithOAuthAuthentication(configurationInstance, + "mediaServiceBaseUri", "oAuthUri", "clientId", + "clientSecret", "testScope"); + + // Act + MediaContract mediaContract = MediaService.create(); + + // Assert + assertNotNull(mediaContract); + configurationInstance = null; + + } + + @Test + public void createMediaContractWithSpecifiedConfigurationTest() { + // Arrange + Configuration configuration = MediaConfiguration + .configureWithOAuthAuthentication("mediaServiceBaseUri", + "oAuthUri", "clientId", "clientSecret", "testScope"); + + // Act + MediaContract mediaContract = MediaService.create(configuration); + + // Assert + assertNotNull(mediaContract); + } + + @Test + public void createMediaContractWithSpecifiedProfileTest() { + // Arrange + String profile = "testProfile"; + + // Act + MediaContract mediaContract = MediaService.create(profile); + + // Assert + assertNotNull(mediaContract); + + } + + @Test + public void createMediaContractWithSpecifiedProfileAndConfiguration() { + // Arrange + String profile = "testProfile"; + Configuration configuration = MediaConfiguration + .configureWithOAuthAuthentication(profile, new Configuration(), + "mediaServiceBaseUri", "oAuthUri", "clientId", + "clientSecret", "testScope"); + + // Act + MediaContract mediaContract = MediaService.create(profile, + configuration); + + // Assert + assertNotNull(mediaContract); + } +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/NotificationEndPointIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/NotificationEndPointIntegrationTest.java new file mode 100644 index 0000000000000..0a921d4b7fac0 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/NotificationEndPointIntegrationTest.java @@ -0,0 +1,221 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.EndPointType; +import com.microsoft.windowsazure.services.media.models.NotificationEndPoint; +import com.microsoft.windowsazure.services.media.models.NotificationEndPointInfo; + +public class NotificationEndPointIntegrationTest extends IntegrationTestBase { + private final String validButNonexistNotificationEndPointId = "notificationEndPointId"; + private final String testEndPointAddress = "testendpointaddress"; + + private void verifyNotificationEndPointInfosEqual(String message, + NotificationEndPointInfo expected, NotificationEndPointInfo actual) { + verifyNotificationEndPointProperties(message, expected.getName(), + expected.getEndPointType(), expected.getEndPointAddress(), + actual); + } + + private void verifyNotificationEndPointProperties(String message, + String name, EndPointType endPointType, String endPointAddress, + NotificationEndPointInfo notificationEndPointInfo) { + assertNotNull(message, notificationEndPointInfo); + assertEquals(message + " Name", name, + notificationEndPointInfo.getName()); + assertEquals(message + " EndPointType", endPointType, + notificationEndPointInfo.getEndPointType()); + assertEquals(message + " EndPointAddress", endPointAddress, + notificationEndPointInfo.getEndPointAddress()); + assertNotNull(message + " Created", + notificationEndPointInfo.getCreated()); + assertNotNull(message + " Id", notificationEndPointInfo.getId()); + } + + @Test + public void canCreateNotificationEndPoint() throws Exception { + String testName = testNotificationEndPointPrefix + "CanCreate"; + + NotificationEndPointInfo actualNotificationEndPoint = service + .create(NotificationEndPoint.create(testName, + EndPointType.AzureQueue, testEndPointAddress)); + + verifyNotificationEndPointProperties("notification end point ", + testName, EndPointType.AzureQueue, testEndPointAddress, + actualNotificationEndPoint); + } + + @Test + public void canCreateNotificationEndPointWithReadPermissions() + throws Exception { + String testName = testNotificationEndPointPrefix + "CanCreate"; + + NotificationEndPointInfo actualNotificationEndPoint = service + .create(NotificationEndPoint.create(testName, + EndPointType.AzureQueue, testEndPointAddress)); + + verifyNotificationEndPointProperties("notification end point", + testName, EndPointType.AzureQueue, testEndPointAddress, + actualNotificationEndPoint); + } + + @Test + public void canGetSingleNotificationEndPointById() throws Exception { + String expectedName = testNotificationEndPointPrefix + "GetOne"; + NotificationEndPointInfo expectedNotificationEndPointInfo = service + .create(NotificationEndPoint.create(expectedName, + EndPointType.AzureQueue, testEndPointAddress)); + + NotificationEndPointInfo actualNotificationEndPointInfo = service + .get(NotificationEndPoint.get(expectedNotificationEndPointInfo + .getId())); + + assertEquals(expectedNotificationEndPointInfo.getId(), + actualNotificationEndPointInfo.getId()); + verifyNotificationEndPointProperties("notification end point", + expectedName, EndPointType.AzureQueue, testEndPointAddress, + actualNotificationEndPointInfo); + } + + @Test + public void canGetSingleNotificationEndPointByInvalidId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.get(NotificationEndPoint.get(invalidId)); + } + + @Test + public void cannotGetSingleNotificationEndPointByNonexistId() + throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.get(NotificationEndPoint + .get(validButNonexistNotificationEndPointId)); + } + + @Test + public void canRetrieveListOfNotificationEndPoints() throws Exception { + String[] notificationEndPointNames = new String[] { + testNotificationEndPointPrefix + "ListOne", + testNotificationEndPointPrefix + "ListTwo" }; + + List expectedNotificationEndPoints = new ArrayList(); + for (int i = 0; i < notificationEndPointNames.length; i++) { + NotificationEndPointInfo notificationEndPointInfo = service + .create(NotificationEndPoint.create( + notificationEndPointNames[i], + EndPointType.AzureQueue, testEndPointAddress)); + expectedNotificationEndPoints.add(notificationEndPointInfo); + } + + List actualAccessPolicies = service + .list(NotificationEndPoint.list()); + + verifyListResultContains("listNotificationEndPoints", + expectedNotificationEndPoints, actualAccessPolicies, + new ComponentDelegate() { + @Override + public void verifyEquals(String message, Object expected, + Object actual) { + verifyNotificationEndPointInfosEqual(message, + (NotificationEndPointInfo) expected, + (NotificationEndPointInfo) actual); + } + }); + } + + @Test + public void canUseQueryParametersWhenListingNotificationEndPoints() + throws Exception { + String[] notificationEndPointNames = new String[] { + testNotificationEndPointPrefix + "ListThree", + testNotificationEndPointPrefix + "ListFour", + testNotificationEndPointPrefix + "ListFive", + testNotificationEndPointPrefix + "ListSix", + testNotificationEndPointPrefix + "ListSeven" }; + + List expectedNotificationEndPointInfos = new ArrayList(); + for (int i = 0; i < notificationEndPointNames.length; i++) { + NotificationEndPointInfo notificationEndPointInfo = service + .create(NotificationEndPoint.create( + notificationEndPointNames[i], + EndPointType.AzureQueue, testEndPointAddress)); + expectedNotificationEndPointInfos.add(notificationEndPointInfo); + } + + List actualNotificationEndPointInfos = service + .list(NotificationEndPoint.list().setTop(2)); + + assertEquals(2, actualNotificationEndPointInfos.size()); + } + + @Test + public void canDeleteNotificationEndPointById() throws Exception { + String testNotificationEndPointName = testNotificationEndPointPrefix + + "ToDelete"; + NotificationEndPointInfo notificationEndPointToBeDeleted = service + .create(NotificationEndPoint.create( + testNotificationEndPointName, EndPointType.AzureQueue, + testEndPointAddress)); + List listNotificationEndPointsResult = service + .list(NotificationEndPoint.list()); + int notificationEndPointBaseline = listNotificationEndPointsResult.size(); + + service.delete(NotificationEndPoint + .delete(notificationEndPointToBeDeleted.getId())); + + listNotificationEndPointsResult = service.list(NotificationEndPoint.list()); + assertEquals("listNotificationEndPointResult.size", notificationEndPointBaseline - 1, + listNotificationEndPointsResult.size()); + + for (NotificationEndPointInfo policy : service + .list(NotificationEndPoint.list())) { + assertFalse(notificationEndPointToBeDeleted.getId().equals( + policy.getId())); + } + + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(404)); + service.get(NotificationEndPoint.get(notificationEndPointToBeDeleted + .getId())); + } + + @Test + public void canDeleteNotificationEndPointByInvalidId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.delete(NotificationEndPoint.delete(invalidId)); + } + + @Test + public void cannotDeleteNotificationEndPointByNonexistId() throws Exception { + expectedException.expect(ServiceException.class); + expectedException.expect(new ServiceExceptionMatcher(400)); + service.delete(NotificationEndPoint + .delete(validButNonexistNotificationEndPointId)); + } + +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/ProtectionKeyIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/ProtectionKeyIntegrationTest.java new file mode 100644 index 0000000000000..a96b0a5ddd9ac --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/ProtectionKeyIntegrationTest.java @@ -0,0 +1,54 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.ContentKeyType; +import com.microsoft.windowsazure.services.media.models.ProtectionKey; + +public class ProtectionKeyIntegrationTest extends IntegrationTestBase { + + @Test + public void canGetProtectionKeyId() throws ServiceException { + // Arrange + + // Act + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(ContentKeyType.CommonEncryption)); + + // Assert + assertNotNull(protectionKeyId); + } + + @Test + public void canGetProtectionKey() throws ServiceException { + // Arrange + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(ContentKeyType.CommonEncryption)); + + // Act + String protectionKey = service.action(ProtectionKey + .getProtectionKey(protectionKeyId)); + + // Assert + assertNotNull(protectionKey); + } + +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ServiceExceptionMatcher.java b/media/src/test/java/com/microsoft/windowsazure/services/media/ServiceExceptionMatcher.java similarity index 92% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ServiceExceptionMatcher.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/ServiceExceptionMatcher.java index 5baee5b57cd2d..3031e792f5534 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ServiceExceptionMatcher.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/ServiceExceptionMatcher.java @@ -18,7 +18,7 @@ import org.hamcrest.BaseMatcher; import org.hamcrest.Description; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; public class ServiceExceptionMatcher extends BaseMatcher { private final int httpStatusCode; @@ -42,6 +42,7 @@ public boolean matches(Object item) { @Override public void describeTo(Description description) { - description.appendText("Must be ServiceException with status code" + this.httpStatusCode); + description.appendText("Must be ServiceException with status code" + + this.httpStatusCode); } } diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/TaskIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/TaskIntegrationTest.java new file mode 100644 index 0000000000000..c88d71c7ad05a --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/TaskIntegrationTest.java @@ -0,0 +1,339 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.Job; +import com.microsoft.windowsazure.services.media.models.Job.Creator; +import com.microsoft.windowsazure.services.media.models.JobInfo; +import com.microsoft.windowsazure.services.media.models.JobState; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.Task; +import com.microsoft.windowsazure.services.media.models.Task.CreateBatchOperation; +import com.microsoft.windowsazure.services.media.models.TaskInfo; +import com.microsoft.windowsazure.services.media.models.TaskOption; +import com.microsoft.windowsazure.services.media.models.TaskState; +import com.sun.jersey.core.util.Base64; + +public class TaskIntegrationTest extends IntegrationTestBase { + private static AssetInfo assetInfo; + private Creator jobCreator; + + private static final String commonConfiguration = "H.264 256k DSL CBR"; + + @BeforeClass + public static void setup() throws Exception { + IntegrationTestBase.setup(); + assetInfo = setupAssetWithFile(); + } + + @Before + public void instanceSetup() { + this.jobCreator = Job.create() + .setName(testJobPrefix + UUID.randomUUID().toString()) + .setPriority(3).addInputMediaAsset(assetInfo.getId()); + } + + @Test + public void createTaskSuccess() throws ServiceException, + UnsupportedEncodingException { + // Arrange + + // Required + String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_ID; + String taskBody = constructTaskBody(0); + + // Optional parameters + String configuration = new String(Base64.encode(commonConfiguration), + "UTF8"); + String name = "My encoding Task " + UUID.randomUUID().toString(); + int jobPriority = 3; + TaskOption options = TaskOption.ProtectedConfiguration; + // Use a fake id, to simulate real use. + String encryptionKeyId = "nb:kid:UUID:" + UUID.randomUUID().toString(); + String encryptionScheme = "ConfigurationEncryption"; + String encryptionVersion = "1.0"; + // Use a trivial vector, 16 bytes of zeros, base-64 encoded. + String initializationVector = new String(Base64.encode(new byte[16]), + "UTF8"); + + CreateBatchOperation taskCreator = Task + .create(mediaProcessorId, taskBody) + .setConfiguration(configuration).setName(name) + .setPriority(jobPriority).setOptions(options) + .setEncryptionKeyId(encryptionKeyId) + .setEncryptionScheme(encryptionScheme) + .setEncryptionVersion(encryptionVersion) + .setInitializationVector(initializationVector); + jobCreator.addTaskCreator(taskCreator); + + // Act + JobInfo job = service.create(jobCreator); + List taskInfos = service.list(Task.list(job.getTasksLink())); + + // Assert + assertEquals("taskInfos count", 1, taskInfos.size()); + verifyTaskPropertiesJustStarted("taskInfo", mediaProcessorId, options, + taskBody, configuration, name, jobPriority, encryptionKeyId, + encryptionScheme, encryptionVersion, initializationVector, + taskInfos.get(0)); + } + + @Test + public void createTwoTasksSuccess() throws ServiceException { + // Arrange + + // Required + String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_ID; + String[] taskBodies = new String[] { constructTaskBody(0), + constructTaskBody(1) }; + + // Optional parameters + String configuration = commonConfiguration; + String baseName = "My encoding Task " + UUID.randomUUID().toString(); + String[] suffixes = new String[] { " 1", " 2" }; + int jobPriority = 3; + TaskOption options = TaskOption.None; + + List taskCreators = new ArrayList(); + + for (int i = 0; i < taskBodies.length; i++) { + CreateBatchOperation taskCreator = Task + .create(mediaProcessorId, taskBodies[i]) + .setConfiguration(configuration) + .setName(baseName + suffixes[i]); + taskCreators.add(taskCreator); + jobCreator.addTaskCreator(taskCreator); + } + + // Act + JobInfo job = service.create(jobCreator); + List taskInfos = service.list(Task.list(job.getTasksLink())); + + // Assert + assertEquals("taskInfos count", taskCreators.size(), taskInfos.size()); + for (int i = 0; i < taskCreators.size(); i++) { + verifyTaskPropertiesJustStartedNoEncryption("taskInfo", + mediaProcessorId, options, taskBodies[i], configuration, + baseName + suffixes[i], jobPriority, taskInfos.get(i)); + } + } + + @Test + public void canListTasksWithOptions() throws ServiceException { + // Arrange + String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_ID; + String configuration = commonConfiguration; + String[] taskNameSuffixes = new String[] { "A", "B", "C", "D" }; + String baseName = "My encoding Task " + UUID.randomUUID().toString(); + int taskCounter = 0; + for (String suffix : taskNameSuffixes) { + CreateBatchOperation taskCreator = Task + .create(mediaProcessorId, constructTaskBody(taskCounter++)) + .setConfiguration(configuration).setName(baseName + suffix); + jobCreator.addTaskCreator(taskCreator); + } + + service.create(jobCreator); + + // Act + ListResult listTaskResult1 = service.list(Task.list().set( + "$filter", "startswith(Name, '" + baseName + "') eq true")); + ListResult listTaskResult2 = service.list(Task.list() + .set("$filter", "startswith(Name, '" + baseName + "') eq true") + .setTop(2)); + + // Assert + assertEquals("listTaskResult1.size", 4, listTaskResult1.size()); + assertEquals("listTaskResult2.size", 2, listTaskResult2.size()); + } + + @Test + public void cancelTaskSuccess() throws ServiceException, + InterruptedException { + // Arrange + String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_ID; + String taskBody = constructTaskBody(0); + String configuration = commonConfiguration; + String name = "My encoding Task " + UUID.randomUUID().toString(); + CreateBatchOperation taskCreator = Task + .create(mediaProcessorId, taskBody) + .setConfiguration(configuration).setName(name); + jobCreator.addTaskCreator(taskCreator); + + JobInfo jobInfo = service.create(jobCreator); + + // Act + service.action(Job.cancel(jobInfo.getId())); + JobInfo cancellingJobInfo = service.get(Job.get(jobInfo.getId())); + while (cancellingJobInfo.getState() == JobState.Canceling) { + Thread.sleep(2000); + cancellingJobInfo = service.get(Job.get(jobInfo.getId())); + } + + // Assert + List taskInfos = service.list(Task.list(cancellingJobInfo + .getTasksLink())); + for (TaskInfo taskInfo : taskInfos) { + verifyTaskPropertiesNoEncryption("canceled task", mediaProcessorId, + TaskOption.None, taskBody, configuration, name, 3, + null, null, 0.0, 0.0, null, TaskState.Canceled, + taskInfo); + } + } + + private void verifyTaskProperties(String message, String mediaProcessorId, + TaskOption options, String taskBody, String configuration, + String name, int priority, String encryptionKeyId, + String encryptionScheme, String encryptionVersion, + String initializationVector, Date endTime, String errorDetails, + double progress, double runningDuration, Date startTime, + TaskState state, TaskInfo actual) throws ServiceException { + assertNotNull(message, actual); + assertNotNull(message + " id", actual.getId()); + + // Required fields + assertEquals(message + " getMediaProcessorId", mediaProcessorId, + actual.getMediaProcessorId()); + assertEquals(message + " getOptions", options, actual.getOptions()); + assertEquals(message + " getTaskBody", taskBody, actual.getTaskBody()); + + // Optional fields + assertEquals(message + " getConfiguration", configuration, + actual.getConfiguration()); + assertEquals(message + " getName", name, actual.getName()); + assertEquals(message + " getPriority", priority, actual.getPriority()); + + // Optional encryption fields + assertEqualsNullEmpty(message + " getEncryptionKeyId", encryptionKeyId, + actual.getEncryptionKeyId()); + assertEqualsNullEmpty(message + " getEncryptionScheme", + encryptionScheme, actual.getEncryptionScheme()); + assertEqualsNullEmpty(message + " getEncryptionVersion", + encryptionVersion, actual.getEncryptionVersion()); + assertEqualsNullEmpty(message + " getInitializationVector", + initializationVector, actual.getInitializationVector()); + + // Read-only fields + assertDateApproxEquals(message + " getEndTime", endTime, + actual.getEndTime()); + assertNotNull(message + " getErrorDetails", actual.getErrorDetails()); + assertEquals(message + " getErrorDetails.size", 0, actual + .getErrorDetails().size()); + + ListResult inputAssets = service.list(Asset.list(actual + .getInputAssetsLink())); + ListResult outputAssets = service.list(Asset.list(actual + .getOutputAssetsLink())); + + assertEquals(message + " inputAssets.size", 1, inputAssets.size()); + assertEquals(message + " inputAssets.get(0).getId", assetInfo.getId(), + inputAssets.get(0).getId()); + + assertEquals(message + " outputAssets.size", 1, outputAssets.size()); + // Because this is a new asset, there is not much else to test + assertTrue(message + " outputAssets.get(0).getId != assetInfo.getId", + !assetInfo.getId().equals(outputAssets.get(0).getId())); + + assertEquals(message + " getProgress", progress, actual.getProgress(), + 0.01); + assertEquals(message + " getRunningDuration", runningDuration, + actual.getRunningDuration(), 0.01); + assertDateApproxEquals(message + " getStartTime", startTime, + actual.getStartTime()); + assertEquals(message + " getState", state, actual.getState()); + + // Note: The PerfMessage is not validated because it is server + // generated. + } + + private void verifyTaskPropertiesJustStarted(String message, + String mediaProcessorId, TaskOption options, String taskBody, + String configuration, String name, int priority, + String encryptionKeyId, String encryptionScheme, + String encryptionVersion, String initializationVector, + TaskInfo actual) throws ServiceException { + + // Read-only + Date endTime = null; + String errorDetails = null; + double progress = 0.0; + int runningDuration = 0; + Date startTime = null; + TaskState state = TaskState.None; + + verifyTaskProperties(message, mediaProcessorId, options, taskBody, + configuration, name, priority, encryptionKeyId, + encryptionScheme, encryptionVersion, initializationVector, + endTime, errorDetails, progress, runningDuration, startTime, + state, actual); + } + + private void verifyTaskPropertiesJustStartedNoEncryption(String message, + String mediaProcessorId, TaskOption options, String taskBody, + String configuration, String name, int priority, TaskInfo actual) + throws ServiceException { + String encryptionKeyId = null; + String encryptionScheme = null; + String encryptionVersion = null; + String initializationVector = null; + + verifyTaskPropertiesJustStarted(message, mediaProcessorId, options, + taskBody, configuration, name, priority, encryptionKeyId, + encryptionScheme, encryptionVersion, initializationVector, + actual); + } + + private void verifyTaskPropertiesNoEncryption(String message, + String mediaProcessorId, TaskOption options, String taskBody, + String configuration, String name, int priority, Date endTime, + String errorDetails, double progress, double runningDuration, + Date startTime, TaskState state, TaskInfo actual) + throws ServiceException { + String encryptionKeyId = null; + String encryptionScheme = null; + String encryptionVersion = null; + String initializationVector = null; + + verifyTaskProperties(message, mediaProcessorId, options, taskBody, + configuration, name, priority, encryptionKeyId, + encryptionScheme, encryptionVersion, initializationVector, + endTime, errorDetails, progress, runningDuration, startTime, + state, actual); + } + + private String constructTaskBody(int outputIndex) { + return "JobInputAsset(0)" + + "JobOutputAsset(" + outputIndex + + ")"; + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/UploadingIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/UploadingIntegrationTest.java similarity index 82% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/UploadingIntegrationTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/UploadingIntegrationTest.java index 080fe6fc4cf11..272ba487dbfd7 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/UploadingIntegrationTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/UploadingIntegrationTest.java @@ -22,12 +22,12 @@ import org.junit.BeforeClass; import org.junit.Test; +import com.microsoft.windowsazure.core.pipeline.jersey.ExponentialRetryPolicy; +import com.microsoft.windowsazure.core.pipeline.jersey.RetryPolicyFilter; import com.microsoft.windowsazure.services.blob.models.BlockList; import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; -import com.microsoft.windowsazure.services.core.ExponentialRetryPolicy; -import com.microsoft.windowsazure.services.core.RetryPolicyFilter; import com.microsoft.windowsazure.services.media.models.AccessPolicy; import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; @@ -41,22 +41,26 @@ */ public class UploadingIntegrationTest extends IntegrationTestBase { private static WritableBlobContainerContract blobWriter; - private static byte[] firstPrimes = new byte[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; + private static byte[] firstPrimes = new byte[] { 2, 3, 5, 7, 11, 13, 17, + 19, 23, 29 }; @BeforeClass public static void setup() throws Exception { IntegrationTestBase.setup(); - AssetInfo asset = service.create(Asset.create().setName(testAssetPrefix + "uploadBlockBlobAsset")); + AssetInfo asset = service.create(Asset.create().setName( + testAssetPrefix + "uploadBlockBlobAsset")); - AccessPolicyInfo policy = service.create(AccessPolicy.create(testPolicyPrefix + "uploadWritePolicy", 10, + AccessPolicyInfo policy = service.create(AccessPolicy.create( + testPolicyPrefix + "uploadWritePolicy", 10, EnumSet.of(AccessPolicyPermission.WRITE))); LocatorInfo locator = createLocator(policy, asset, 5); blobWriter = service.createBlobWriter(locator); - ExponentialRetryPolicy retryPolicy = new ExponentialRetryPolicy(5000, 5, new int[] { 400, 404 }); + ExponentialRetryPolicy retryPolicy = new ExponentialRetryPolicy(5000, + 5, new int[] { 400, 404 }); blobWriter = blobWriter.withFilter(new RetryPolicyFilter(retryPolicy)); } @@ -69,8 +73,10 @@ public void canUploadBlockBlob() throws Exception { @Test public void canUploadBlockBlobWithOptions() throws Exception { InputStream blobContent = new ByteArrayInputStream(firstPrimes); - CreateBlobOptions options = new CreateBlobOptions().addMetadata("testMetadataKey", "testMetadataValue"); - blobWriter.createBlockBlob("canUploadBlockBlobWithOptions", blobContent, options); + CreateBlobOptions options = new CreateBlobOptions().addMetadata( + "testMetadataKey", "testMetadataValue"); + blobWriter.createBlockBlob("canUploadBlockBlobWithOptions", + blobContent, options); } @Test @@ -82,8 +88,10 @@ public void canCreateBlobBlock() throws Exception { @Test public void canCreateBlobBlockWithOptions() throws Exception { InputStream blobContent = new ByteArrayInputStream(firstPrimes); - CreateBlobBlockOptions options = new CreateBlobBlockOptions().setTimeout(100); - blobWriter.createBlobBlock("canCreateBlobBlockWithOptions", "123", blobContent, options); + CreateBlobBlockOptions options = new CreateBlobBlockOptions() + .setTimeout(100); + blobWriter.createBlobBlock("canCreateBlobBlockWithOptions", "123", + blobContent, options); } @Test @@ -97,19 +105,23 @@ public void canCommitBlobBlocksWithOptions() throws Exception { BlockList blockList = new BlockList(); CommitBlobBlocksOptions options = new CommitBlobBlocksOptions() .setBlobContentType("text/html;charset=ISO-8859-1"); - blobWriter.commitBlobBlocks("canCommitBlobBlocksWithOptions", blockList, options); + blobWriter.commitBlobBlocks("canCommitBlobBlocksWithOptions", + blockList, options); } @Test public void canUploadBlockBlobWithExplicitRetry() throws Exception { InputStream blobContent = new ByteArrayInputStream(firstPrimes); - blobWriter.createBlockBlob("canUploadBlockBlobWithExplicitRetry1", blobContent); + blobWriter.createBlockBlob("canUploadBlockBlobWithExplicitRetry1", + blobContent); - ExponentialRetryPolicy forceRetryPolicy = new ExponentialRetryPolicy(1, 1, new int[] { 201 }); - WritableBlobContainerContract forceRetryBlobWriter = blobWriter.withFilter(new RetryPolicyFilter( - forceRetryPolicy)); + ExponentialRetryPolicy forceRetryPolicy = new ExponentialRetryPolicy(1, + 1, new int[] { 201 }); + WritableBlobContainerContract forceRetryBlobWriter = blobWriter + .withFilter(new RetryPolicyFilter(forceRetryPolicy)); blobContent.reset(); - forceRetryBlobWriter.createBlockBlob("canUploadBlockBlobWithExplicitRetry2", blobContent); + forceRetryBlobWriter.createBlockBlob( + "canUploadBlockBlobWithExplicitRetry2", blobContent); } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/LinkRetrievalTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/LinkRetrievalTest.java similarity index 75% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/LinkRetrievalTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/LinkRetrievalTest.java index 6e8c9e0483277..2d027a5252388 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/LinkRetrievalTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/LinkRetrievalTest.java @@ -15,7 +15,10 @@ package com.microsoft.windowsazure.services.media.implementation; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; @@ -55,19 +58,25 @@ public void setup() { link2.setRel("Related/else"); link2.setHref("some/other/href/somewhere"); - entry.getEntryChildren().add(new JAXBElement(linkName, LinkType.class, link1)); - entry.getEntryChildren().add(new JAXBElement(linkName, LinkType.class, link2)); + entry.getEntryChildren().add( + new JAXBElement(linkName, LinkType.class, link1)); + entry.getEntryChildren().add( + new JAXBElement(linkName, LinkType.class, link2)); - MediaProcessorType payload = new MediaProcessorType().setId("DummyId").setName("Dummy Name") - .setVersion("0.0.0").setVendor("Contoso").setSku("sku skiddo").setDescription("For testing links only"); + MediaProcessorType payload = new MediaProcessorType().setId("DummyId") + .setName("Dummy Name").setVersion("0.0.0").setVendor("Contoso") + .setSku("sku skiddo").setDescription("For testing links only"); ContentType contentElement = new ContentType(); contentElement.getContent().add( - new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, MediaProcessorType.class, - payload)); + new JAXBElement( + Constants.ODATA_PROPERTIES_ELEMENT_NAME, + MediaProcessorType.class, payload)); entry.getEntryChildren().add( - new JAXBElement(Constants.ATOM_CONTENT_ELEMENT_NAME, ContentType.class, contentElement)); + new JAXBElement( + Constants.ATOM_CONTENT_ELEMENT_NAME, ContentType.class, + contentElement)); info = new MediaProcessorInfo(entry, payload); } diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperationsTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperationsTest.java new file mode 100644 index 0000000000000..05615e3c458bc --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperationsTest.java @@ -0,0 +1,138 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.implementation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.URI; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeMultipart; +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.ParserConfigurationException; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.media.models.Job; +import com.microsoft.windowsazure.services.media.models.Task; + +public class MediaBatchOperationsTest { + + @Test + public void createMediaBatchOperationSuccess() throws JAXBException, + ParserConfigurationException { + // Arrange + URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media") + .build(); + + // Act + MediaBatchOperations mediaBatchOperations = new MediaBatchOperations( + serviceUri); + + // Assert + assertNotNull(mediaBatchOperations); + + } + + @Test(expected = IllegalArgumentException.class) + public void createMediaBatchOperationFailedWithNullUri() + throws JAXBException, ParserConfigurationException { + // Arrange + URI serviceUri = null; + + // Act + @SuppressWarnings("unused") + MediaBatchOperations mediaBatchOperations = new MediaBatchOperations( + serviceUri); + + // Assert + assertTrue(false); + + } + + @Test + public void addCreateJobOperationToMediaBatchOperationsSuccess() + throws JAXBException, ParserConfigurationException { + // Arrange + URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media") + .build(); + Job.CreateBatchOperation createJobOperation = new Job.CreateBatchOperation( + serviceUri); + + // Act + MediaBatchOperations mediaBatchOperations = new MediaBatchOperations( + serviceUri); + mediaBatchOperations.addOperation(createJobOperation); + + // Assert + assertNotNull(mediaBatchOperations); + assertEquals(1, mediaBatchOperations.getOperations().size()); + + } + + @Test + public void addCreateTaskOperationToMediaBatchOperationsSuccess() + throws JAXBException, ParserConfigurationException { + // Arrange + URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media") + .build(); + String mediaProcessorId = "testMediaProcessorId"; + String taskBody = "testTaskBody"; + + Task.CreateBatchOperation taskCreateBatchOperation = new Task.CreateBatchOperation( + mediaProcessorId, taskBody); + + // Act + MediaBatchOperations mediaBatchOperations = new MediaBatchOperations( + serviceUri); + mediaBatchOperations.addOperation(taskCreateBatchOperation); + + // Assert + assertNotNull(mediaBatchOperations); + assertEquals(1, mediaBatchOperations.getOperations().size()); + } + + @Test + public void getMimeMultipartSuccess() throws JAXBException, + ParserConfigurationException, MessagingException, IOException { + // Arrange + String mediaProcessorId = "testMediaProcessorId"; + String taskBody = "testTaskBody"; + URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media") + .build(); + Task.CreateBatchOperation taskCreateBatchOperation = new Task.CreateBatchOperation( + mediaProcessorId, taskBody); + Job.CreateBatchOperation jobCreateBatchOperation = new Job.CreateBatchOperation( + serviceUri); + + // Act + MediaBatchOperations mediaBatchOperations = new MediaBatchOperations( + serviceUri); + mediaBatchOperations.addOperation(jobCreateBatchOperation); + mediaBatchOperations.addOperation(taskCreateBatchOperation); + MimeMultipart mimeMultipart = mediaBatchOperations.getMimeMultipart(); + + // Assert + assertNotNull(mediaBatchOperations); + assertEquals(2, mediaBatchOperations.getOperations().size()); + assertNotNull(mimeMultipart); + } + +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxyIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxyIntegrationTest.java new file mode 100644 index 0000000000000..9b87e2031ff43 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxyIntegrationTest.java @@ -0,0 +1,51 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.media.implementation; + +import static org.junit.Assert.assertNotNull; + +import java.net.URI; + +import org.junit.Test; + +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.services.media.IntegrationTestBase; +import com.microsoft.windowsazure.services.media.MediaConfiguration; +import com.sun.jersey.api.client.Client; + +public class OAuthRestProxyIntegrationTest extends IntegrationTestBase { + @Test + public void serviceCanBeCalledToCreateAccessToken() throws Exception { + // Arrange + OAuthContract oAuthContract = new OAuthRestProxy( + config.create(Client.class), new UserAgentFilter()); + + // Act + URI oAuthUri = new URI( + (String) config.getProperty(MediaConfiguration.OAUTH_URI)); + String clientId = (String) config + .getProperty(MediaConfiguration.OAUTH_CLIENT_ID); + String clientSecret = (String) config + .getProperty(MediaConfiguration.OAUTH_CLIENT_SECRET); + String scope = (String) config + .getProperty(MediaConfiguration.OAUTH_SCOPE); + OAuthTokenResponse result = oAuthContract.getAccessToken(oAuthUri, + clientId, clientSecret, scope); + + // Assert + assertNotNull(result); + assertNotNull(result.getAccessToken()); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManagerTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManagerTest.java similarity index 80% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManagerTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManagerTest.java index ec76153f61a78..f593f87d2d77d 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManagerTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthTokenManagerTest.java @@ -14,8 +14,13 @@ */ package com.microsoft.windowsazure.services.media.implementation; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.io.IOException; import java.net.URI; @@ -29,8 +34,8 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.utils.DateFactory; +import com.microsoft.windowsazure.core.utils.DateFactory; +import com.microsoft.windowsazure.exception.ServiceException; public class OAuthTokenManagerTest { private OAuthContract contract; @@ -52,7 +57,8 @@ public void init() throws URISyntaxException { String accountPassword = "testpassword"; String scope = "testscope"; - client = new OAuthTokenManager(contract, dateFactory, acsBaseUri, accountName, accountPassword, scope); + client = new OAuthTokenManager(contract, dateFactory, acsBaseUri, + accountName, accountPassword, scope); when(dateFactory.getDate()).thenAnswer(new Answer() { @Override @@ -62,24 +68,28 @@ public Date answer(InvocationOnMock invocation) throws Throwable { }); } - private void doIncrementingTokens() throws ServiceException, URISyntaxException, IOException { + private void doIncrementingTokens() throws ServiceException, + URISyntaxException, IOException { doAnswer(new Answer() { int count = 0; @Override - public OAuthTokenResponse answer(InvocationOnMock invocation) throws Throwable { + public OAuthTokenResponse answer(InvocationOnMock invocation) + throws Throwable { ++count; OAuthTokenResponse wrapResponse = new OAuthTokenResponse(); wrapResponse.setAccessToken("testaccesstoken1-" + count); wrapResponse.setExpiresIn(83); return wrapResponse; } - }).when(contract).getAccessToken(new URI("testurl"), "testname", "testpassword", "testscope"); + }).when(contract).getAccessToken(new URI("testurl"), "testname", + "testpassword", "testscope"); } @Test - public void clientUsesContractToGetToken() throws ServiceException, URISyntaxException, IOException { + public void clientUsesContractToGetToken() throws ServiceException, + URISyntaxException, IOException { // Arrange doIncrementingTokens(); @@ -92,8 +102,8 @@ public void clientUsesContractToGetToken() throws ServiceException, URISyntaxExc } @Test - public void clientWillNotCallMultipleTimesWhileAccessTokenIsValid() throws ServiceException, URISyntaxException, - IOException { + public void clientWillNotCallMultipleTimesWhileAccessTokenIsValid() + throws ServiceException, URISyntaxException, IOException { // Arrange doIncrementingTokens(); @@ -108,12 +118,13 @@ public void clientWillNotCallMultipleTimesWhileAccessTokenIsValid() throws Servi assertEquals("testaccesstoken1-1", accessToken2); assertEquals("testaccesstoken1-1", accessToken3); - verify(contract, times(1)).getAccessToken(new URI("testurl"), "testname", "testpassword", "testscope"); + verify(contract, times(1)).getAccessToken(new URI("testurl"), + "testname", "testpassword", "testscope"); } @Test - public void clientWillBeCalledWhenTokenIsHalfwayToExpiring() throws ServiceException, URISyntaxException, - IOException { + public void clientWillBeCalledWhenTokenIsHalfwayToExpiring() + throws ServiceException, URISyntaxException, IOException { // Arrange doIncrementingTokens(); @@ -128,7 +139,8 @@ public void clientWillBeCalledWhenTokenIsHalfwayToExpiring() throws ServiceExcep assertEquals("testaccesstoken1-1", accessToken2); assertEquals("testaccesstoken1-2", accessToken3); - verify(contract, times(2)).getAccessToken(new URI("testurl"), "testname", "testpassword", "testscope"); + verify(contract, times(2)).getAccessToken(new URI("testurl"), + "testname", "testpassword", "testscope"); } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataDateParsingTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataDateParsingTest.java similarity index 87% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataDateParsingTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataDateParsingTest.java index faea8a747fc64..8e46df841647e 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataDateParsingTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataDateParsingTest.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.implementation; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Calendar; import java.util.Date; @@ -26,11 +26,9 @@ import org.junit.Test; /** - * Tests around parsing dates - OData requires date - * strings without timezones be treated as UTC. - * ISO spec, and Java default, is to use local timezone. - * So we need to plug in to tweak Jaxb to use OData - * conventions. + * Tests around parsing dates - OData requires date strings without timezones be + * treated as UTC. ISO spec, and Java default, is to use local timezone. So we + * need to plug in to tweak Jaxb to use OData conventions. * */ public class ODataDateParsingTest { @@ -97,7 +95,8 @@ public void stringWithNoTimezoneActsAsUTC() throws Exception { } @Test - public void stringWithFractionalTimeReturnsCorrectMillisecondsTo100nsBoundary() throws Exception { + public void stringWithFractionalTimeReturnsCorrectMillisecondsTo100nsBoundary() + throws Exception { String exampleDate = "2012-11-28T17:43:12.1234567Z"; Date parsedTime = new ODataDateAdapter().unmarshal(exampleDate); @@ -107,13 +106,15 @@ public void stringWithFractionalTimeReturnsCorrectMillisecondsTo100nsBoundary() timeToNearestSecond.set(2012, 10, 28, 17, 43, 12); timeToNearestSecond.set(Calendar.MILLISECOND, 0); - long millis = parsedTime.getTime() - timeToNearestSecond.getTimeInMillis(); + long millis = parsedTime.getTime() + - timeToNearestSecond.getTimeInMillis(); assertEquals(123, millis); } @Test - public void stringWithFractionalTimeReturnsCorrectMillisecondsAsFractionNotCount() throws Exception { + public void stringWithFractionalTimeReturnsCorrectMillisecondsAsFractionNotCount() + throws Exception { String exampleDate = "2012-11-28T17:43:12.1Z"; Date parsedTime = new ODataDateAdapter().unmarshal(exampleDate); @@ -123,13 +124,15 @@ public void stringWithFractionalTimeReturnsCorrectMillisecondsAsFractionNotCount timeToNearestSecond.set(2012, 10, 28, 17, 43, 12); timeToNearestSecond.set(Calendar.MILLISECOND, 0); - long millis = parsedTime.getTime() - timeToNearestSecond.getTimeInMillis(); + long millis = parsedTime.getTime() + - timeToNearestSecond.getTimeInMillis(); assertEquals(100, millis); } @Test - public void stringWithFractionalSecondsAndTimezoneOffsetParses() throws Exception { + public void stringWithFractionalSecondsAndTimezoneOffsetParses() + throws Exception { String exampleDate = "2012-11-28T17:43:12.1-08:00"; Date parsedTime = new ODataDateAdapter().unmarshal(exampleDate); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationFromJerseyTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationFromJerseyTest.java similarity index 78% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationFromJerseyTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationFromJerseyTest.java index 3fc50cae73e71..6596241e998f1 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationFromJerseyTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationFromJerseyTest.java @@ -23,8 +23,8 @@ import org.junit.Assert; import org.junit.Test; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.DefaultDateFactory; +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.core.utils.DefaultDateFactory; import com.microsoft.windowsazure.services.media.IntegrationTestBase; import com.microsoft.windowsazure.services.media.MediaConfiguration; import com.microsoft.windowsazure.services.media.MediaContract; @@ -41,7 +41,8 @@ public class ODataSerializationFromJerseyTest extends IntegrationTestBase { @Test - public void canBuildJerseyClientToCreateAnAssetWhichIsProperlyDeserialized() throws Exception { + public void canBuildJerseyClientToCreateAnAssetWhichIsProperlyDeserialized() + throws Exception { // Build a jersey client object by hand; this is working up to the // full integration into the media services rest proxy, but we // need to go step by step to begin. @@ -52,7 +53,7 @@ public void canBuildJerseyClientToCreateAnAssetWhichIsProperlyDeserialized() thr cc.getSingletons().add(new ODataEntityProvider()); Client c = Client.create(cc); - c.addFilter(new LoggingFilter(System.out)); + // c.addFilter(new LoggingFilter(System.out)); c.addFilter(new RedirectFilter(createLocationManager())); c.addFilter(new OAuthFilter(createTokenManager())); c.addFilter(new VersionHeadersFilter()); @@ -61,14 +62,16 @@ public void canBuildJerseyClientToCreateAnAssetWhichIsProperlyDeserialized() thr ODataAtomMarshaller m = new ODataAtomMarshaller(); AssetType requestData = new AssetType(); - requestData.setName("firstTestAsset"); + requestData.setName(testAssetPrefix + "firstTestAsset"); requestData.setAlternateId("some external id"); - AssetInfo newAsset = assetResource.type(MediaType.APPLICATION_ATOM_XML).accept(MediaType.APPLICATION_ATOM_XML) + AssetInfo newAsset = assetResource.type(MediaType.APPLICATION_ATOM_XML) + .accept(MediaType.APPLICATION_ATOM_XML) .post(AssetInfo.class, m.marshalEntry(requestData)); Assert.assertNotNull(newAsset); - Assert.assertEquals("firstTestAsset", newAsset.getName()); + Assert.assertEquals(testAssetPrefix + "firstTestAsset", + newAsset.getName()); Assert.assertEquals("some external id", newAsset.getAlternateId()); } @@ -77,23 +80,30 @@ private OAuthContract createOAuthContract() { } private OAuthTokenManager createTokenManager() throws URISyntaxException { - return new OAuthTokenManager(createOAuthContract(), new DefaultDateFactory(), + return new OAuthTokenManager( + createOAuthContract(), + new DefaultDateFactory(), (String) config.getProperty(MediaConfiguration.OAUTH_URI), (String) config.getProperty(MediaConfiguration.OAUTH_CLIENT_ID), - (String) config.getProperty(MediaConfiguration.OAUTH_CLIENT_SECRET), + (String) config + .getProperty(MediaConfiguration.OAUTH_CLIENT_SECRET), (String) config.getProperty(MediaConfiguration.OAUTH_SCOPE)); } - private ResourceLocationManager createLocationManager() throws URISyntaxException { - return new ResourceLocationManager((String) config.getProperty(MediaConfiguration.URI)); + private ResourceLocationManager createLocationManager() + throws URISyntaxException { + return new ResourceLocationManager( + (String) config.getProperty(MediaConfiguration.URI)); } @Test public void canCreateAssetThroughMediaServiceAPI() throws Exception { MediaContract client = createService(); - AssetInfo newAsset = client.create(Asset.create().setName("secondTestAsset")); + AssetInfo newAsset = client.create(Asset.create().setName( + testAssetPrefix + "secondTestAsset")); - Assert.assertEquals("secondTestAsset", newAsset.getName()); + Assert.assertEquals(testAssetPrefix + "secondTestAsset", + newAsset.getName()); } @Test diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationTest.java similarity index 85% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationTest.java index c64b32afd905c..af8d39dda47aa 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ODataSerializationTest.java @@ -56,22 +56,29 @@ public class ODataSerializationTest { + " \n" + " \n" + " \n" - + " \n" + " \n" + + " \n" + + " \n" + " nb:cid:UUID:1f6c7bb4-8013-486e-b4c9-2e4a6842b9a6\n" + " 0\n" + " 2012-08-28T18:34:06.123\n" + " 2012-08-28T18:34:06.123\n" - + " \n" + " testAsset\n" - + " 0\n" + " \n" - + " \n" + " \n" + ""; + + " \n" + + " testAsset\n" + + " 0\n" + + " \n" + + " \n" + + " \n" + + ""; @Test public void canUnmarshallAssetFromFeed() throws Exception { ODataAtomUnmarshaller um = new ODataAtomUnmarshaller(); - InputStream input = new ByteArrayInputStream(sampleFeedOneAsset.getBytes("UTF-8")); + InputStream input = new ByteArrayInputStream( + sampleFeedOneAsset.getBytes("UTF-8")); List entries = um.unmarshalFeed(input, AssetInfo.class); Assert.assertEquals(1, entries.size()); - Assert.assertEquals("nb:cid:UUID:1f6c7bb4-8013-486e-b4c9-2e4a6842b9a6", entries.get(0).getId()); + Assert.assertEquals("nb:cid:UUID:1f6c7bb4-8013-486e-b4c9-2e4a6842b9a6", + entries.get(0).getId()); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -82,15 +89,21 @@ public void canMarshalEntryFromJavaObject() throws Exception { a.setOptions(0); a.setAlternateId("some other id"); - JAXBContext context = JAXBContext.newInstance(EntryType.class, AssetType.class); + JAXBContext context = JAXBContext.newInstance(EntryType.class, + AssetType.class); Marshaller m = context.createMarshaller(); EntryType e = new EntryType(); ContentType c = new ContentType(); - c.getContent().add(new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, AssetType.class, a)); - e.getEntryChildren().add(new JAXBElement(Constants.ATOM_CONTENT_ELEMENT_NAME, ContentType.class, c)); + c.getContent().add( + new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, + AssetType.class, a)); + e.getEntryChildren().add( + new JAXBElement(Constants.ATOM_CONTENT_ELEMENT_NAME, + ContentType.class, c)); - m.marshal(new JAXBElement(new QName(Constants.ATOM_NS, "entry"), EntryType.class, e), System.out); + m.marshal(new JAXBElement(new QName(Constants.ATOM_NS, "entry"), + EntryType.class, e), System.out); } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/RedirectionFilterTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/RedirectionFilterTest.java similarity index 78% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/RedirectionFilterTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/RedirectionFilterTest.java index 32c6f5525cca4..b87632d6250ff 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/RedirectionFilterTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/RedirectionFilterTest.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.implementation; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import javax.ws.rs.core.MultivaluedMap; @@ -39,69 +39,88 @@ public class RedirectionFilterTest { private final String redirectedBaseURI = "http://redirected.somewhere.example/Stuff/"; @Test - public void whenInvokedAndNotRedirected_shouldAddBaseURIToRequest() throws Exception { + public void whenInvokedAndNotRedirected_shouldAddBaseURIToRequest() + throws Exception { RequestRecordingFilter sink = new RequestRecordingFilter(); Client c = Client.create(); c.addFilter(sink); - c.addFilter(new RedirectFilter(new ResourceLocationManager(originalBaseURI))); + c.addFilter(new RedirectFilter(new ResourceLocationManager( + originalBaseURI))); c.resource("Files").get(ClientResponse.class); - assertEquals(originalBaseURI + "Files", sink.request.getURI().toString()); + assertEquals(originalBaseURI + "Files", sink.request.getURI() + .toString()); } @Test - public void whenInvokedAndRedirected_shouldHaveRedirectedURIInRequest() throws Exception { + public void whenInvokedAndRedirected_shouldHaveRedirectedURIInRequest() + throws Exception { RequestRecordingFilter sink = new RequestRecordingFilter(); Client c = Client.create(); c.addFilter(sink); - c.addFilter(new RedirectingTestFilter(originalBaseURI, redirectedBaseURI)); + c.addFilter(new RedirectingTestFilter(originalBaseURI, + redirectedBaseURI)); - c.addFilter(new RedirectFilter(new ResourceLocationManager(originalBaseURI))); + c.addFilter(new RedirectFilter(new ResourceLocationManager( + originalBaseURI))); - ClientResponse response = c.resource("Things").get(ClientResponse.class); + ClientResponse response = c.resource("Things") + .get(ClientResponse.class); assertEquals(200, response.getStatus()); - assertEquals(redirectedBaseURI + "Things", sink.request.getURI().toString()); + assertEquals(redirectedBaseURI + "Things", sink.request.getURI() + .toString()); } @Test - public void whenRedirectedMultipleTimes_requestEndsUpAtFinalRediret() throws Exception { + public void whenRedirectedMultipleTimes_requestEndsUpAtFinalRediret() + throws Exception { RequestRecordingFilter sink = new RequestRecordingFilter(); Client c = Client.create(); c.addFilter(sink); - c.addFilter(new RedirectingTestFilter("https://a.example/API/", "https://b.example/API/")); - c.addFilter(new RedirectingTestFilter("https://b.example/API/", "https://c.example/API/")); - c.addFilter(new RedirectingTestFilter("https://c.example/API/", "https://final.example/Code/")); + c.addFilter(new RedirectingTestFilter("https://a.example/API/", + "https://b.example/API/")); + c.addFilter(new RedirectingTestFilter("https://b.example/API/", + "https://c.example/API/")); + c.addFilter(new RedirectingTestFilter("https://c.example/API/", + "https://final.example/Code/")); - c.addFilter(new RedirectFilter(new ResourceLocationManager("https://a.example/API/"))); + c.addFilter(new RedirectFilter(new ResourceLocationManager( + "https://a.example/API/"))); ClientResponse response = c.resource("Stuff").get(ClientResponse.class); assertEquals(200, response.getStatus()); - assertEquals("https://final.example/Code/Stuff", sink.request.getURI().toString()); + assertEquals("https://final.example/Code/Stuff", sink.request.getURI() + .toString()); } @Test - public void whenRedirectingToNull_shouldGetClientException() throws Exception { + public void whenRedirectingToNull_shouldGetClientException() + throws Exception { RequestRecordingFilter sink = new RequestRecordingFilter(); Client c = Client.create(); c.addFilter(sink); c.addFilter(new RedirectingTestFilter(originalBaseURI, null)); - c.addFilter(new RedirectFilter(new ResourceLocationManager(originalBaseURI))); + c.addFilter(new RedirectFilter(new ResourceLocationManager( + originalBaseURI))); thrown.expect(ClientHandlerException.class); c.resource("Something").get(ClientResponse.class); } @Test - public void whenRedirectingToBadURI_shouldGetClientException() throws Exception { + public void whenRedirectingToBadURI_shouldGetClientException() + throws Exception { RequestRecordingFilter sink = new RequestRecordingFilter(); Client c = Client.create(); c.addFilter(sink); - c.addFilter(new RedirectingTestFilter(originalBaseURI, "no way this is valid!")); - c.addFilter(new RedirectFilter(new ResourceLocationManager(originalBaseURI))); + c.addFilter(new RedirectingTestFilter(originalBaseURI, + "no way this is valid!")); + c.addFilter(new RedirectFilter(new ResourceLocationManager( + originalBaseURI))); thrown.expect(ClientHandlerException.class); c.resource("Something").get(ClientResponse.class); @@ -118,7 +137,8 @@ private class RequestRecordingFilter extends ClientFilter { public ClientRequest request; @Override - public ClientResponse handle(ClientRequest request) throws ClientHandlerException { + public ClientResponse handle(ClientRequest request) + throws ClientHandlerException { this.request = request; ClientResponse response = Mockito.mock(ClientResponse.class); @@ -136,23 +156,25 @@ private class RedirectingTestFilter extends ClientFilter { private final String uriToRedirect; private final String uriRedirectedTo; - public RedirectingTestFilter(String uriToRedirect, String uriRedirectedTo) { + public RedirectingTestFilter(String uriToRedirect, + String uriRedirectedTo) { this.uriToRedirect = uriToRedirect; this.uriRedirectedTo = uriRedirectedTo; } @Override - public ClientResponse handle(ClientRequest request) throws ClientHandlerException { + public ClientResponse handle(ClientRequest request) + throws ClientHandlerException { if (request.getURI().toString().startsWith(uriToRedirect)) { ClientResponse response = Mockito.mock(ClientResponse.class); - Mockito.when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.MOVED_PERMANENTLY); + Mockito.when(response.getClientResponseStatus()).thenReturn( + ClientResponse.Status.MOVED_PERMANENTLY); MultivaluedMap headers = new InBoundHeaders(); headers.add("location", uriRedirectedTo); Mockito.when(response.getHeaders()).thenReturn(headers); return response; - } - else { + } else { return getNext().handle(request); } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManagerTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManagerTest.java similarity index 93% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManagerTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManagerTest.java index d7c11ae94764a..f7585471f74a2 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManagerTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/ResourceLocationManagerTest.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.implementation; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.net.URI; @@ -32,7 +32,8 @@ public void testCanCreateWithBaseUri() throws Exception { } @Test - public void testWhenCallingGetRedirectedURI_shouldReturnURIWithBaseURIPreprended() throws Exception { + public void testWhenCallingGetRedirectedURI_shouldReturnURIWithBaseURIPreprended() + throws Exception { String baseURI = "http://base.uri.example/path/"; ResourceLocationManager m = new ResourceLocationManager(baseURI); @@ -44,7 +45,8 @@ public void testWhenCallingGetRedirectedURI_shouldReturnURIWithBaseURIPreprended } @Test - public void settingBaseURIAfterRedirecting_shouldReturnURIWithNewBaseURI() throws Exception { + public void settingBaseURIAfterRedirecting_shouldReturnURIWithNewBaseURI() + throws Exception { String baseURI = "http://base.uri.example/path/"; String redirectedBaseURI = "http://other.uri.example/API/"; ResourceLocationManager m = new ResourceLocationManager(baseURI); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilterTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilterTest.java similarity index 88% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilterTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilterTest.java index ac543d83b54c6..5fd980cb7d37d 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilterTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/SASTokenFilterTest.java @@ -15,7 +15,8 @@ package com.microsoft.windowsazure.services.media.implementation; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.HashMap; @@ -49,7 +50,8 @@ public void setup() throws Exception { @Test public void filterAddsQueryParameterToRequestUrl() throws Exception { - WebResource r = client.resource("http://astorageaccount.blob.something.example/asset-abcd"); + WebResource r = client + .resource("http://astorageaccount.blob.something.example/asset-abcd"); r.get(ClientResponse.class); @@ -58,12 +60,14 @@ public void filterAddsQueryParameterToRequestUrl() throws Exception { @Test public void filterPreservesQueryParameters() throws Exception { - client.resource("http://storage.service.example/asset-efgh").queryParam("param0", "first") - .queryParam("param1", "second").get(ClientResponse.class); + client.resource("http://storage.service.example/asset-efgh") + .queryParam("param0", "first").queryParam("param1", "second") + .get(ClientResponse.class); assertContainsSASToken(sink.request.getURI()); - Map queryParams = parseQueryParameters(sink.request.getURI()); + Map queryParams = parseQueryParameters(sink.request + .getURI()); assertTrue(queryParams.containsKey("param0")); assertTrue(queryParams.containsKey("param1")); assertEquals("first", queryParams.get("param0")); @@ -81,7 +85,8 @@ private class RequestRecordingFilter extends ClientFilter { public ClientRequest request; @Override - public ClientResponse handle(ClientRequest request) throws ClientHandlerException { + public ClientResponse handle(ClientRequest request) + throws ClientHandlerException { this.request = request; ClientResponse response = Mockito.mock(ClientResponse.class); @@ -101,10 +106,12 @@ private void assertContainsSASToken(URI uri) { assertTrue(queryParams.containsKey("si")); assertTrue(queryParams.containsKey("sig")); - assertEquals("iMDPr8V%2FIJrYG8t2GeSqBh5tTUdM7ykOObFVICa%2F%2F1Q%3D", queryParams.get("sig")); + assertEquals("iMDPr8V%2FIJrYG8t2GeSqBh5tTUdM7ykOObFVICa%2F%2F1Q%3D", + queryParams.get("sig")); } - // Simplistic parsing of query parameters into map so we can assert against contents + // Simplistic parsing of query parameters into map so we can assert against + // contents // easily. private Map parseQueryParameters(URI uri) { HashMap queryParameters = new HashMap(); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/StatusLineTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/StatusLineTest.java similarity index 85% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/StatusLineTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/implementation/StatusLineTest.java index 4c5b2d2d2518b..18a74eddbd779 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/StatusLineTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/implementation/StatusLineTest.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.implementation; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; @@ -23,7 +23,7 @@ import org.junit.Test; -import com.microsoft.windowsazure.services.table.implementation.InputStreamDataSource; +import com.microsoft.windowsazure.core.utils.InputStreamDataSource; public class StatusLineTest { @@ -33,8 +33,10 @@ public void testCanCreateStatus() throws Exception { String httpResponse = "HTTP/1.1 200 OK"; int expectedStatus = 200; String expectedReason = "OK"; - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(httpResponse.getBytes()); - DataSource dataSource = new InputStreamDataSource(byteArrayInputStream, "defaultContentType"); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( + httpResponse.getBytes()); + DataSource dataSource = new InputStreamDataSource(byteArrayInputStream, + "defaultContentType"); // Act StatusLine statusLine = StatusLine.create(dataSource); @@ -46,12 +48,14 @@ public void testCanCreateStatus() throws Exception { @Test public void testGetSetStatus() { - // Arrange + // Arrange String httpResponse = "HTTP/1.1 200 OK"; int expectedStatus = 300; String expectedReason = "NotOK"; - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(httpResponse.getBytes()); - DataSource dataSource = new InputStreamDataSource(byteArrayInputStream, "defaultContentType"); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( + httpResponse.getBytes()); + DataSource dataSource = new InputStreamDataSource(byteArrayInputStream, + "defaultContentType"); StatusLine statusLine = StatusLine.create(dataSource); // Act diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyEntityTest.java similarity index 83% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyEntityTest.java index 6c7ec9b6b604b..d875f988d51b3 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyEntityTest.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.net.URLEncoder; import java.util.EnumSet; @@ -36,28 +36,33 @@ public class AccessPolicyEntityTest { private final String expectedUri; public AccessPolicyEntityTest() throws Exception { - expectedUri = String.format("AccessPolicies('%s')", URLEncoder.encode(examplePolicyId, "UTF-8")); + expectedUri = String.format("AccessPolicies('%s')", + URLEncoder.encode(examplePolicyId, "UTF-8")); } @Test public void createAccessPolicyProvidesExpectedPayload() throws Exception { String name = "some Access Policy"; double duration = 10; - EnumSet permissions = EnumSet.of(AccessPolicyPermission.READ, - AccessPolicyPermission.LIST); + EnumSet permissions = EnumSet.of( + AccessPolicyPermission.READ, AccessPolicyPermission.LIST); - EntityCreateOperation creator = AccessPolicy.create(name, duration, permissions); + EntityCreateOperation creator = AccessPolicy.create( + name, duration, permissions); - AccessPolicyType payload = (AccessPolicyType) creator.getRequestContents(); + AccessPolicyType payload = (AccessPolicyType) creator + .getRequestContents(); assertEquals(name, payload.getName()); assertEquals(duration, payload.getDurationInMinutes(), 0.0); - assertEquals(AccessPolicyPermission.bitsFromPermissions(permissions), payload.getPermissions().intValue()); + assertEquals(AccessPolicyPermission.bitsFromPermissions(permissions), + payload.getPermissions().intValue()); } @Test public void getReturnsExpectedUri() throws Exception { - EntityGetOperation getter = AccessPolicy.get(examplePolicyId); + EntityGetOperation getter = AccessPolicy + .get(examplePolicyId); assertEquals(expectedUri, getter.getUri()); } @@ -71,7 +76,8 @@ public void listReturnsExpectedUri() throws Exception { @Test public void listWithQueryParametersReturnsThem() throws Exception { - EntityListOperation lister = AccessPolicy.list().setTop(10).setSkip(2); + EntityListOperation lister = AccessPolicy.list() + .setTop(10).setSkip(2); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfoTest.java new file mode 100644 index 0000000000000..07732ab7cc13e --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfoTest.java @@ -0,0 +1,96 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.models; + +import java.util.Date; +import java.util.EnumSet; + +import org.junit.Assert; +import org.junit.Test; + +import com.microsoft.windowsazure.services.media.implementation.content.AccessPolicyType; + +public class AccessPolicyInfoTest { + + @Test + public void getSetId() { + String expected = "expectedId"; + + AccessPolicyInfo policy = new AccessPolicyInfo(null, + new AccessPolicyType().setId(expected)); + + String actual = policy.getId(); + + Assert.assertEquals(expected, actual); + } + + @Test + public void getSetCreated() { + Date expected = new Date(); + AccessPolicyInfo policy = new AccessPolicyInfo(null, + new AccessPolicyType().setCreated(expected)); + + Date actual = policy.getCreated(); + + Assert.assertEquals(expected, actual); + } + + @Test + public void getSetLastModified() { + Date expected = new Date(); + AccessPolicyInfo policy = new AccessPolicyInfo(null, + new AccessPolicyType().setLastModified(expected)); + + Date actual = policy.getLastModified(); + + Assert.assertEquals(expected, actual); + } + + @Test + public void getSetName() { + String expected = "policy name goes here"; + AccessPolicyInfo policy = new AccessPolicyInfo(null, + new AccessPolicyType().setName(expected)); + + String actual = policy.getName(); + + Assert.assertEquals(expected, actual); + } + + @Test + public void getSetDurationInMinutes() { + double expected = 60; // arbitrary value + AccessPolicyInfo policy = new AccessPolicyInfo(null, + new AccessPolicyType().setDurationInMinutes(expected)); + + double actual = policy.getDurationInMinutes(); + + Assert.assertEquals(expected, actual, 0.0); + } + + @Test + public void getSetPermissions() { + EnumSet expected = EnumSet.of( + AccessPolicyPermission.LIST, AccessPolicyPermission.WRITE); + AccessPolicyInfo policy = new AccessPolicyInfo(null, + new AccessPolicyType().setPermissions(AccessPolicyPermission + .bitsFromPermissions(expected))); + + EnumSet actual = policy.getPermissions(); + + Assert.assertEquals(expected, actual); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermissionTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermissionTest.java similarity index 80% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermissionTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermissionTest.java index 90bfb9cf4efe8..f9134fb1eac2a 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermissionTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyPermissionTest.java @@ -15,7 +15,9 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.EnumSet; @@ -34,13 +36,15 @@ public void testGetFlagValue() { @Test public void testZeroResultsInNonePermission() { - EnumSet perms = AccessPolicyPermission.permissionsFromBits(0); + EnumSet perms = AccessPolicyPermission + .permissionsFromBits(0); assertTrue(perms.contains(AccessPolicyPermission.NONE)); } @Test public void testAllBitsSetResultsInAllPermissions() { - EnumSet perms = AccessPolicyPermission.permissionsFromBits(1 + 2 + 4 + 8); + EnumSet perms = AccessPolicyPermission + .permissionsFromBits(1 + 2 + 4 + 8); assertFalse(perms.contains(AccessPolicyPermission.NONE)); assertTrue(perms.contains(AccessPolicyPermission.READ)); @@ -51,7 +55,8 @@ public void testAllBitsSetResultsInAllPermissions() { @Test public void testWriteBitsResultsInOnlyWritePermissions() { - EnumSet perms = AccessPolicyPermission.permissionsFromBits(2); + EnumSet perms = AccessPolicyPermission + .permissionsFromBits(2); assertFalse(perms.contains(AccessPolicyPermission.NONE)); assertFalse(perms.contains(AccessPolicyPermission.READ)); @@ -62,7 +67,8 @@ public void testWriteBitsResultsInOnlyWritePermissions() { @Test public void testEmptyPermissionsResultsInZeroBits() { - EnumSet perms = EnumSet.noneOf(AccessPolicyPermission.class); + EnumSet perms = EnumSet + .noneOf(AccessPolicyPermission.class); int bits = AccessPolicyPermission.bitsFromPermissions(perms); assertEquals(0, bits); @@ -70,8 +76,10 @@ public void testEmptyPermissionsResultsInZeroBits() { @Test public void allPermissionsInSetResultsInCorrectValue() { - EnumSet perms = EnumSet.of(AccessPolicyPermission.READ, AccessPolicyPermission.WRITE, - AccessPolicyPermission.DELETE, AccessPolicyPermission.LIST, AccessPolicyPermission.NONE); + EnumSet perms = EnumSet.of( + AccessPolicyPermission.READ, AccessPolicyPermission.WRITE, + AccessPolicyPermission.DELETE, AccessPolicyPermission.LIST, + AccessPolicyPermission.NONE); int bits = AccessPolicyPermission.bitsFromPermissions(perms); assertEquals(1 + 2 + 4 + 8, bits); @@ -79,7 +87,8 @@ public void allPermissionsInSetResultsInCorrectValue() { @Test public void writePermissionsInSetResultsInCorrectValue() { - EnumSet perms = EnumSet.of(AccessPolicyPermission.WRITE); + EnumSet perms = EnumSet + .of(AccessPolicyPermission.WRITE); int bits = AccessPolicyPermission.bitsFromPermissions(perms); assertEquals(2, bits); @@ -87,7 +96,8 @@ public void writePermissionsInSetResultsInCorrectValue() { @Test public void unknownPermissionBitsAreIgnored() { - EnumSet perms = AccessPolicyPermission.permissionsFromBits(16 + 32); + EnumSet perms = AccessPolicyPermission + .permissionsFromBits(16 + 32); assertTrue(perms.contains(AccessPolicyPermission.NONE)); } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetEntityTest.java similarity index 82% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetEntityTest.java index a60c58ca06ddb..aa72b1811cfd4 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetEntityTest.java @@ -15,7 +15,9 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.net.URLEncoder; @@ -40,7 +42,8 @@ */ public class AssetEntityTest { static final String sampleAssetId = "nb:cid:UUID:1151b8bd-9ada-4e7f-9787-8dfa49968eab"; - private final String expectedUri = String.format("Assets('%s')", URLEncoder.encode(sampleAssetId, "UTF-8")); + private final String expectedUri = String.format("Assets('%s')", + URLEncoder.encode(sampleAssetId, "UTF-8")); public AssetEntityTest() throws Exception { } @@ -63,7 +66,8 @@ public void assetCreateReturnsDefaultCreatePayload() { public void assetCreateCanSetAssetName() { String name = "assetCreateCanSetAssetName"; - Asset.Creator creator = Asset.create().setName("assetCreateCanSetAssetName"); + Asset.Creator creator = Asset.create().setName( + "assetCreateCanSetAssetName"); AssetType payload = (AssetType) creator.getRequestContents(); @@ -79,7 +83,8 @@ public void assetCreateCanSetAssetName() { @Test public void assetGetReturnsExpectedUri() throws Exception { - String expectedUri = String.format("Assets('%s')", URLEncoder.encode(sampleAssetId, "UTF-8")); + String expectedUri = String.format("Assets('%s')", + URLEncoder.encode(sampleAssetId, "UTF-8")); EntityGetOperation getter = Asset.get(sampleAssetId); @@ -97,7 +102,8 @@ public void assetListReturnsExpectedUri() { @Test public void assetListCanTakeQueryParameters() { - EntityListOperation lister = Asset.list().setTop(10).setSkip(2); + EntityListOperation lister = Asset.list().setTop(10) + .setSkip(2); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); @@ -106,11 +112,13 @@ public void assetListCanTakeQueryParameters() { @Test public void assetListCanTakeQueryParametersChained() { - EntityListOperation lister = Asset.list().setTop(10).setSkip(2).set("filter", "something"); + EntityListOperation lister = Asset.list().setTop(10) + .setSkip(2).set("filter", "something"); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); - assertEquals("something", lister.getQueryParameters().getFirst("filter")); + assertEquals("something", lister.getQueryParameters() + .getFirst("filter")); assertEquals(3, lister.getQueryParameters().size()); } @@ -126,7 +134,8 @@ public void assetUpdateCanSetNameAndAltId() throws Exception { String expectedName = "newAssetName"; String expectedAltId = "newAltId"; - EntityUpdateOperation updater = Asset.update(sampleAssetId).setName(expectedName).setAlternateId(expectedAltId); + EntityUpdateOperation updater = Asset.update(sampleAssetId) + .setName(expectedName).setAlternateId(expectedAltId); AssetType payload = (AssetType) updater.getRequestContents(); @@ -148,16 +157,19 @@ public void assetDeleteReturnsExpectedUri() throws Exception { public void listForLinkReturnsExpectedUri() throws Exception { JobInfo fakeJob = createJob(); - EntityListOperation lister = Asset.list(fakeJob.getInputAssetsLink()); + EntityListOperation lister = Asset.list(fakeJob + .getInputAssetsLink()); assertEquals(lister.getUri(), expectedInputAsset); } private JobInfo createJob() { EntryType fakeJobEntry = new EntryType(); - addEntryLink(fakeJobEntry, Constants.ODATA_DATA_NS + "/related/OutputMediaAssets", expectedOutputAsset, + addEntryLink(fakeJobEntry, Constants.ODATA_DATA_NS + + "/related/OutputMediaAssets", expectedOutputAsset, "application/atom+xml;type=feed", "OutputAssets"); - addEntryLink(fakeJobEntry, Constants.ODATA_DATA_NS + "/related/InputMediaAssets", expectedInputAsset, + addEntryLink(fakeJobEntry, Constants.ODATA_DATA_NS + + "/related/InputMediaAssets", expectedInputAsset, "application/atom+xml;type=feed", "InputAssets"); JobType payload = new JobType().setId("SomeId").setName("FakeJob"); @@ -166,15 +178,16 @@ private JobInfo createJob() { return new JobInfo(fakeJobEntry, payload); } - private void addEntryLink(EntryType entry, String rel, String href, String type, String title) { + private void addEntryLink(EntryType entry, String rel, String href, + String type, String title) { LinkType link = new LinkType(); link.setRel(rel); link.setHref(href); link.setType(type); link.setTitle(title); - JAXBElement linkElement = new JAXBElement(new QName("link", Constants.ATOM_NS), - LinkType.class, link); + JAXBElement linkElement = new JAXBElement( + new QName("link", Constants.ATOM_NS), LinkType.class, link); entry.getEntryChildren().add(linkElement); } @@ -182,10 +195,13 @@ private void addEntryLink(EntryType entry, String rel, String href, String type, private ContentType addEntryContent(EntryType entry, Object content) { ContentType contentWrapper = new ContentType(); contentWrapper.getContent().add( - new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, content.getClass(), content)); + new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, + content.getClass(), content)); entry.getEntryChildren().add( - new JAXBElement(Constants.ATOM_CONTENT_ELEMENT_NAME, ContentType.class, contentWrapper)); + new JAXBElement( + Constants.ATOM_CONTENT_ELEMENT_NAME, ContentType.class, + contentWrapper)); return contentWrapper; } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileEntityTest.java similarity index 81% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileEntityTest.java index 5e7607ea309ba..5ec2a9ec55797 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileEntityTest.java @@ -15,7 +15,8 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import org.junit.Test; @@ -39,10 +40,12 @@ public AssetFileEntityTest() throws Exception { @Test public void createFileInfosHasExpectedUri() throws Exception { - EntityActionOperation action = AssetFile.createFileInfos(exampleAssetId); + EntityActionOperation action = AssetFile + .createFileInfos(exampleAssetId); assertEquals("CreateFileInfos", action.getUri()); - assertEquals(encodedAssetId, action.getQueryParameters().getFirst("assetid")); + assertEquals(encodedAssetId, + action.getQueryParameters().getFirst("assetid")); } @Test @@ -58,11 +61,16 @@ public void createWithOptionsSetsOptionsAsExpected() throws Exception { Boolean expectedIsPrimary = true; String expectedMimeType = "application/octet-stream"; - EntityCreateOperation creator = AssetFile.create(exampleAssetId, expectedName) - .setContentChecksum(expectedChecksum).setContentFileSize(expectedSize) - .setEncryptionKeyId(expectedEncryptionKey).setEncryptionScheme(expectedEncryptionScheme) - .setEncryptionVersion(expectedEncryptionVersion).setInitializationVector(expectedInitializationVector) - .setIsEncrypted(expectedIsEncrypted).setIsPrimary(expectedIsPrimary).setMimeType(expectedMimeType); + EntityCreateOperation creator = AssetFile + .create(exampleAssetId, expectedName) + .setContentChecksum(expectedChecksum) + .setContentFileSize(expectedSize) + .setEncryptionKeyId(expectedEncryptionKey) + .setEncryptionScheme(expectedEncryptionScheme) + .setEncryptionVersion(expectedEncryptionVersion) + .setInitializationVector(expectedInitializationVector) + .setIsEncrypted(expectedIsEncrypted) + .setIsPrimary(expectedIsPrimary).setMimeType(expectedMimeType); AssetFileType payload = (AssetFileType) creator.getRequestContents(); @@ -73,7 +81,8 @@ public void createWithOptionsSetsOptionsAsExpected() throws Exception { assertEquals(expectedEncryptionKey, payload.getEncryptionKeyId()); assertEquals(expectedEncryptionScheme, payload.getEncryptionScheme()); assertEquals(expectedEncryptionVersion, payload.getEncryptionVersion()); - assertEquals(expectedInitializationVector, payload.getInitializationVector()); + assertEquals(expectedInitializationVector, + payload.getInitializationVector()); assertEquals(expectedIsEncrypted, payload.getIsEncrypted()); assertEquals(expectedIsPrimary, payload.getIsPrimary()); assertEquals(expectedMimeType, payload.getMimeType()); @@ -108,10 +117,14 @@ public void updateWithAllOptionsHasCorrectPayload() throws Exception { Boolean expectedIsPrimary = true; String expectedMimeType = "application/octet-stream"; - EntityUpdateOperation updater = AssetFile.update(exampleFileId).setContentChecksum(expectedChecksum) - .setContentFileSize(expectedSize).setEncryptionKeyId(expectedEncryptionKey) - .setEncryptionScheme(expectedEncryptionScheme).setEncryptionVersion(expectedEncryptionVersion) - .setInitializationVector(expectedInitializationVector).setIsEncrypted(expectedIsEncrypted) + EntityUpdateOperation updater = AssetFile.update(exampleFileId) + .setContentChecksum(expectedChecksum) + .setContentFileSize(expectedSize) + .setEncryptionKeyId(expectedEncryptionKey) + .setEncryptionScheme(expectedEncryptionScheme) + .setEncryptionVersion(expectedEncryptionVersion) + .setInitializationVector(expectedInitializationVector) + .setIsEncrypted(expectedIsEncrypted) .setIsPrimary(expectedIsPrimary).setMimeType(expectedMimeType); AssetFileType payload = (AssetFileType) updater.getRequestContents(); @@ -124,7 +137,8 @@ public void updateWithAllOptionsHasCorrectPayload() throws Exception { assertEquals(expectedEncryptionKey, payload.getEncryptionKeyId()); assertEquals(expectedEncryptionScheme, payload.getEncryptionScheme()); assertEquals(expectedEncryptionVersion, payload.getEncryptionVersion()); - assertEquals(expectedInitializationVector, payload.getInitializationVector()); + assertEquals(expectedInitializationVector, + payload.getInitializationVector()); assertEquals(expectedIsEncrypted, payload.getIsEncrypted()); assertEquals(expectedIsPrimary, payload.getIsPrimary()); assertEquals(expectedMimeType, payload.getMimeType()); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileInfoTest.java similarity index 77% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileInfoTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileInfoTest.java index a3e577fa847c0..568b6bc70f8c9 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileInfoTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetFileInfoTest.java @@ -14,7 +14,7 @@ */ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Date; @@ -27,7 +27,8 @@ public class AssetFileInfoTest { @Test public void testGetSetId() { String expectedId = "testId"; - AssetFileInfo file = new AssetFileInfo(null, new AssetFileType().setId(expectedId)); + AssetFileInfo file = new AssetFileInfo(null, + new AssetFileType().setId(expectedId)); String actualId = file.getId(); @@ -38,7 +39,8 @@ public void testGetSetId() { @Test public void testGetSetName() { String expectedName = "testName"; - AssetFileInfo fileInfo = new AssetFileInfo(null, new AssetFileType().setName(expectedName)); + AssetFileInfo fileInfo = new AssetFileInfo(null, + new AssetFileType().setName(expectedName)); String actualName = fileInfo.getName(); @@ -64,7 +66,8 @@ public void testGetSetContentFileSize() { @Test public void testGetSetParentAssetId() { String expectedParentAssetId = "testParentAssetId"; - AssetFileInfo fileInfo = new AssetFileInfo(null, new AssetFileType().setParentAssetId(expectedParentAssetId)); + AssetFileInfo fileInfo = new AssetFileInfo(null, + new AssetFileType().setParentAssetId(expectedParentAssetId)); String actualParentAssetId = fileInfo.getParentAssetId(); @@ -75,7 +78,8 @@ public void testGetSetParentAssetId() { public void testGetSetEncryptionVersion() { String expectedEncryptionVersion = "testEncryptionVersion"; AssetFileInfo fileInfo = new AssetFileInfo(null, - new AssetFileType().setEncryptionVersion(expectedEncryptionVersion)); + new AssetFileType() + .setEncryptionVersion(expectedEncryptionVersion)); String actualEncryptionVersion = fileInfo.getEncryptionVersion(); @@ -87,7 +91,8 @@ public void testGetSetEncryptionScheme() { // Arrange String expectedEncryptionScheme = "testEncryptionScheme"; AssetFileInfo fileInfo = new AssetFileInfo(null, - new AssetFileType().setEncryptionScheme(expectedEncryptionScheme)); + new AssetFileType() + .setEncryptionScheme(expectedEncryptionScheme)); // Act String actualEncryptionScheme = fileInfo.getEncryptionScheme(); @@ -98,9 +103,10 @@ public void testGetSetEncryptionScheme() { @Test public void testGetSetIsEncrypted() { - // Arrange + // Arrange Boolean expectedIsEncrypted = true; - AssetFileInfo fileInfo = new AssetFileInfo(null, new AssetFileType().setIsEncrypted(expectedIsEncrypted)); + AssetFileInfo fileInfo = new AssetFileInfo(null, + new AssetFileType().setIsEncrypted(expectedIsEncrypted)); // Act Boolean actualIsEncrypted = fileInfo.getIsEncrypted(); @@ -124,7 +130,8 @@ public void testGetSetEncryptionKeyId() { public void testGetSetInitializationVector() { String expectedInitializationVector = "testInitializationVector"; AssetFileInfo fileInfo = new AssetFileInfo(null, - new AssetFileType().setInitializationVector(expectedInitializationVector)); + new AssetFileType() + .setInitializationVector(expectedInitializationVector)); String actualInitializationVector = fileInfo.getInitializationVector(); @@ -136,19 +143,21 @@ public void testGetSetInitializationVector() { public void testGetSetIsPrimary() { // Arrange Boolean expectedIsPrimary = true; - AssetFileInfo fileInfo = new AssetFileInfo(null, new AssetFileType().setIsPrimary(expectedIsPrimary)); + AssetFileInfo fileInfo = new AssetFileInfo(null, + new AssetFileType().setIsPrimary(expectedIsPrimary)); // Act Boolean actualIsPrimary = fileInfo.getIsPrimary(); - // Assert + // Assert assertEquals(expectedIsPrimary, actualIsPrimary); } @Test public void testGetSetLastModified() { Date expectedLastModified = new Date(); - AssetFileInfo fileInfo = new AssetFileInfo(null, new AssetFileType().setLastModified(expectedLastModified)); + AssetFileInfo fileInfo = new AssetFileInfo(null, + new AssetFileType().setLastModified(expectedLastModified)); Date actualLastModified = fileInfo.getLastModified(); @@ -158,7 +167,8 @@ public void testGetSetLastModified() { @Test public void testGetSetCreated() { Date expectedCreated = new Date(); - AssetFileInfo fileInfo = new AssetFileInfo(null, new AssetFileType().setCreated(expectedCreated)); + AssetFileInfo fileInfo = new AssetFileInfo(null, + new AssetFileType().setCreated(expectedCreated)); Date actualCreated = fileInfo.getCreated(); @@ -168,7 +178,8 @@ public void testGetSetCreated() { @Test public void testGetSetMimeType() { String expectedMimeType = "testMimeType"; - AssetFileInfo fileInfo = new AssetFileInfo(null, new AssetFileType().setMimeType(expectedMimeType)); + AssetFileInfo fileInfo = new AssetFileInfo(null, + new AssetFileType().setMimeType(expectedMimeType)); String actualMimeType = fileInfo.getMimeType(); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetInfoTest.java similarity index 75% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetInfoTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetInfoTest.java index 66d3b0f7e4cee..6c7e0b1f3f47c 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AssetInfoTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/AssetInfoTest.java @@ -14,7 +14,7 @@ */ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Date; @@ -28,9 +28,10 @@ public class AssetInfoTest { public void testGetSetId() { // Arrange String expectedId = "expectedId"; - AssetInfo assetInfo = new AssetInfo(null, new AssetType().setId(expectedId)); + AssetInfo assetInfo = new AssetInfo(null, + new AssetType().setId(expectedId)); - // Act + // Act String actualId = assetInfo.getId(); // Assert @@ -42,7 +43,8 @@ public void testGetSetId() { public void testGetSetState() { // Arrange AssetState expectedState = AssetState.Published; - AssetInfo assetInfo = new AssetInfo(null, new AssetType().setState(expectedState.getCode())); + AssetInfo assetInfo = new AssetInfo(null, + new AssetType().setState(expectedState.getCode())); // Act AssetState actualState = assetInfo.getState(); @@ -56,9 +58,10 @@ public void testGetSetCreated() throws Exception { // Arrange Date expectedCreated = new Date(); - AssetInfo assetInfo = new AssetInfo(null, new AssetType().setCreated(expectedCreated)); + AssetInfo assetInfo = new AssetInfo(null, + new AssetType().setCreated(expectedCreated)); - // Act + // Act Date actualCreated = assetInfo.getCreated(); // Assert @@ -70,7 +73,8 @@ public void testGetSetCreated() throws Exception { public void testGetSetLastModified() throws Exception { // Arrange Date expectedLastModified = new Date(); - AssetInfo assetInfo = new AssetInfo(null, new AssetType().setLastModified(expectedLastModified)); + AssetInfo assetInfo = new AssetInfo(null, + new AssetType().setLastModified(expectedLastModified)); // Act Date actualLastModified = assetInfo.getLastModified(); @@ -83,7 +87,8 @@ public void testGetSetLastModified() throws Exception { public void testGetSetAlternateId() { // Arrange String expectedAlternateId = "testAlternateId"; - AssetInfo assetInfo = new AssetInfo(null, new AssetType().setAlternateId(expectedAlternateId)); + AssetInfo assetInfo = new AssetInfo(null, + new AssetType().setAlternateId(expectedAlternateId)); // Act String actualAlternateId = assetInfo.getAlternateId(); @@ -96,7 +101,8 @@ public void testGetSetAlternateId() { public void testGetSetName() { // Arrange String expectedName = "testName"; - AssetInfo assetInfo = new AssetInfo(null, new AssetType().setName(expectedName)); + AssetInfo assetInfo = new AssetInfo(null, + new AssetType().setName(expectedName)); // Act String actualName = assetInfo.getName(); @@ -110,7 +116,8 @@ public void testGetSetOptions() { // Arrange AssetOption expectedOptions = AssetOption.None; - AssetInfo assetInfo = new AssetInfo(null, new AssetType().setOptions(expectedOptions.getCode())); + AssetInfo assetInfo = new AssetInfo(null, + new AssetType().setOptions(expectedOptions.getCode())); // Act AssetOption actualOptions = assetInfo.getOptions(); diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/models/ChannelEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ChannelEntityTest.java new file mode 100644 index 0000000000000..bcec8d340d257 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ChannelEntityTest.java @@ -0,0 +1,207 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.media.models; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.net.URLEncoder; + +import javax.xml.bind.JAXBElement; +import javax.xml.namespace.QName; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.media.entityoperations.EntityDeleteOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityGetOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation; +import com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation; +import com.microsoft.windowsazure.services.media.implementation.atom.ContentType; +import com.microsoft.windowsazure.services.media.implementation.atom.EntryType; +import com.microsoft.windowsazure.services.media.implementation.atom.LinkType; +import com.microsoft.windowsazure.services.media.implementation.content.AssetType; +import com.microsoft.windowsazure.services.media.implementation.content.Constants; +import com.microsoft.windowsazure.services.media.implementation.content.JobType; + +/** + * Tests for the methods and factories of the Asset entity. + */ +public class ChannelEntityTest { + static final String sampleAssetId = "nb:cid:UUID:1151b8bd-9ada-4e7f-9787-8dfa49968eab"; + private final String expectedUri = String.format("Assets('%s')", + URLEncoder.encode(sampleAssetId, "UTF-8")); + + public ChannelEntityTest() throws Exception { + } + + @Test + public void assetCreateReturnsDefaultCreatePayload() { + AssetType payload = (AssetType) Asset.create().getRequestContents(); + + assertNotNull(payload); + assertNull(payload.getId()); + assertNull(payload.getState()); + assertNull(payload.getCreated()); + assertNull(payload.getLastModified()); + assertNull(payload.getAlternateId()); + assertNull(payload.getName()); + assertNull(payload.getOptions()); + } + + @Test + public void assetCreateCanSetAssetName() { + String name = "assetCreateCanSetAssetName"; + + Asset.Creator creator = Asset.create().setName( + "assetCreateCanSetAssetName"); + + AssetType payload = (AssetType) creator.getRequestContents(); + + assertNotNull(payload); + assertNull(payload.getId()); + assertNull(payload.getState()); + assertNull(payload.getCreated()); + assertNull(payload.getLastModified()); + assertNull(payload.getAlternateId()); + assertEquals(name, payload.getName()); + assertNull(payload.getOptions()); + } + + @Test + public void assetGetReturnsExpectedUri() throws Exception { + String expectedUri = String.format("Assets('%s')", + URLEncoder.encode(sampleAssetId, "UTF-8")); + + EntityGetOperation getter = Asset.get(sampleAssetId); + + assertEquals(expectedUri, getter.getUri()); + } + + @Test + public void assetListReturnsExpectedUri() { + EntityListOperation lister = Asset.list(); + + assertEquals("Assets", lister.getUri()); + assertNotNull(lister.getQueryParameters()); + assertEquals(0, lister.getQueryParameters().size()); + } + + @Test + public void assetListCanTakeQueryParameters() { + EntityListOperation lister = Asset.list().setTop(10) + .setSkip(2); + + assertEquals("10", lister.getQueryParameters().getFirst("$top")); + assertEquals("2", lister.getQueryParameters().getFirst("$skip")); + assertEquals(2, lister.getQueryParameters().size()); + } + + @Test + public void assetListCanTakeQueryParametersChained() { + EntityListOperation lister = Asset.list().setTop(10) + .setSkip(2).set("filter", "something"); + + assertEquals("10", lister.getQueryParameters().getFirst("$top")); + assertEquals("2", lister.getQueryParameters().getFirst("$skip")); + assertEquals("something", lister.getQueryParameters() + .getFirst("filter")); + assertEquals(3, lister.getQueryParameters().size()); + } + + @Test + public void assetUpdateReturnsExpectedUri() throws Exception { + EntityUpdateOperation updater = Asset.update(sampleAssetId); + assertEquals(expectedUri, updater.getUri()); + } + + @Test + public void assetUpdateCanSetNameAndAltId() throws Exception { + + String expectedName = "newAssetName"; + String expectedAltId = "newAltId"; + + EntityUpdateOperation updater = Asset.update(sampleAssetId) + .setName(expectedName).setAlternateId(expectedAltId); + + AssetType payload = (AssetType) updater.getRequestContents(); + + assertEquals(expectedName, payload.getName()); + assertEquals(expectedAltId, payload.getAlternateId()); + } + + @Test + public void assetDeleteReturnsExpectedUri() throws Exception { + EntityDeleteOperation deleter = Asset.delete(sampleAssetId); + + assertEquals(expectedUri, deleter.getUri()); + } + + private static final String expectedOutputAsset = "Job(someJobId)/OutputAssets"; + private static final String expectedInputAsset = "Job(someJobId)/InputAssets"; + + @Test + public void listForLinkReturnsExpectedUri() throws Exception { + JobInfo fakeJob = createJob(); + + EntityListOperation lister = Asset.list(fakeJob + .getInputAssetsLink()); + + assertEquals(lister.getUri(), expectedInputAsset); + } + + private JobInfo createJob() { + EntryType fakeJobEntry = new EntryType(); + addEntryLink(fakeJobEntry, Constants.ODATA_DATA_NS + + "/related/OutputMediaAssets", expectedOutputAsset, + "application/atom+xml;type=feed", "OutputAssets"); + addEntryLink(fakeJobEntry, Constants.ODATA_DATA_NS + + "/related/InputMediaAssets", expectedInputAsset, + "application/atom+xml;type=feed", "InputAssets"); + + JobType payload = new JobType().setId("SomeId").setName("FakeJob"); + addEntryContent(fakeJobEntry, payload); + + return new JobInfo(fakeJobEntry, payload); + } + + private void addEntryLink(EntryType entry, String rel, String href, + String type, String title) { + LinkType link = new LinkType(); + link.setRel(rel); + link.setHref(href); + link.setType(type); + link.setTitle(title); + + JAXBElement linkElement = new JAXBElement( + new QName("link", Constants.ATOM_NS), LinkType.class, link); + entry.getEntryChildren().add(linkElement); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private ContentType addEntryContent(EntryType entry, Object content) { + ContentType contentWrapper = new ContentType(); + contentWrapper.getContent().add( + new JAXBElement(Constants.ODATA_PROPERTIES_ELEMENT_NAME, + content.getClass(), content)); + + entry.getEntryChildren().add( + new JAXBElement( + Constants.ATOM_CONTENT_ELEMENT_NAME, ContentType.class, + contentWrapper)); + return contentWrapper; + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyEntityTest.java similarity index 81% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyEntityTest.java index bd7f4362246ae..7173ad58f1218 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyEntityTest.java @@ -15,7 +15,9 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.net.URLEncoder; @@ -34,8 +36,8 @@ public class ContentKeyEntityTest { private final String testContentKeyId = "nb:kid:UUID:c82307be-1a81-4554-ba7d-cf6dfa735a5a"; private final ContentKeyType testContentKeyType = ContentKeyType.StorageEncryption; private final String testEncryptedContentKey = "testEncryptedContentKey"; - private final String testExpectedContentKeyUri = String.format("ContentKeys('%s')", - URLEncoder.encode(testContentKeyId, "UTF-8")); + private final String testExpectedContentKeyUri = String.format( + "ContentKeys('%s')", URLEncoder.encode(testContentKeyId, "UTF-8")); public ContentKeyEntityTest() throws Exception { @@ -43,20 +45,23 @@ public ContentKeyEntityTest() throws Exception { @Test public void createContentKeyHasCorrectUrl() throws Exception { - EntityCreateOperation creator = ContentKey.create(testContentKeyId, testContentKeyType, - testEncryptedContentKey); + EntityCreateOperation creator = ContentKey.create( + testContentKeyId, testContentKeyType, testEncryptedContentKey); assertEquals("ContentKeys", creator.getUri()); } @Test public void createContentKeyHasCorrectPayload() throws Exception { - ContentKeyRestType contentKeyRestType = (ContentKeyRestType) ContentKey.create(testContentKeyId, - testContentKeyType, testEncryptedContentKey).getRequestContents(); + ContentKeyRestType contentKeyRestType = (ContentKeyRestType) ContentKey + .create(testContentKeyId, testContentKeyType, + testEncryptedContentKey).getRequestContents(); assertEquals(testContentKeyId, contentKeyRestType.getId()); - assertEquals(testContentKeyType.getCode(), contentKeyRestType.getContentKeyType().intValue()); - assertEquals(testEncryptedContentKey, contentKeyRestType.getEncryptedContentKey()); + assertEquals(testContentKeyType.getCode(), contentKeyRestType + .getContentKeyType().intValue()); + assertEquals(testEncryptedContentKey, + contentKeyRestType.getEncryptedContentKey()); assertNull(contentKeyRestType.getChecksum()); assertNull(contentKeyRestType.getCreated()); assertNull(contentKeyRestType.getLastModified()); @@ -67,7 +72,8 @@ public void createContentKeyHasCorrectPayload() throws Exception { @Test public void getContentKeyGivesExpectedUri() throws Exception { - assertEquals(testExpectedContentKeyUri, ContentKey.get(testContentKeyId).getUri()); + assertEquals(testExpectedContentKeyUri, ContentKey + .get(testContentKeyId).getUri()); } @Test @@ -82,7 +88,8 @@ public void listContentKeyReturnsExpectedUri() { @Test public void listContentKeyCanTakeQueryParameters() { - EntityListOperation lister = ContentKey.list().setTop(10).setSkip(2); + EntityListOperation lister = ContentKey.list() + .setTop(10).setSkip(2); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfoTest.java similarity index 76% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfoTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfoTest.java index 1fd2c0cb267df..d75cedd295fc5 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfoTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ContentKeyInfoTest.java @@ -14,7 +14,7 @@ */ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Date; @@ -28,9 +28,10 @@ public class ContentKeyInfoTest { public void testGetSetId() { // Arrange String expectedId = "expectedId"; - ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, new ContentKeyRestType().setId(expectedId)); + ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, + new ContentKeyRestType().setId(expectedId)); - // Act + // Act String actualId = contentKeyInfo.getId(); // Assert @@ -41,7 +42,8 @@ public void testGetSetId() { public void testGetSetCreated() { // Arrange Date expectedCreated = new Date(); - ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, new ContentKeyRestType().setCreated(expectedCreated)); + ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, + new ContentKeyRestType().setCreated(expectedCreated)); // Act Date actualCreated = contentKeyInfo.getCreated(); @@ -69,10 +71,12 @@ public void testGetSetContentKeyType() { // Arrange ContentKeyType expectedContentKeyType = ContentKeyType.ConfigurationEncryption; ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, - new ContentKeyRestType().setContentKeyType(expectedContentKeyType.getCode())); + new ContentKeyRestType() + .setContentKeyType(expectedContentKeyType.getCode())); - // Act - ContentKeyType actualContentKeyType = contentKeyInfo.getContentKeyType(); + // Act + ContentKeyType actualContentKeyType = contentKeyInfo + .getContentKeyType(); // Assert assertEquals(expectedContentKeyType, actualContentKeyType); @@ -81,13 +85,15 @@ public void testGetSetContentKeyType() { @Test public void testGetSetEncryptedContentKey() { - // Arrange + // Arrange String expectedEncryptedContentKey = "testX509Certificate"; ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, - new ContentKeyRestType().setEncryptedContentKey(expectedEncryptedContentKey)); + new ContentKeyRestType() + .setEncryptedContentKey(expectedEncryptedContentKey)); // Act - String actualEncryptedContentKey = contentKeyInfo.getEncryptedContentKey(); + String actualEncryptedContentKey = contentKeyInfo + .getEncryptedContentKey(); // Assert assertEquals(expectedEncryptedContentKey, actualEncryptedContentKey); @@ -97,7 +103,8 @@ public void testGetSetEncryptedContentKey() { public void testGetSetName() { // Arrange String expectedName = "expectedName"; - ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, new ContentKeyRestType().setName(expectedName)); + ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, + new ContentKeyRestType().setName(expectedName)); // Act String actualName = contentKeyInfo.getName(); @@ -108,15 +115,16 @@ public void testGetSetName() { @Test public void testGetSetProtectionKeyId() { - // Arrange + // Arrange String expectedProtectionKeyId = "expectedProtectionKeyId"; ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, - new ContentKeyRestType().setProtectionKeyId(expectedProtectionKeyId)); + new ContentKeyRestType() + .setProtectionKeyId(expectedProtectionKeyId)); // Act String actualProtectionKeyId = contentKeyInfo.getProtectionKeyId(); - // Assert + // Assert assertEquals(expectedProtectionKeyId, actualProtectionKeyId); } @@ -126,10 +134,13 @@ public void testGetSetProtectionKeyType() { // Arrange ProtectionKeyType expectedProtectionKeyType = ProtectionKeyType.X509CertificateThumbprint; ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, - new ContentKeyRestType().setProtectionKeyType(expectedProtectionKeyType.getCode())); + new ContentKeyRestType() + .setProtectionKeyType(expectedProtectionKeyType + .getCode())); // Act - ProtectionKeyType actualProtectionKeyType = contentKeyInfo.getProtectionKeyType(); + ProtectionKeyType actualProtectionKeyType = contentKeyInfo + .getProtectionKeyType(); // Assert assertEquals(expectedProtectionKeyType, actualProtectionKeyType); @@ -137,11 +148,12 @@ public void testGetSetProtectionKeyType() { @Test public void testGetSetCheckSum() { - // Arrange + // Arrange String expectedCheckSum = "testCheckSum"; - ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, new ContentKeyRestType().setChecksum(expectedCheckSum)); + ContentKeyInfo contentKeyInfo = new ContentKeyInfo(null, + new ContentKeyRestType().setChecksum(expectedCheckSum)); - // Act + // Act String actualCheckSum = contentKeyInfo.getChecksum(); // Assert diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/GenericListResultTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/GenericListResultTest.java similarity index 90% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/GenericListResultTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/GenericListResultTest.java index 7409542605c13..f754ea0fc665a 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/GenericListResultTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/GenericListResultTest.java @@ -15,7 +15,11 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; @@ -46,7 +50,8 @@ public void listWithContentsIsNotEmpty() throws Exception { @Test public void createWithEmptyCollectionGivesNoResults() throws Exception { - List result = new ListResult(new ArrayList()); + List result = new ListResult( + new ArrayList()); assertEquals(0, result.size()); } @@ -59,7 +64,8 @@ public void createWithCollectionContentsContainsContents() throws Exception { } @Test - public void createWithCollectionContentsCanRetrieveContents() throws Exception { + public void createWithCollectionContentsCanRetrieveContents() + throws Exception { List result = createStringListResult(); for (int i = 0; i < expectedStrings.length; ++i) { @@ -128,7 +134,8 @@ public void indexOfItemNotInListIsMinusOne() throws Exception { @Test public void lastIndexOfItemInCollectionIsCorrect() throws Exception { - ListResult result = new ListResult(Arrays.asList("c", "b", "c", "a")); + ListResult result = new ListResult(Arrays.asList("c", + "b", "c", "a")); assertEquals(2, result.lastIndexOf("c")); } @@ -274,61 +281,64 @@ public void sublistIsImmutable() throws Exception { } private ListResult createStringListResult() { - ListResult result = new ListResult(Arrays.asList(expectedStrings)); + ListResult result = new ListResult( + Arrays.asList(expectedStrings)); return result; } - /// Assertion helpers /// + // / Assertion helpers /// private void assertIteratorState(int position, ListIterator iterator) { boolean expectHasNext = position < expectedStrings.length; boolean expectHasPrevious = position != 0; assertNotNull("Iterator is null", iterator); - assertEquals(String.format("HasNext at position %d", position), expectHasNext, iterator.hasNext()); - assertEquals(String.format("HasPrevious at position %d", position), expectHasPrevious, iterator.hasPrevious()); + assertEquals(String.format("HasNext at position %d", position), + expectHasNext, iterator.hasNext()); + assertEquals(String.format("HasPrevious at position %d", position), + expectHasPrevious, iterator.hasPrevious()); if (expectHasNext) { - assertEquals(String.format("NextIndex at position %d", position), position, iterator.nextIndex()); + assertEquals(String.format("NextIndex at position %d", position), + position, iterator.nextIndex()); } if (expectHasPrevious) { - assertEquals(String.format("PreviousIndex at position %d", position), position - 1, - iterator.previousIndex()); + assertEquals( + String.format("PreviousIndex at position %d", position), + position - 1, iterator.previousIndex()); } } - private void assertIteratorAtPositionMovingForward(int position, ListIterator iterator) { + private void assertIteratorAtPositionMovingForward(int position, + ListIterator iterator) { assertIteratorState(position, iterator); if (iterator.hasNext()) { assertEquals(expectedStrings[position], iterator.next()); - } - else { + } else { try { iterator.next(); fail("Exception should have been thrown"); - } - catch (NoSuchElementException ex) { + } catch (NoSuchElementException ex) { // Ok, we expected this } } } - private void assertIteratorAtPositionMovingBackward(int position, ListIterator iterator) { + private void assertIteratorAtPositionMovingBackward(int position, + ListIterator iterator) { assertIteratorState(position, iterator); if (iterator.hasPrevious()) { assertEquals(expectedStrings[position - 1], iterator.previous()); - } - else { + } else { try { iterator.previous(); fail("Exception should have been thrown"); - } - catch (NoSuchElementException ex) { + } catch (NoSuchElementException ex) { // Ok, we expected this } } @@ -342,8 +352,7 @@ private void assertUnsupported(Action action) { try { action.Do(); fail("Expected UnsupportedOperationException"); - } - catch (UnsupportedOperationException ex) { + } catch (UnsupportedOperationException ex) { // This is ok } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/JobEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/JobEntityTest.java similarity index 89% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/JobEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/JobEntityTest.java index 361aec9ffa659..b17a8f2200437 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/JobEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/JobEntityTest.java @@ -15,7 +15,8 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.net.URI; @@ -23,7 +24,7 @@ import org.junit.Test; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation; import com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData; @@ -72,11 +73,13 @@ public void JobListCanTakeQueryParameters() { @Test public void JobListCanTakeQueryParametersChained() { - EntityListOperation lister = Job.list().setTop(10).setSkip(2).set("filter", "something"); + EntityListOperation lister = Job.list().setTop(10).setSkip(2) + .set("filter", "something"); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); - assertEquals("something", lister.getQueryParameters().getFirst("filter")); + assertEquals("something", lister.getQueryParameters() + .getFirst("filter")); assertEquals(3, lister.getQueryParameters().size()); } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/JobInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/JobInfoTest.java similarity index 76% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/JobInfoTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/JobInfoTest.java index a4e7fd95fe34b..a1c92e73ebbf4 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/JobInfoTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/JobInfoTest.java @@ -14,7 +14,7 @@ */ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Date; @@ -31,7 +31,7 @@ public void testGetSetId() { String expectedId = "expectedId"; JobInfo JobInfo = new JobInfo(null, new JobType().setId(expectedId)); - // Act + // Act String actualId = JobInfo.getId(); // Assert @@ -57,9 +57,10 @@ public void testGetSetCreated() throws Exception { // Arrange Date expectedCreated = new Date(); - JobInfo JobInfo = new JobInfo(null, new JobType().setCreated(expectedCreated)); + JobInfo JobInfo = new JobInfo(null, + new JobType().setCreated(expectedCreated)); - // Act + // Act Date actualCreated = JobInfo.getCreated(); // Assert @@ -71,7 +72,8 @@ public void testGetSetCreated() throws Exception { public void testGetSetLastModified() throws Exception { // Arrange Date expectedLastModified = new Date(); - JobInfo JobInfo = new JobInfo(null, new JobType().setLastModified(expectedLastModified)); + JobInfo JobInfo = new JobInfo(null, + new JobType().setLastModified(expectedLastModified)); // Act Date actualLastModified = JobInfo.getLastModified(); @@ -84,7 +86,8 @@ public void testGetSetLastModified() throws Exception { public void testGetSetPriority() { // Arrange int expectedPriority = 3; - JobInfo JobInfo = new JobInfo(null, new JobType().setPriority(expectedPriority)); + JobInfo JobInfo = new JobInfo(null, + new JobType().setPriority(expectedPriority)); // Act int actualPriority = JobInfo.getPriority(); @@ -97,7 +100,8 @@ public void testGetSetPriority() { public void testGetSetRunningDuration() { // Arrange Double expectedRunningDuration = 1234.5; - JobInfo JobInfo = new JobInfo(null, new JobType().setRunningDuration(expectedRunningDuration)); + JobInfo JobInfo = new JobInfo(null, + new JobType().setRunningDuration(expectedRunningDuration)); // Act Double actualRunningDuration = JobInfo.getRunningDuration(); @@ -110,7 +114,8 @@ public void testGetSetRunningDuration() { public void testGetSetStartTime() { // Arrange Date expectedStartTime = new Date(); - JobInfo JobInfo = new JobInfo(null, new JobType().setLastModified(expectedStartTime)); + JobInfo JobInfo = new JobInfo(null, + new JobType().setLastModified(expectedStartTime)); // Act Date actualStartTime = JobInfo.getLastModified(); @@ -123,7 +128,8 @@ public void testGetSetStartTime() { public void testGetSetState() { // Arrange JobState expectedJobState = JobState.Finished; - JobInfo JobInfo = new JobInfo(null, new JobType().setState(expectedJobState.getCode())); + JobInfo JobInfo = new JobInfo(null, + new JobType().setState(expectedJobState.getCode())); // Act JobState actualJobState = JobInfo.getState(); @@ -134,23 +140,26 @@ public void testGetSetState() { @Test public void testGetSetNotificationEndPoint() { - // Arrange + // Arrange String expectedNotificationEndPointId = "testNotificationEndPointId"; JobNotificationSubscription expectedJobNotificationSubscription = new JobNotificationSubscription( expectedNotificationEndPointId, TargetJobState.All); JobNotificationSubscriptionType expectedJobNotificationSubscriptionType = new JobNotificationSubscriptionType(); JobType expectedJobType = new JobType(); - expectedJobType.addJobNotificationSubscriptionType(expectedJobNotificationSubscriptionType - .setNotificationEndPointId(expectedNotificationEndPointId).setTargetJobState( - TargetJobState.All.getCode())); + expectedJobType + .addJobNotificationSubscriptionType(expectedJobNotificationSubscriptionType + .setNotificationEndPointId( + expectedNotificationEndPointId) + .setTargetJobState(TargetJobState.All.getCode())); JobInfo jobInfo = new JobInfo(null, expectedJobType); - // Act - JobNotificationSubscription actualJobNotificationSubscription = jobInfo.getJobNotificationSubscriptions() - .get(0); + // Act + JobNotificationSubscription actualJobNotificationSubscription = jobInfo + .getJobNotificationSubscriptions().get(0); - // Assert - assertEquals(expectedJobNotificationSubscription.getNotificationEndPointId(), + // Assert + assertEquals( + expectedJobNotificationSubscription.getNotificationEndPointId(), actualJobNotificationSubscription.getNotificationEndPointId()); assertEquals(expectedJobNotificationSubscription.getTargetJobState(), actualJobNotificationSubscription.getTargetJobState()); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorEntityTest.java similarity index 76% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorEntityTest.java index 80881ea3c7841..05dc90122a51d 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorEntityTest.java @@ -15,7 +15,9 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.net.URLEncoder; import java.util.Date; @@ -45,20 +47,22 @@ public LocatorEntityTest() throws Exception { @Test public void createLocatorHasCorrectUrl() throws Exception { - EntityCreateOperation creator = Locator.create(exampleAccessPolicyId, exampleAssetId, - LocatorType.SAS); + EntityCreateOperation creator = Locator.create( + exampleAccessPolicyId, exampleAssetId, LocatorType.SAS); assertEquals("Locators", creator.getUri()); } @Test public void createLocatorHasCorrectPayload() throws Exception { - LocatorRestType locatorType = (LocatorRestType) Locator.create(exampleAccessPolicyId, exampleAssetId, - LocatorType.SAS).getRequestContents(); + LocatorRestType locatorType = (LocatorRestType) Locator.create( + exampleAccessPolicyId, exampleAssetId, LocatorType.SAS) + .getRequestContents(); assertEquals(exampleAssetId, locatorType.getAssetId()); assertEquals(exampleAccessPolicyId, locatorType.getAccessPolicyId()); - assertEquals(LocatorType.SAS.getCode(), locatorType.getType().intValue()); + assertEquals(LocatorType.SAS.getCode(), locatorType.getType() + .intValue()); assertNull(locatorType.getStartTime()); assertNull(locatorType.getExpirationDateTime()); } @@ -67,14 +71,17 @@ public void createLocatorHasCorrectPayload() throws Exception { public void createLocatorCanSetStartTime() throws Exception { Date now = new Date(); - EntityCreateOperation creator = Locator.create(exampleAccessPolicyId, exampleAssetId, - LocatorType.SAS).setStartDateTime(now); + EntityCreateOperation creator = Locator.create( + exampleAccessPolicyId, exampleAssetId, LocatorType.SAS) + .setStartDateTime(now); - LocatorRestType locatorType = (LocatorRestType) creator.getRequestContents(); + LocatorRestType locatorType = (LocatorRestType) creator + .getRequestContents(); assertEquals(exampleAssetId, locatorType.getAssetId()); assertEquals(exampleAccessPolicyId, locatorType.getAccessPolicyId()); - assertEquals(LocatorType.SAS.getCode(), locatorType.getType().intValue()); + assertEquals(LocatorType.SAS.getCode(), locatorType.getType() + .intValue()); assertEquals(now, locatorType.getStartTime()); } @@ -83,10 +90,12 @@ public void createLocatorCanSetPath() throws Exception { String expectedPath = "testExpectedPath"; - EntityCreateOperation creator = Locator.create(exampleAccessPolicyId, exampleAssetId, - LocatorType.SAS).setPath(expectedPath); + EntityCreateOperation creator = Locator.create( + exampleAccessPolicyId, exampleAssetId, LocatorType.SAS) + .setPath(expectedPath); - LocatorRestType locatorType = (LocatorRestType) creator.getRequestContents(); + LocatorRestType locatorType = (LocatorRestType) creator + .getRequestContents(); assertEquals(expectedPath, locatorType.getPath()); @@ -97,10 +106,12 @@ public void createLocatorCanSetBaseUri() throws Exception { String expectedBaseUri = "testExpectedBaseUri"; - EntityCreateOperation creator = Locator.create(exampleAccessPolicyId, exampleAssetId, - LocatorType.SAS).setBaseUri(expectedBaseUri); + EntityCreateOperation creator = Locator.create( + exampleAccessPolicyId, exampleAssetId, LocatorType.SAS) + .setBaseUri(expectedBaseUri); - LocatorRestType locatorType = (LocatorRestType) creator.getRequestContents(); + LocatorRestType locatorType = (LocatorRestType) creator + .getRequestContents(); assertEquals(expectedBaseUri, locatorType.getBaseUri()); @@ -111,12 +122,15 @@ public void createLocatorCanSetContentAccessComponent() throws Exception { String expectedContentAccessComponent = "testExpectedContentAccessComponent"; - EntityCreateOperation creator = Locator.create(exampleAccessPolicyId, exampleAssetId, - LocatorType.SAS).setContentAccessComponent(expectedContentAccessComponent); + EntityCreateOperation creator = Locator.create( + exampleAccessPolicyId, exampleAssetId, LocatorType.SAS) + .setContentAccessComponent(expectedContentAccessComponent); - LocatorRestType locatorType = (LocatorRestType) creator.getRequestContents(); + LocatorRestType locatorType = (LocatorRestType) creator + .getRequestContents(); - assertEquals(expectedContentAccessComponent, locatorType.getContentAccessComponent()); + assertEquals(expectedContentAccessComponent, + locatorType.getContentAccessComponent()); } @@ -137,7 +151,8 @@ public void listLocatorReturnsExpectedUri() { @Test public void listLocatorCanTakeQueryParameters() { - EntityListOperation lister = Locator.list().setTop(10).setSkip(2); + EntityListOperation lister = Locator.list().setTop(10) + .setSkip(2); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); @@ -156,9 +171,11 @@ public void locatorUpdateCanSetStarTime() throws Exception { Date tenMinutesAgo = new Date(now.getTime() - 10 * 60 * 1000); - EntityUpdateOperation updater = Locator.update(exampleLocatorId).setStartDateTime(tenMinutesAgo); + EntityUpdateOperation updater = Locator.update(exampleLocatorId) + .setStartDateTime(tenMinutesAgo); - LocatorRestType payload = (LocatorRestType) updater.getRequestContents(); + LocatorRestType payload = (LocatorRestType) updater + .getRequestContents(); assertEquals(tenMinutesAgo, payload.getStartTime()); } diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorInfoTest.java new file mode 100644 index 0000000000000..d038b3e0f98e7 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorInfoTest.java @@ -0,0 +1,157 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.media.models; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.media.implementation.content.LocatorRestType; + +public class LocatorInfoTest { + + @Test + public void testGetSetId() { + // Arrange + String expectedId = "testId"; + LocatorInfo locator = new LocatorInfo(null, + new LocatorRestType().setId(expectedId)); + + // Act + String actualId = locator.getId(); + + // Assert + assertEquals(expectedId, actualId); + } + + @Test + public void testGetSetExpirationDateTime() { + // Arrange + Date expectedExpirationDateTime = new Date(); + LocatorInfo locatorInfo = new LocatorInfo(null, + new LocatorRestType() + .setExpirationDateTime(expectedExpirationDateTime)); + + // Act + Date actualExpirationDateTime = locatorInfo.getExpirationDateTime(); + + // Assert + assertEquals(expectedExpirationDateTime, actualExpirationDateTime); + } + + @Test + public void testGetSetType() { + // Arrange + LocatorType expectedLocatorType = LocatorType.SAS; + LocatorInfo locatorInfo = new LocatorInfo(null, + new LocatorRestType().setType(expectedLocatorType.getCode())); + + // Act + LocatorType actualLocatorType = locatorInfo.getLocatorType(); + + // Assert + assertEquals(expectedLocatorType, actualLocatorType); + } + + @Test + public void testGetSetPath() { + // Arrange + String expectedPath = "testPath"; + LocatorInfo locatorInfo = new LocatorInfo(null, + new LocatorRestType().setPath(expectedPath)); + + // Act + String actualPath = locatorInfo.getPath(); + + // Assert + assertEquals(expectedPath, actualPath); + } + + @Test + public void testGetSetAccessPolicyId() { + // Arrange + String expectedAccessPolicyId = "testAccessPolicyId"; + LocatorInfo locatorInfo = new LocatorInfo(null, + new LocatorRestType().setAccessPolicyId(expectedAccessPolicyId)); + + // Act + String actualAccessPolicyId = locatorInfo.getAccessPolicyId(); + + // Assert + assertEquals(expectedAccessPolicyId, actualAccessPolicyId); + } + + @Test + public void testGetSetAssetId() { + // Arrange + String expectedAssetId = "testAssetId"; + LocatorInfo locatorInfo = new LocatorInfo(null, + new LocatorRestType().setAssetId(expectedAssetId)); + + // Act + String actualAssetId = locatorInfo.getAssetId(); + + // Assert + assertEquals(expectedAssetId, actualAssetId); + } + + @Test + public void testGetSetStartTime() { + // Arrange + Date expectedStartTime = new Date(); + LocatorInfo locatorInfo = new LocatorInfo(null, + new LocatorRestType().setStartTime(expectedStartTime)); + + // Act + Date actualStartTime = locatorInfo.getStartTime(); + + // Assert + assertEquals(expectedStartTime, actualStartTime); + } + + @Test + public void testGetSetBaseUri() { + // Arrange + String expectedBaseUri = "testBaseUri"; + LocatorInfo locatorInfo = new LocatorInfo(null, + new LocatorRestType().setBaseUri(expectedBaseUri)); + + // Act + String actualBaseUri = locatorInfo.getBaseUri(); + + // Assert + assertEquals(expectedBaseUri, actualBaseUri); + } + + @Test + public void testGetSetContentAccessComponent() { + // Arrange + String expectedContentAccessComponent = "testContentAccessToken"; + LocatorInfo locatorInfo = new LocatorInfo( + null, + new LocatorRestType() + .setContentAccessComponent(expectedContentAccessComponent)); + + // Act + String actualContentAccessComponent = locatorInfo + .getContentAccessToken(); + + // Assert + assertEquals(expectedContentAccessComponent, + actualContentAccessComponent); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorEntityTest.java similarity index 93% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorEntityTest.java index 33de16847679f..f3c3f572d7ef8 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorEntityTest.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; @@ -35,7 +35,8 @@ public void listMediaProcessorsReturnsExpectedUri() { @Test public void listMediaProcessorsCanTakeQueryParmeters() { - EntityListOperation lister = MediaProcessor.list().setTop(10).setSkip(2); + EntityListOperation lister = MediaProcessor.list() + .setTop(10).setSkip(2); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfoTest.java similarity index 95% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfoTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfoTest.java index 72d87f2db4c0c..b161eafbe2c8f 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfoTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/MediaProcessorInfoTest.java @@ -14,7 +14,7 @@ */ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; @@ -26,9 +26,10 @@ public class MediaProcessorInfoTest { public void testGetSetId() { // Arrange String expectedId = "expectedId"; - MediaProcessorInfo mediaProcessorInfo = new MediaProcessorInfo(null, new MediaProcessorType().setId(expectedId)); + MediaProcessorInfo mediaProcessorInfo = new MediaProcessorInfo(null, + new MediaProcessorType().setId(expectedId)); - // Act + // Act String actualId = mediaProcessorInfo.getId(); // Assert @@ -58,7 +59,7 @@ public void testGetSetDescription() throws Exception { MediaProcessorInfo mediaProcessorInfo = new MediaProcessorInfo(null, new MediaProcessorType().setDescription(expectedDescription)); - // Act + // Act String actualDescription = mediaProcessorInfo.getDescription(); // Assert diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointEntityTest.java similarity index 77% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointEntityTest.java index a1b2b0c094181..03e8c9ce0ea48 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointEntityTest.java @@ -15,13 +15,15 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.net.URLEncoder; import org.junit.Test; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.entityoperations.EntityDeleteOperation; import com.microsoft.windowsazure.services.media.entityoperations.EntityGetOperation; import com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation; @@ -34,7 +36,8 @@ */ public class NotificationEndPointEntityTest { static final String sampleNotificationEndPointId = "nb:cid:UUID:1151b8bd-9ada-4e7f-9787-8dfa49968eab"; - private final String expectedUri = String.format("NotificationEndPoints('%s')", + private final String expectedUri = String.format( + "NotificationEndPoints('%s')", URLEncoder.encode(sampleNotificationEndPointId, "UTF-8")); private final String testNotificationEndPoint = "testNotificationEndPoint"; private final String testQueueName = "testqueue"; @@ -43,9 +46,11 @@ public NotificationEndPointEntityTest() throws Exception { } @Test - public void NotificationEndPointCreateReturnsDefaultCreatePayload() throws ServiceException { - NotificationEndPointType payload = (NotificationEndPointType) NotificationEndPoint.create( - testNotificationEndPoint, EndPointType.AzureQueue, testQueueName).getRequestContents(); + public void NotificationEndPointCreateReturnsDefaultCreatePayload() + throws ServiceException { + NotificationEndPointType payload = (NotificationEndPointType) NotificationEndPoint + .create(testNotificationEndPoint, EndPointType.AzureQueue, + testQueueName).getRequestContents(); assertNotNull(payload); assertNull(payload.getId()); @@ -59,10 +64,11 @@ public void NotificationEndPointCreateReturnsDefaultCreatePayload() throws Servi public void NotificationEndPointCreateCanSetNotificationEndPointName() { String name = "NotificationEndPointCreateCanSetNotificationEndPointName"; - NotificationEndPoint.Creator creator = (Creator) NotificationEndPoint.create(name, EndPointType.AzureQueue, - testQueueName); + NotificationEndPoint.Creator creator = (Creator) NotificationEndPoint + .create(name, EndPointType.AzureQueue, testQueueName); - NotificationEndPointType payload = (NotificationEndPointType) creator.getRequestContents(); + NotificationEndPointType payload = (NotificationEndPointType) creator + .getRequestContents(); assertNotNull(payload); assertNull(payload.getId()); @@ -75,14 +81,16 @@ public void NotificationEndPointGetReturnsExpectedUri() throws Exception { String expectedUri = String.format("NotificationEndPoints('%s')", URLEncoder.encode(sampleNotificationEndPointId, "UTF-8")); - EntityGetOperation getter = NotificationEndPoint.get(sampleNotificationEndPointId); + EntityGetOperation getter = NotificationEndPoint + .get(sampleNotificationEndPointId); assertEquals(expectedUri, getter.getUri()); } @Test public void NotificationEndPointListReturnsExpectedUri() { - EntityListOperation lister = NotificationEndPoint.list(); + EntityListOperation lister = NotificationEndPoint + .list(); assertEquals("NotificationEndPoints", lister.getUri()); assertNotNull(lister.getQueryParameters()); @@ -91,7 +99,8 @@ public void NotificationEndPointListReturnsExpectedUri() { @Test public void NotificationEndPointListCanTakeQueryParameters() { - EntityListOperation lister = NotificationEndPoint.list().setTop(10).setSkip(2); + EntityListOperation lister = NotificationEndPoint + .list().setTop(10).setSkip(2); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); @@ -100,18 +109,20 @@ public void NotificationEndPointListCanTakeQueryParameters() { @Test public void NotificationEndPointListCanTakeQueryParametersChained() { - EntityListOperation lister = NotificationEndPoint.list().setTop(10).setSkip(2) - .set("filter", "something"); + EntityListOperation lister = NotificationEndPoint + .list().setTop(10).setSkip(2).set("filter", "something"); assertEquals("10", lister.getQueryParameters().getFirst("$top")); assertEquals("2", lister.getQueryParameters().getFirst("$skip")); - assertEquals("something", lister.getQueryParameters().getFirst("filter")); + assertEquals("something", lister.getQueryParameters() + .getFirst("filter")); assertEquals(3, lister.getQueryParameters().size()); } @Test public void NotificationEndPointUpdateReturnsExpectedUri() throws Exception { - EntityUpdateOperation updater = NotificationEndPoint.update(sampleNotificationEndPointId); + EntityUpdateOperation updater = NotificationEndPoint + .update(sampleNotificationEndPointId); assertEquals(expectedUri, updater.getUri()); } @@ -120,16 +131,19 @@ public void NotificationEndPointUpdateCanSetNameAndAltId() throws Exception { String expectedName = "newNotificationEndPointName"; - EntityUpdateOperation updater = NotificationEndPoint.update(sampleNotificationEndPointId).setName(expectedName); + EntityUpdateOperation updater = NotificationEndPoint.update( + sampleNotificationEndPointId).setName(expectedName); - NotificationEndPointType payload = (NotificationEndPointType) updater.getRequestContents(); + NotificationEndPointType payload = (NotificationEndPointType) updater + .getRequestContents(); assertEquals(expectedName, payload.getName()); } @Test public void NotificationEndPointDeleteReturnsExpectedUri() throws Exception { - EntityDeleteOperation deleter = NotificationEndPoint.delete(sampleNotificationEndPointId); + EntityDeleteOperation deleter = NotificationEndPoint + .delete(sampleNotificationEndPointId); assertEquals(expectedUri, deleter.getUri()); } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfoTest.java similarity index 76% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfoTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfoTest.java index 18331b5f38014..fb589ee8585cc 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfoTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/NotificationEndPointInfoTest.java @@ -14,7 +14,7 @@ */ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Date; @@ -28,10 +28,10 @@ public class NotificationEndPointInfoTest { public void testGetSetId() { // Arrange String expectedId = "expectedId"; - NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo(null, - new NotificationEndPointType().setId(expectedId)); + NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo( + null, new NotificationEndPointType().setId(expectedId)); - // Act + // Act String actualId = notificationEndPointInfo.getId(); // Assert @@ -43,8 +43,8 @@ public void testGetSetId() { public void testGetSetName() { // Arrange String expectedName = "notificationEndPointName"; - NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo(null, - new NotificationEndPointType().setName(expectedName)); + NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo( + null, new NotificationEndPointType().setName(expectedName)); // Act String actualName = notificationEndPointInfo.getName(); @@ -58,10 +58,11 @@ public void testGetSetCreated() throws Exception { // Arrange Date expectedCreated = new Date(); - NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo(null, + NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo( + null, new NotificationEndPointType().setCreated(expectedCreated)); - // Act + // Act Date actualCreated = notificationEndPointInfo.getCreated(); // Assert @@ -73,11 +74,14 @@ public void testGetSetCreated() throws Exception { public void testGetSetEndPointType() throws Exception { // Arrange EndPointType expectedEndPointType = EndPointType.AzureQueue; - NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo(null, - new NotificationEndPointType().setEndPointType(expectedEndPointType.getCode())); + NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo( + null, + new NotificationEndPointType() + .setEndPointType(expectedEndPointType.getCode())); // Act - EndPointType actualEndPointType = notificationEndPointInfo.getEndPointType(); + EndPointType actualEndPointType = notificationEndPointInfo + .getEndPointType(); // Assert assertEquals(expectedEndPointType, actualEndPointType); @@ -87,11 +91,14 @@ public void testGetSetEndPointType() throws Exception { public void testGetSetEndPointAddress() { // Arrange String expectedEndPointAddress = "testGetSetEndPointAddress"; - NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo(null, - new NotificationEndPointType().setEndPointAddress(expectedEndPointAddress)); + NotificationEndPointInfo notificationEndPointInfo = new NotificationEndPointInfo( + null, + new NotificationEndPointType() + .setEndPointAddress(expectedEndPointAddress)); // Act - String actualEndPointAddress = notificationEndPointInfo.getEndPointAddress(); + String actualEndPointAddress = notificationEndPointInfo + .getEndPointAddress(); // Assert assertEquals(expectedEndPointAddress, actualEndPointAddress); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyEntityTest.java similarity index 75% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyEntityTest.java index 79991d82f0d2b..91889681025f9 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/ProtectionKeyEntityTest.java @@ -15,7 +15,7 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.List; @@ -31,19 +31,23 @@ public ProtectionKeyEntityTest() throws Exception { @Test public void ProtectionKeyIdReturnsPayloadWithTheRightProtectionKeyType() { - List contentKeyTypeArray = ProtectionKey.getProtectionKeyId(ContentKeyType.StorageEncryption) + List contentKeyTypeArray = ProtectionKey + .getProtectionKeyId(ContentKeyType.StorageEncryption) .getQueryParameters().get("contentKeyType"); String actualContentKeyType = contentKeyTypeArray.get(0); - assertEquals(ContentKeyType.StorageEncryption.getCode(), Integer.parseInt(actualContentKeyType)); + assertEquals(ContentKeyType.StorageEncryption.getCode(), + Integer.parseInt(actualContentKeyType)); } @Test public void ProtectionKeyReturnsPayloadWithTheRightProtectionKeyId() { String expectedProtectionKeyId = "expectedProtectionKey"; - String actualProtectionKeyId = ProtectionKey.getProtectionKey(expectedProtectionKeyId).getQueryParameters() + String actualProtectionKeyId = ProtectionKey + .getProtectionKey(expectedProtectionKeyId).getQueryParameters() .getFirst("ProtectionKeyId"); - expectedProtectionKeyId = String.format("'%s'", expectedProtectionKeyId); + expectedProtectionKeyId = String + .format("'%s'", expectedProtectionKeyId); assertEquals(expectedProtectionKeyId, actualProtectionKeyId); } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/TaskEntityTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/TaskEntityTest.java similarity index 82% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/TaskEntityTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/media/models/TaskEntityTest.java index 42d312f16d4cd..7927eff9a1391 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/TaskEntityTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/TaskEntityTest.java @@ -15,7 +15,8 @@ package com.microsoft.windowsazure.services.media.models; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import javax.xml.bind.JAXBElement; @@ -42,7 +43,8 @@ private TaskType getTaskType(EntryType entryType) { if (grandChild instanceof JAXBElement) { @SuppressWarnings("rawtypes") JAXBElement contentElement = (JAXBElement) grandChild; - TaskType taskType = (TaskType) contentElement.getValue(); + TaskType taskType = (TaskType) contentElement + .getValue(); return taskType; } } @@ -61,7 +63,8 @@ public void taskCreateReturnsDefaultCreatePayload() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody).getEntryType()); + TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, + expectedTaskBody).getEntryType()); assertNotNull(taskType); assertEquals(expectedMediaProcessorId, taskType.getMediaProcessorId()); @@ -75,8 +78,9 @@ public void taskCreateCanSetTaskName() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody).setName(expectedName) - .getEntryType()); + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) + .setName(expectedName).getEntryType()); assertNotNull(taskType); assertEquals(expectedName, taskType.getName()); @@ -89,7 +93,8 @@ public void taskCreateCanSetConfiguration() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody) + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) .setConfiguration(expectedConfiguration).getEntryType()); assertNotNull(taskType); @@ -103,7 +108,8 @@ public void taskCreateCanSetPriority() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody) + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) .setPriority(expectedPriority).getEntryType()); assertNotNull(taskType); @@ -117,7 +123,8 @@ public void taskCreateCanSetTaskBody() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody) + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) .setTaskBody(expectedTaskBodyResult).getEntryType()); assertNotNull(taskType); @@ -131,7 +138,8 @@ public void taskCreateCanSetEncryptionKeyId() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody) + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) .setEncryptionKeyId(expectedEncryptionKeyId).getEntryType()); assertNotNull(taskType); @@ -145,7 +153,8 @@ public void taskCreateCanSetEncryptionScheme() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody) + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) .setEncryptionScheme(expectedEncryptionScheme).getEntryType()); assertNotNull(taskType); @@ -159,7 +168,8 @@ public void taskCreateCanSetEncryptionVersion() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody) + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) .setEncryptionVersion(expectedEncryptionVersion).getEntryType()); assertNotNull(taskType); @@ -173,10 +183,13 @@ public void taskCreateCanSetInitializationVector() { String expectedMediaProcessorId = "expectedMediaProcessorId"; String expectedTaskBody = "expectedTaskBody"; - TaskType taskType = getTaskType(Task.create(expectedMediaProcessorId, expectedTaskBody) - .setInitializationVector(expectedInitializationVector).getEntryType()); + TaskType taskType = getTaskType(Task + .create(expectedMediaProcessorId, expectedTaskBody) + .setInitializationVector(expectedInitializationVector) + .getEntryType()); assertNotNull(taskType); - assertEquals(expectedInitializationVector, taskType.getInitializationVector()); + assertEquals(expectedInitializationVector, + taskType.getInitializationVector()); } } diff --git a/media/src/test/java/com/microsoft/windowsazure/services/media/models/TaskInfoTest.java b/media/src/test/java/com/microsoft/windowsazure/services/media/models/TaskInfoTest.java new file mode 100644 index 0000000000000..ec0f74296fa5d --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/media/models/TaskInfoTest.java @@ -0,0 +1,292 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.media.models; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.media.implementation.content.ErrorDetailType; +import com.microsoft.windowsazure.services.media.implementation.content.TaskType; + +public class TaskInfoTest { + + @Test + public void testGetSetId() { + // Arrange + String expectedId = "expectedId"; + TaskInfo taskInfo = new TaskInfo(null, new TaskType().setId(expectedId)); + + // Act + String actualId = taskInfo.getId(); + + // Assert + assertEquals(expectedId, actualId); + + } + + @Test + public void testGetSetConfiguration() { + // Arrange + String expectedConfiguration = "expectedConfiguration"; + TaskInfo taskInfo = new TaskInfo(null, + new TaskType().setConfiguration(expectedConfiguration)); + + // Act + String actualConfiguration = taskInfo.getConfiguration(); + + // Assert + assertEquals(expectedConfiguration, actualConfiguration); + } + + @Test + public void testGetSetEndTime() throws Exception { + // Arrange + Date expectedEndTime = new Date(); + + TaskInfo taskInfo = new TaskInfo(null, + new TaskType().setEndTime(expectedEndTime)); + + // Act + Date actualEndTime = taskInfo.getEndTime(); + + // Assert + assertEquals(expectedEndTime, actualEndTime); + + } + + @Test + public void testGetSetErrorDetails() throws Exception { + // Arrange + List expectedErrorDetails = new ArrayList(); + List expectedErrorDetailsType = new ArrayList(); + for (ErrorDetailType errorDetailType : expectedErrorDetailsType) { + ErrorDetail errorDetail = new ErrorDetail( + errorDetailType.getCode(), errorDetailType.getMessage()); + expectedErrorDetails.add(errorDetail); + } + TaskInfo taskInfo = new TaskInfo(null, + new TaskType().setErrorDetails(expectedErrorDetailsType)); + + // Act + List actualErrorDetails = taskInfo.getErrorDetails(); + + // Assert + assertEquals(expectedErrorDetails, actualErrorDetails); + } + + @Test + public void testGetSetMediaProcessorId() { + // Arrange + String expectedName = "testName"; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setName(expectedName)); + + // Act + String actualName = TaskInfo.getName(); + + // Assert + assertEquals(expectedName, actualName); + } + + @Test + public void testGetSetName() { + // Arrange + + TaskOption expectedOptions = TaskOption.None; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setOptions(expectedOptions.getCode())); + + // Act + TaskOption actualOptions = TaskInfo.getOptions(); + + // Assert + assertEquals(expectedOptions, actualOptions); + } + + @Test + public void testGetSetPerfMessage() { + // Arrange + String expectedPerfMessage = "testGetSetPerfMessage"; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setPerfMessage(expectedPerfMessage)); + + // Act + String actualPerfMessage = TaskInfo.getPerfMessage(); + + // Assert + assertEquals(expectedPerfMessage, actualPerfMessage); + } + + @Test + public void testGetSetPriority() { + // Arrange + int expectedPriority = 3; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setPriority(expectedPriority)); + + // Act + int actualPriority = TaskInfo.getPriority(); + + // Assert + assertEquals(expectedPriority, actualPriority); + } + + @Test + public void testGetSetProgress() { + // Arrange + double expectedProgress = 3; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setProgress(expectedProgress)); + + // Act + double actualProgress = TaskInfo.getProgress(); + + // Assert + assertEquals(expectedProgress, actualProgress, 0.00001); + } + + @Test + public void testGetSetRunningDuration() { + // Arrange + double expectedRunningDuration = 3; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setRunningDuration(expectedRunningDuration)); + + // Act + double actualRunningDuration = TaskInfo.getRunningDuration(); + + // Assert + assertEquals(expectedRunningDuration, actualRunningDuration, 0.00001); + } + + @Test + public void testGetSetStartTime() { + // Arrange + Date expectedStartTime = new Date(); + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setStartTime(expectedStartTime)); + + // Act + Date actualStartTime = TaskInfo.getStartTime(); + + // Assert + assertEquals(expectedStartTime, actualStartTime); + } + + @Test + public void testGetSetState() { + // Arrange + TaskState expectedState = TaskState.Completed; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setState(expectedState.getCode())); + + // Act + TaskState actualState = TaskInfo.getState(); + + // Assert + assertEquals(expectedState, actualState); + } + + @Test + public void testGetSetTaskBody() { + // Arrange + String expectedTaskBody = "getSetTaskBody"; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setTaskBody(expectedTaskBody)); + + // Act + String actualTaskBody = TaskInfo.getTaskBody(); + + // Assert + assertEquals(expectedTaskBody, actualTaskBody); + } + + @Test + public void testGetSetOptions() { + // Arrange + TaskOption expectedTaskOption = TaskOption.ProtectedConfiguration; + TaskInfo TaskInfo = new TaskInfo(null, + new TaskType().setOptions(expectedTaskOption.getCode())); + + // Act + TaskOption actualTaskOption = TaskInfo.getOptions(); + + // Assert + assertEquals(expectedTaskOption, actualTaskOption); + } + + @Test + public void testGetSetEncryptionKeyId() { + // Arrange + String expectedEncryptionKeyId = "getSetEncryptionKeyId"; + TaskInfo taskInfo = new TaskInfo(null, + new TaskType().setEncryptionKeyId(expectedEncryptionKeyId)); + + // Act + String actualEncryptionKeyId = taskInfo.getEncryptionKeyId(); + + // Assert + assertEquals(expectedEncryptionKeyId, actualEncryptionKeyId); + } + + @Test + public void testGetSetEncryptionScheme() { + // Arrange + String expectedEncryptionScheme = "getSetEncryptionScheme"; + TaskInfo taskInfo = new TaskInfo(null, + new TaskType().setEncryptionScheme(expectedEncryptionScheme)); + + // Act + String actualEncryptionScheme = taskInfo.getEncryptionScheme(); + + // Assert + assertEquals(expectedEncryptionScheme, actualEncryptionScheme); + } + + @Test + public void testGetSetEncryptionVersion() { + // Arrange + String expectedEncryptionVersion = "1.5"; + TaskInfo taskInfo = new TaskInfo(null, + new TaskType().setEncryptionVersion(expectedEncryptionVersion)); + + // Act + String actualEncryptionVersion = taskInfo.getEncryptionVersion(); + + // Assert + assertEquals(expectedEncryptionVersion, actualEncryptionVersion); + } + + @Test + public void testGetSetInitializationVector() { + // Arrange + String expectedInitializationVector = "testInitializationVector"; + TaskInfo taskInfo = new TaskInfo(null, + new TaskType() + .setEncryptionVersion(expectedInitializationVector)); + + // Act + String actualInitializationVector = taskInfo.getEncryptionVersion(); + + // Assert + assertEquals(expectedInitializationVector, actualInitializationVector); + } + +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/queue/IntegrationTestBase.java b/media/src/test/java/com/microsoft/windowsazure/services/queue/IntegrationTestBase.java new file mode 100644 index 0000000000000..307cccf73d39a --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/queue/IntegrationTestBase.java @@ -0,0 +1,45 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.queue; + +import com.microsoft.windowsazure.Configuration; + +public abstract class IntegrationTestBase { + protected static Configuration createConfiguration() { + Configuration config = Configuration.getInstance(); + overrideWithEnv(config, QueueConfiguration.ACCOUNT_NAME); + overrideWithEnv(config, QueueConfiguration.ACCOUNT_KEY); + overrideWithEnv(config, QueueConfiguration.URI); + return config; + } + + private static void overrideWithEnv(Configuration config, String key) { + String value = System.getenv(key); + if (value == null) + return; + + config.setProperty(key, value); + } + + protected static boolean isRunningWithEmulator(Configuration config) { + String accountName = "devstoreaccount1"; + String accountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; + + return accountName.equals(config + .getProperty(QueueConfiguration.ACCOUNT_NAME)) + && accountKey.equals(config + .getProperty(QueueConfiguration.ACCOUNT_KEY)); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/QueueServiceIntegrationTest.java b/media/src/test/java/com/microsoft/windowsazure/services/queue/QueueServiceIntegrationTest.java similarity index 86% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/QueueServiceIntegrationTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/queue/QueueServiceIntegrationTest.java index c8fc533a59e27..af2db32d929ba 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/QueueServiceIntegrationTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/queue/QueueServiceIntegrationTest.java @@ -14,7 +14,10 @@ */ package com.microsoft.windowsazure.services.queue; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.util.Date; import java.util.GregorianCalendar; @@ -29,9 +32,8 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.ServiceExceptionMatcher; +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.queue.models.CreateQueueOptions; import com.microsoft.windowsazure.services.queue.models.GetQueueMetadataResult; import com.microsoft.windowsazure.services.queue.models.ListMessagesOptions; @@ -59,6 +61,7 @@ public class QueueServiceIntegrationTest extends IntegrationTestBase { private static String CREATABLE_QUEUE_1; private static String CREATABLE_QUEUE_2; private static String CREATABLE_QUEUE_3; + private static String CREATABLE_QUEUE_4; private static String[] creatableQueues; private static String[] testQueues; private static QueueContract service; @@ -78,7 +81,8 @@ public static void setup() throws Exception { creatableQueues = new String[10]; for (int i = 0; i < creatableQueues.length; i++) { - creatableQueues[i] = String.format("%s%d", createableQueuesPrefix, i + 1); + creatableQueues[i] = String.format("%s%d", createableQueuesPrefix, + i + 1); } TEST_QUEUE_FOR_MESSAGES = testQueues[0]; @@ -93,6 +97,7 @@ public static void setup() throws Exception { CREATABLE_QUEUE_1 = creatableQueues[0]; CREATABLE_QUEUE_2 = creatableQueues[1]; CREATABLE_QUEUE_3 = creatableQueues[2]; + CREATABLE_QUEUE_4 = creatableQueues[3]; // Create all test containers and their content config = createConfiguration(); @@ -108,7 +113,8 @@ public static void cleanup() throws Exception { deleteQueues(service, createableQueuesPrefix, creatableQueues); } - private static void createQueues(QueueContract service, String prefix, String[] list) throws Exception { + private static void createQueues(QueueContract service, String prefix, + String[] list) throws Exception { Set containers = listQueues(service, prefix); for (String item : list) { if (!containers.contains(item)) { @@ -117,7 +123,8 @@ private static void createQueues(QueueContract service, String prefix, String[] } } - private static void deleteQueues(QueueContract service, String prefix, String[] list) throws Exception { + private static void deleteQueues(QueueContract service, String prefix, + String[] list) throws Exception { Set containers = listQueues(service, prefix); for (String item : list) { if (containers.contains(item)) { @@ -126,9 +133,11 @@ private static void deleteQueues(QueueContract service, String prefix, String[] } } - private static Set listQueues(QueueContract service, String prefix) throws Exception { + private static Set listQueues(QueueContract service, String prefix) + throws Exception { HashSet result = new HashSet(); - ListQueuesResult list = service.listQueues(new ListQueuesOptions().setPrefix(prefix)); + ListQueuesResult list = service.listQueues(new ListQueuesOptions() + .setPrefix(prefix)); for (Queue item : list.getQueues()) { result.add(item.getName()); } @@ -139,7 +148,8 @@ private static Set listQueues(QueueContract service, String prefix) thro public void getServicePropertiesWorks() throws Exception { // Arrange - // Don't run this test with emulator, as v1.6 doesn't support this method + // Don't run this test with emulator, as v1.6 doesn't support this + // method if (isRunningWithEmulator(config)) { return; } @@ -160,7 +170,8 @@ public void getServicePropertiesWorks() throws Exception { public void setServicePropertiesWorks() throws Exception { // Arrange - // Don't run this test with emulator, as v1.6 doesn't support this method + // Don't run this test with emulator, as v1.6 doesn't support this + // method if (isRunningWithEmulator(config)) { return; } @@ -189,7 +200,8 @@ public void createQueueWorks() throws Exception { // Act service.createQueue(CREATABLE_QUEUE_1); - GetQueueMetadataResult result = service.getQueueMetadata(CREATABLE_QUEUE_1); + GetQueueMetadataResult result = service + .getQueueMetadata(CREATABLE_QUEUE_1); service.deleteQueue(CREATABLE_QUEUE_1); // Assert @@ -201,15 +213,15 @@ public void createQueueWorks() throws Exception { @Test public void deleteQueueWorks() throws Exception { - // Arrange + // Arrange expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.createQueue(CREATABLE_QUEUE_1); + service.createQueue(CREATABLE_QUEUE_4); // Act - service.deleteQueue(CREATABLE_QUEUE_1); - GetQueueMetadataResult result = service.getQueueMetadata(CREATABLE_QUEUE_1); + service.deleteQueue(CREATABLE_QUEUE_4); + GetQueueMetadataResult result = service + .getQueueMetadata(CREATABLE_QUEUE_4); // Assert assertNull(result); @@ -220,9 +232,10 @@ public void createQueueWithOptionsWorks() throws Exception { // Arrange // Act - service.createQueue(CREATABLE_QUEUE_2, - new CreateQueueOptions().addMetadata("foo", "bar").addMetadata("test", "blah")); - GetQueueMetadataResult result = service.getQueueMetadata(CREATABLE_QUEUE_2); + service.createQueue(CREATABLE_QUEUE_2, new CreateQueueOptions() + .addMetadata("foo", "bar").addMetadata("test", "blah")); + GetQueueMetadataResult result = service + .getQueueMetadata(CREATABLE_QUEUE_2); service.deleteQueue(CREATABLE_QUEUE_2); // Assert @@ -255,10 +268,11 @@ public void listQueuesWithOptionsWorks() throws Exception { // Arrange // Act - ListQueuesResult result = service.listQueues(new ListQueuesOptions().setMaxResults(3).setPrefix( - testQueuesPrefix)); - ListQueuesResult result2 = service.listQueues(new ListQueuesOptions().setMarker(result.getNextMarker()) - .setPrefix(testQueuesPrefix).setIncludeMetadata(true)); + ListQueuesResult result = service.listQueues(new ListQueuesOptions() + .setMaxResults(3).setPrefix(testQueuesPrefix)); + ListQueuesResult result2 = service.listQueues(new ListQueuesOptions() + .setMarker(result.getNextMarker()).setPrefix(testQueuesPrefix) + .setIncludeMetadata(true)); // Assert assertNotNull(result); @@ -296,7 +310,8 @@ public void setQueueMetadataWorks() throws Exception { metadata.put("test", "blah"); service.setQueueMetadata(CREATABLE_QUEUE_3, metadata); - GetQueueMetadataResult result = service.getQueueMetadata(CREATABLE_QUEUE_3); + GetQueueMetadataResult result = service + .getQueueMetadata(CREATABLE_QUEUE_3); service.deleteQueue(CREATABLE_QUEUE_3); @@ -324,7 +339,7 @@ public void createMessageWorks() throws Exception { @Test public void createNullMessageException() throws Exception { - // Arrange + // Arrange // Act expectedException.expect(NullPointerException.class); @@ -344,7 +359,8 @@ public void listMessagesWorks() throws Exception { service.createMessage(TEST_QUEUE_FOR_MESSAGES_2, "message2"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_2, "message3"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_2, "message4"); - ListMessagesResult result = service.listMessages(TEST_QUEUE_FOR_MESSAGES_2); + ListMessagesResult result = service + .listMessages(TEST_QUEUE_FOR_MESSAGES_2); // Assert assertNotNull(result); @@ -380,8 +396,10 @@ public void listMessagesWithOptionsWorks() throws Exception { service.createMessage(TEST_QUEUE_FOR_MESSAGES_3, "message2"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_3, "message3"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_3, "message4"); - ListMessagesResult result = service.listMessages(TEST_QUEUE_FOR_MESSAGES_3, new ListMessagesOptions() - .setNumberOfMessages(4).setVisibilityTimeoutInSeconds(20)); + ListMessagesResult result = service.listMessages( + TEST_QUEUE_FOR_MESSAGES_3, + new ListMessagesOptions().setNumberOfMessages(4) + .setVisibilityTimeoutInSeconds(20)); // Assert assertNotNull(result); @@ -418,7 +436,8 @@ public void peekMessagesWorks() throws Exception { service.createMessage(TEST_QUEUE_FOR_MESSAGES_4, "message2"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_4, "message3"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_4, "message4"); - PeekMessagesResult result = service.peekMessages(TEST_QUEUE_FOR_MESSAGES_4); + PeekMessagesResult result = service + .peekMessages(TEST_QUEUE_FOR_MESSAGES_4); // Assert assertNotNull(result); @@ -451,7 +470,8 @@ public void peekMessagesWithOptionsWorks() throws Exception { service.createMessage(TEST_QUEUE_FOR_MESSAGES_5, "message2"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_5, "message3"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_5, "message4"); - PeekMessagesResult result = service.peekMessages(TEST_QUEUE_FOR_MESSAGES_5, + PeekMessagesResult result = service.peekMessages( + TEST_QUEUE_FOR_MESSAGES_5, new PeekMessagesOptions().setNumberOfMessages(4)); // Assert @@ -484,7 +504,8 @@ public void clearMessagesWorks() throws Exception { service.createMessage(TEST_QUEUE_FOR_MESSAGES_6, "message4"); service.clearMessages(TEST_QUEUE_FOR_MESSAGES_6); - PeekMessagesResult result = service.peekMessages(TEST_QUEUE_FOR_MESSAGES_6); + PeekMessagesResult result = service + .peekMessages(TEST_QUEUE_FOR_MESSAGES_6); // Assert assertNotNull(result); @@ -501,10 +522,13 @@ public void deleteMessageWorks() throws Exception { service.createMessage(TEST_QUEUE_FOR_MESSAGES_7, "message3"); service.createMessage(TEST_QUEUE_FOR_MESSAGES_7, "message4"); - ListMessagesResult result = service.listMessages(TEST_QUEUE_FOR_MESSAGES_7); - service.deleteMessage(TEST_QUEUE_FOR_MESSAGES_7, result.getQueueMessages().get(0).getMessageId(), result + ListMessagesResult result = service + .listMessages(TEST_QUEUE_FOR_MESSAGES_7); + service.deleteMessage(TEST_QUEUE_FOR_MESSAGES_7, result + .getQueueMessages().get(0).getMessageId(), result .getQueueMessages().get(0).getPopReceipt()); - ListMessagesResult result2 = service.listMessages(TEST_QUEUE_FOR_MESSAGES_7, + ListMessagesResult result2 = service.listMessages( + TEST_QUEUE_FOR_MESSAGES_7, new ListMessagesOptions().setNumberOfMessages(32)); // Assert @@ -523,7 +547,8 @@ public void updateNullMessageException() throws Exception { // Act expectedException.expect(NullPointerException.class); - service.updateMessage(TEST_QUEUE_FOR_MESSAGES_8, messageId, popReceipt, messageText, visibilityTimeoutInSeconds); + service.updateMessage(TEST_QUEUE_FOR_MESSAGES_8, messageId, popReceipt, + messageText, visibilityTimeoutInSeconds); } @@ -538,11 +563,14 @@ public void updateMessageWorks() throws Exception { // Act service.createMessage(TEST_QUEUE_FOR_MESSAGES_8, "message1"); - ListMessagesResult listResult1 = service.listMessages(TEST_QUEUE_FOR_MESSAGES_8); - UpdateMessageResult updateResult = service.updateMessage(TEST_QUEUE_FOR_MESSAGES_8, listResult1 - .getQueueMessages().get(0).getMessageId(), listResult1.getQueueMessages().get(0).getPopReceipt(), - "new text", 0); - ListMessagesResult listResult2 = service.listMessages(TEST_QUEUE_FOR_MESSAGES_8); + ListMessagesResult listResult1 = service + .listMessages(TEST_QUEUE_FOR_MESSAGES_8); + UpdateMessageResult updateResult = service.updateMessage( + TEST_QUEUE_FOR_MESSAGES_8, listResult1.getQueueMessages() + .get(0).getMessageId(), listResult1.getQueueMessages() + .get(0).getPopReceipt(), "new text", 0); + ListMessagesResult listResult2 = service + .listMessages(TEST_QUEUE_FOR_MESSAGES_8); // Assert assertNotNull(updateResult); @@ -553,7 +581,8 @@ public void updateMessageWorks() throws Exception { assertNotNull(listResult2); QueueMessage entry = listResult2.getQueueMessages().get(0); - assertEquals(listResult1.getQueueMessages().get(0).getMessageId(), entry.getMessageId()); + assertEquals(listResult1.getQueueMessages().get(0).getMessageId(), + entry.getMessageId()); assertEquals("new text", entry.getMessageText()); assertNotNull(entry.getPopReceipt()); assertEquals(2, entry.getDequeueCount()); diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceScenarioTest.java b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceScenarioTest.java similarity index 76% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceScenarioTest.java rename to media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceScenarioTest.java index 0d4ef704f2233..0087cfcb2ee42 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceScenarioTest.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceScenarioTest.java @@ -15,7 +15,8 @@ package com.microsoft.windowsazure.services.scenarios; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import java.io.InputStream; import java.util.ArrayList; @@ -28,7 +29,7 @@ import org.junit.BeforeClass; import org.junit.Test; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.services.media.MediaContract; import com.microsoft.windowsazure.services.media.MediaService; import com.microsoft.windowsazure.services.media.models.AssetInfo; @@ -63,8 +64,10 @@ public static void cleanup() throws ServiceException { @Test public void newAsset() throws Exception { - AssetInfo asset = wrapper.createAsset(testAssetPrefix + "newAsset", AssetOption.None); - validator.validateAsset(asset, testAssetPrefix + "newAsset", AssetOption.None); + AssetInfo asset = wrapper.createAsset(testAssetPrefix + "newAsset", + AssetOption.None); + validator.validateAsset(asset, testAssetPrefix + "newAsset", + AssetOption.None); } @Test @@ -77,14 +80,16 @@ public void pageOverAssets() throws ServiceException { } signalSetupFinished(); - List> pages = wrapper.getAssetSortedPagedResults(rootName, 3); + List> pages = wrapper.getAssetSortedPagedResults( + rootName, 3); validator.validateAssetSortedPages(pages, assetNames, 3); } @Test public void uploadFiles() throws Exception { signalSetupStarting(); - AssetInfo asset = wrapper.createAsset(testAssetPrefix + "uploadFiles", AssetOption.None); + AssetInfo asset = wrapper.createAsset(testAssetPrefix + "uploadFiles", + AssetOption.None); signalSetupFinished(); wrapper.uploadFilesToAsset(asset, 10, getTestAssetFiles()); @@ -95,7 +100,8 @@ public void uploadFiles() throws Exception { public void uploadEncryptedFiles() throws Exception { signalSetupStarting(); byte[] aesKey = getNewAesKey(); - AssetInfo asset = wrapper.createAsset(testAssetPrefix + "uploadEncryptedFiles", AssetOption.StorageEncrypted); + AssetInfo asset = wrapper.createAsset(testAssetPrefix + + "uploadEncryptedFiles", AssetOption.StorageEncrypted); signalSetupFinished(); @@ -106,18 +112,21 @@ public void uploadEncryptedFiles() throws Exception { @Test public void downloadFiles() throws Exception { signalSetupStarting(); - AssetInfo asset = wrapper.createAsset(testAssetPrefix + "downloadFiles", AssetOption.None); + AssetInfo asset = wrapper.createAsset( + testAssetPrefix + "downloadFiles", AssetOption.None); wrapper.uploadFilesToAsset(asset, 10, getTestAssetFiles()); signalSetupFinished(); - Hashtable actualFileStreams = wrapper.downloadFilesFromAsset(asset, 10); + Hashtable actualFileStreams = wrapper + .downloadFilesFromAsset(asset, 10); validator.validateAssetFiles(getTestAssetFiles(), actualFileStreams); } @Test public void createJob() throws Exception { signalSetupStarting(); - AssetInfo asset = wrapper.createAsset(testAssetPrefix + "createJob", AssetOption.None); + AssetInfo asset = wrapper.createAsset(testAssetPrefix + "createJob", + AssetOption.None); wrapper.uploadFilesToAsset(asset, 10, getTestAssetFiles()); signalSetupFinished(); @@ -129,36 +138,42 @@ public void createJob() throws Exception { @Test public void transformAsset() throws Exception { signalSetupStarting(); - AssetInfo asset = wrapper.createAsset(testAssetPrefix + "transformAsset", AssetOption.None); + AssetInfo asset = wrapper.createAsset(testAssetPrefix + + "transformAsset", AssetOption.None); wrapper.uploadFilesToAsset(asset, 10, getTestAssetFiles()); String jobName = testJobPrefix + UUID.randomUUID().toString(); - JobInfo job = wrapper.createJob(jobName, asset, - wrapper.createTaskOptions("Transform", 0, 0, EncoderType.WindowsAzureMediaEncoder)); + JobInfo job = wrapper.createJob(jobName, asset, wrapper + .createTaskOptions("Transform", 0, 0, + EncoderType.WindowsAzureMediaEncoder)); signalSetupFinished(); waitForJobToFinish(job); List outputAssets = wrapper.getJobOutputMediaAssets(job); - validator.validateOutputAssets(outputAssets, getTestAssetFiles().keys()); + validator + .validateOutputAssets(outputAssets, getTestAssetFiles().keys()); } @Test public void transformEncryptedAsset() throws Exception { signalSetupStarting(); byte[] aesKey = getNewAesKey(); - AssetInfo asset = wrapper - .createAsset(testAssetPrefix + "transformEncryptedAsset", AssetOption.StorageEncrypted); + AssetInfo asset = wrapper.createAsset(testAssetPrefix + + "transformEncryptedAsset", AssetOption.StorageEncrypted); wrapper.uploadFilesToAsset(asset, 10, getTestAssetFiles(), aesKey); - String jobName = "my job transformEncryptedAsset" + UUID.randomUUID().toString(); - JobInfo job = wrapper.createJob(jobName, asset, - wrapper.createTaskOptions("Decode", 0, 0, EncoderType.StorageDecryption)); + String jobName = "my job transformEncryptedAsset" + + UUID.randomUUID().toString(); + JobInfo job = wrapper.createJob(jobName, asset, wrapper + .createTaskOptions("Decode", 0, 0, + EncoderType.StorageDecryption)); signalSetupFinished(); waitForJobToFinish(job); List outputAssets = wrapper.getJobOutputMediaAssets(job); - validator.validateOutputAssets(outputAssets, getTestAssetFiles().keys()); + validator + .validateOutputAssets(outputAssets, getTestAssetFiles().keys()); // Verify output asset files. assertEquals("output assets count", 1, outputAssets.size()); @@ -166,7 +181,8 @@ public void transformEncryptedAsset() throws Exception { validator.validateAssetFiles(outputAsset, getTestAssetFiles()); // Verify assets were decoded. - Hashtable actualFileStreams = wrapper.downloadFilesFromAsset(outputAsset, 10); + Hashtable actualFileStreams = wrapper + .downloadFilesFromAsset(outputAsset, 10); validator.validateAssetFiles(getTestAssetFiles(), actualFileStreams); } @@ -178,7 +194,8 @@ private byte[] getNewAesKey() { return aesKey; } - private void waitForJobToFinish(JobInfo job) throws InterruptedException, ServiceException { + private void waitForJobToFinish(JobInfo job) throws InterruptedException, + ServiceException { for (int counter = 0; !wrapper.isJobFinished(job); counter++) { if (counter > 30) { fail("Took took long for the job to finish"); @@ -187,17 +204,21 @@ private void waitForJobToFinish(JobInfo job) throws InterruptedException, Servic } } - private List createTasks() throws ServiceException { + private List createTasks() + throws ServiceException { List tasks = new ArrayList(); - tasks.add(wrapper.createTaskOptions("Decryptor", 0, 0, EncoderType.StorageDecryption)); - tasks.add(wrapper.createTaskOptions("Processor", 0, 1, EncoderType.WindowsAzureMediaEncoder)); + tasks.add(wrapper.createTaskOptions("Decryptor", 0, 0, + EncoderType.StorageDecryption)); + tasks.add(wrapper.createTaskOptions("Processor", 0, 1, + EncoderType.WindowsAzureMediaEncoder)); return tasks; } private Hashtable getTestAssetFiles() { Hashtable inputFiles = new Hashtable(); - inputFiles.put("MPEG4-H264.mp4", getClass().getResourceAsStream("/media/MPEG4-H264.mp4")); + inputFiles.put("MPEG4-H264.mp4", + getClass().getResourceAsStream("/media/MPEG4-H264.mp4")); return inputFiles; } diff --git a/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceValidation.java b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceValidation.java new file mode 100644 index 0000000000000..1e25ecacfdecf --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceValidation.java @@ -0,0 +1,298 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.scenarios; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Date; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.List; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.MediaContract; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetFile; +import com.microsoft.windowsazure.services.media.models.AssetFileInfo; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.AssetOption; +import com.microsoft.windowsazure.services.media.models.AssetState; +import com.microsoft.windowsazure.services.media.models.ContentKey; +import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; +import com.microsoft.windowsazure.services.media.models.JobInfo; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.Task; + +class MediaServiceValidation { + private final MediaContract service; + + public MediaServiceValidation(MediaContract service) { + this.service = service; + } + + public void validateAsset(AssetInfo asset, String name, + AssetOption encryption) throws ServiceException { + // Check the asset state. + assertNotNull("asset", asset); + assertNotNull("asset.getId", asset.getId()); + assertFalse("asset.getId != ''", "".equals(asset.getId())); + assertEquals("asset.state", AssetState.Initialized, asset.getState()); + assertEquals("asset.getOptions", encryption, asset.getOptions()); + + // Verify no files by default. + List initialFiles = service.list(AssetFile.list(asset + .getAssetFilesLink())); + assertNotNull("initialFiles", initialFiles); + assertEquals("initialFiles.size", 0, initialFiles.size()); + + // Reload asset from server for ID + AssetInfo reloadedAsset = service.get(Asset.get(asset.getId())); + + // Verify names match + assertNotNull("reloadedAsset", reloadedAsset); + assertNotNull("reloadedAsset.getId", reloadedAsset.getId()); + assertEquals("reloadedAsset.getId, asset.getId", asset.getId(), + reloadedAsset.getId()); + assertEquals("reloadedAsset.state", AssetState.Initialized, + reloadedAsset.getState()); + assertEquals("reloadedAsset.getOptions", encryption, + reloadedAsset.getOptions()); + } + + public void validateAssetSortedPages(List> pages, + List assetNames, int pageSize) { + int sumSizeOfPages = 0; + List actualAssetNames = new ArrayList(); + + for (ListResult page : pages) { + sumSizeOfPages += page.size(); + for (AssetInfo asset : page) { + actualAssetNames.add(asset.getName()); + } + } + + assertEquals("sumSizeOfPages", assetNames.size(), sumSizeOfPages); + assertEquals("size of last page", 0, pages.get(pages.size() - 1).size()); + + // Do not worry about comparing the details of the sorted pages, + // because Media Services splits on the internal order, then sorts + // each page individually. + } + + public void validateAssetFiles(AssetInfo asset, + Hashtable inputFiles) throws ServiceException, + IOException, NoSuchAlgorithmException { + List assetFiles = service.list(AssetFile.list(asset + .getAssetFilesLink())); + + assertNotNull("assetFiles", assetFiles); + assertEquals("assetFiles.size", inputFiles.size(), assetFiles.size()); + + ContentKeyInfo contentKey = null; + if (asset.getOptions() == AssetOption.StorageEncrypted) { + ListResult contentKeys = service.list(ContentKey + .list(asset.getContentKeysLink())); + assertEquals("contentKeys size", 1, contentKeys.size()); + contentKey = contentKeys.get(0); + } + + // Compare encryption info for asset files + for (AssetFileInfo assetFile : assetFiles) { + if (asset.getOptions() == AssetOption.StorageEncrypted) { + assertEquals("assetFile.getIsEncrypted", true, + assetFile.getIsEncrypted()); + assertEquals("assetFile.getEncryptionKeyId", + contentKey.getId(), assetFile.getEncryptionKeyId()); + assertNotNullOrEmpty("assetFile.getEncryptionScheme", + assetFile.getEncryptionScheme()); + assertNotNullOrEmpty("assetFile.getEncryptionVersion", + assetFile.getEncryptionVersion()); + assertNotNullOrEmpty("assetFile.getInitializationVector", + assetFile.getInitializationVector()); + } else { + assertEquals("assetFile.getIsEncrypted", false, + assetFile.getIsEncrypted()); + assertNullOrEmpty("assetFile.getEncryptionKeyId", + assetFile.getEncryptionKeyId()); + assertNullOrEmpty("assetFile.getEncryptionScheme", + assetFile.getEncryptionScheme()); + assertNullOrEmpty("assetFile.getEncryptionVersion", + assetFile.getEncryptionVersion()); + assertNullOrEmpty("assetFile.getInitializationVector", + assetFile.getInitializationVector()); + } + } + + // Compare the asset files with all files + List allFiles = service.list(AssetFile.list()); + for (AssetFileInfo assetFile : assetFiles) { + assertEquals("fi.getParentAssetId", asset.getId(), + assetFile.getParentAssetId()); + AssetFileInfo match = null; + for (AssetFileInfo aFile : allFiles) { + if (aFile.getId().equals(assetFile.getId())) { + match = aFile; + break; + } + } + + assertFileInfosEqual("match from all files", assetFile, match); + } + } + + public void validateAssetFiles(Hashtable inputFiles, + Hashtable actualFileStreams) + throws IOException, InterruptedException { + assertEquals("fileUrls count", inputFiles.size(), + actualFileStreams.size()); + for (String fileName : actualFileStreams.keySet()) { + InputStream expected = inputFiles.get(fileName); + InputStream actual = actualFileStreams.get(fileName); + assertStreamsEqual(expected, actual); + } + } + + public void validateJob(JobInfo job, String name, AssetInfo asset, + List createTasks) + throws ServiceException { + assertDateApproxEquals("getEndTime", new Date(), job.getCreated()); + assertEquals("job.getName", name, job.getName()); + + List inputAssets = service.list(Asset.list(job + .getInputAssetsLink())); + assertNotNull("inputAssets", inputAssets); + assertEquals("inputAssets.size()", 1, inputAssets.size()); + assertEquals("inputAssets.get(0)", asset.getId(), inputAssets.get(0) + .getId()); + + List outputAssets = service.list(Asset.list(job + .getOutputAssetsLink())); + assertNotNull("outputAssets", outputAssets); + assertEquals("outputAssets.size()", createTasks.size(), + outputAssets.size()); + } + + public void validateOutputAssets(List outputAssets, + Enumeration enumeration) { + assertNotNull("outputAssets", outputAssets); + for (AssetInfo asset : outputAssets) { + assertNotNull("asset", asset); + assertNotNull("asset.getId", asset.getId()); + assertFalse("asset.getId != ''", "".equals(asset.getId())); + assertEquals("asset.state", AssetState.Initialized, + asset.getState()); + assertEquals("asset.getOptions", AssetOption.None, + asset.getOptions()); + } + } + + public void assertFileInfosEqual(String message, AssetFileInfo fi, + AssetFileInfo match) { + assertNotNull(message + ":fi", fi); + assertNotNull(message + ":match", match); + assertEquals(message + ":getContentChecksum", fi.getContentChecksum(), + match.getContentChecksum()); + assertEquals(message + ":getContentFileSize", fi.getContentFileSize(), + match.getContentFileSize()); + assertEquals(message + ":getCreated", fi.getCreated(), + match.getCreated()); + assertEquals(message + ":getEncryptionKeyId", fi.getEncryptionKeyId(), + match.getEncryptionKeyId()); + assertEquals(message + ":getEncryptionScheme", + fi.getEncryptionScheme(), match.getEncryptionScheme()); + assertEquals(message + ":getEncryptionVersion", + fi.getEncryptionVersion(), match.getEncryptionVersion()); + assertEquals(message + ":getId", fi.getId(), match.getId()); + assertEquals(message + ":getIsEncrypted", fi.getIsEncrypted(), + match.getIsEncrypted()); + assertEquals(message + ":getIsPrimary", fi.getIsPrimary(), + match.getIsPrimary()); + assertEquals(message + ":getLastModified", fi.getLastModified(), + match.getLastModified()); + assertEquals(message + ":getMimeType", fi.getMimeType(), + match.getMimeType()); + assertEquals(message + ":getName", fi.getName(), match.getName()); + assertEquals(message + ":getParentAssetId", fi.getParentAssetId(), + match.getParentAssetId()); + } + + protected void assertDateApproxEquals(String message, Date expected, + Date actual) { + // Default allows for a 30 seconds difference in dates, for clock skew, + // network delays, etc. + long deltaInMilliseconds = 30000; + + if (expected == null || actual == null) { + assertEquals(message, expected, actual); + } else { + long diffInMilliseconds = Math.abs(expected.getTime() + - actual.getTime()); + + if (diffInMilliseconds > deltaInMilliseconds) { + assertEquals(message, expected, actual); + } + } + } + + private void assertStreamsEqual(InputStream inputStream1, + InputStream inputStream2) throws IOException { + byte[] buffer1 = new byte[1024]; + byte[] buffer2 = new byte[1024]; + try { + while (true) { + int n1 = inputStream1.read(buffer1); + int n2 = inputStream2.read(buffer2); + assertEquals("number of bytes read from streams", n1, n2); + if (n1 == -1) { + break; + } + for (int i = 0; i < n1; i++) { + assertEquals("byte " + i + " read from streams", + buffer1[i], buffer2[i]); + } + } + } finally { + inputStream1.close(); + inputStream2.close(); + } + } + + private void assertNullOrEmpty(String message, String actual) { + if (actual == null) { + assertNull(message, actual); + } else { + assertEquals(message, "", actual); + } + } + + private void assertNotNullOrEmpty(String message, String actual) { + if (actual == null) { + assertNotNull(message, actual); + } else { + assertTrue(message + ": expect " + actual + " to be null or empty", + actual.length() > 0); + } + } + +} diff --git a/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceWrapper.java b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceWrapper.java new file mode 100644 index 0000000000000..c6409e6da6890 --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceWrapper.java @@ -0,0 +1,548 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.scenarios; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.DigestInputStream; +import java.security.Key; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Random; +import java.util.UUID; + +import javax.crypto.Cipher; +import javax.crypto.CipherInputStream; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import junit.framework.Assert; + +import com.microsoft.windowsazure.core.utils.Base64; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.media.MediaContract; +import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; +import com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation; +import com.microsoft.windowsazure.services.media.implementation.content.AssetFileType; +import com.microsoft.windowsazure.services.media.models.AccessPolicy; +import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; +import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; +import com.microsoft.windowsazure.services.media.models.Asset; +import com.microsoft.windowsazure.services.media.models.AssetFile; +import com.microsoft.windowsazure.services.media.models.AssetFile.Updater; +import com.microsoft.windowsazure.services.media.models.AssetFileInfo; +import com.microsoft.windowsazure.services.media.models.AssetInfo; +import com.microsoft.windowsazure.services.media.models.AssetOption; +import com.microsoft.windowsazure.services.media.models.ContentKey; +import com.microsoft.windowsazure.services.media.models.ContentKeyType; +import com.microsoft.windowsazure.services.media.models.Job; +import com.microsoft.windowsazure.services.media.models.Job.Creator; +import com.microsoft.windowsazure.services.media.models.JobInfo; +import com.microsoft.windowsazure.services.media.models.ListResult; +import com.microsoft.windowsazure.services.media.models.Locator; +import com.microsoft.windowsazure.services.media.models.LocatorInfo; +import com.microsoft.windowsazure.services.media.models.LocatorType; +import com.microsoft.windowsazure.services.media.models.MediaProcessor; +import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo; +import com.microsoft.windowsazure.services.media.models.ProtectionKey; +import com.microsoft.windowsazure.services.media.models.Task; + +class MediaServiceWrapper { + private final MediaContract service; + + private static final String accessPolicyPrefix = "scenarioTestPrefix"; + + private final String MEDIA_PROCESSOR_STORAGE_DECRYPTION = "Storage Decryption"; + private final String MEDIA_PROCESSOR_WINDOWS_AZURE_MEDIA_ENCODER = "Windows Azure Media Encoder"; + + public static enum EncoderType { + WindowsAzureMediaEncoder, StorageDecryption + } + + public MediaServiceWrapper(MediaContract service) { + this.service = service; + } + + // Manage + public AssetInfo createAsset(String name, AssetOption encryption) + throws ServiceException { + if (encryption == AssetOption.StorageEncrypted + && !EncryptionHelper.canUseStrongCrypto()) { + Assert.fail("JVM does not support the required encryption"); + } + + // Create asset. The SDK's top-level method is the simplest way to do + // that. + return service.create(Asset.create().setName(name) + .setAlternateId("altId").setOptions(encryption)); + } + + public List> getAssetSortedPagedResults( + String rootName, int pageSize) throws ServiceException { + List> pages = new ArrayList>(); + for (int skip = 0; true; skip += pageSize) { + EntityListOperation listOperation = Asset.list() + .setTop(pageSize).setSkip(skip) + .set("$filter", "startswith(Name,'" + rootName + "')") + .set("$orderby", "Name"); + + ListResult listAssetResult = service.list(listOperation); + pages.add(listAssetResult); + if (listAssetResult.size() == 0) { + break; + } + } + + return pages; + } + + // Ingest + public void uploadFilesToAsset(AssetInfo asset, int uploadWindowInMinutes, + Hashtable inputFiles) throws Exception { + uploadFilesToAsset(asset, uploadWindowInMinutes, inputFiles, null); + } + + public void uploadFilesToAsset(AssetInfo asset, int uploadWindowInMinutes, + Hashtable inputFiles, byte[] aesKey) + throws Exception { + AccessPolicyInfo accessPolicy = service.create(AccessPolicy.create( + accessPolicyPrefix + "tempAccessPolicy", uploadWindowInMinutes, + EnumSet.of(AccessPolicyPermission.WRITE))); + LocatorInfo locator = service.create(Locator.create( + accessPolicy.getId(), asset.getId(), LocatorType.SAS)); + + String contentKeyId = createAssetContentKey(asset, aesKey); + + WritableBlobContainerContract uploader = service + .createBlobWriter(locator); + + Hashtable infoToUpload = new Hashtable(); + + boolean isFirst = true; + for (String fileName : inputFiles.keySet()) { + MessageDigest digest = MessageDigest.getInstance("MD5"); + + InputStream inputStream = inputFiles.get(fileName); + + byte[] iv = null; + if (aesKey != null) { + iv = createIV(); + inputStream = EncryptionHelper.encryptFile(inputStream, aesKey, + iv); + } + + InputStream digestStream = new DigestInputStream(inputStream, + digest); + CountingStream countingStream = new CountingStream(digestStream); + uploader.createBlockBlob(fileName, countingStream); + + inputStream.close(); + byte[] md5hash = digest.digest(); + String md5 = Base64.encode(md5hash); + + AssetFileInfo fi = new AssetFileInfo(null, new AssetFileType() + .setContentChecksum(md5) + .setContentFileSize(countingStream.getCount()) + .setIsPrimary(isFirst).setName(fileName) + .setInitializationVector(getIVString(iv))); + infoToUpload.put(fileName, fi); + + isFirst = false; + } + + service.action(AssetFile.createFileInfos(asset.getId())); + for (AssetFileInfo assetFile : service.list(AssetFile.list(asset + .getAssetFilesLink()))) { + AssetFileInfo fileInfo = infoToUpload.get(assetFile.getName()); + Updater updateOp = AssetFile.update(assetFile.getId()) + .setContentChecksum(fileInfo.getContentChecksum()) + .setContentFileSize(fileInfo.getContentFileSize()) + .setIsPrimary(fileInfo.getIsPrimary()); + + if (aesKey != null) { + updateOp.setIsEncrypted(true) + .setEncryptionKeyId(contentKeyId) + .setEncryptionScheme("StorageEncryption") + .setEncryptionVersion("1.0") + .setInitializationVector( + fileInfo.getInitializationVector()); + } + + service.update(updateOp); + } + + service.list(AssetFile.list(asset.getAssetFilesLink())); + + service.delete(Locator.delete(locator.getId())); + service.delete(AccessPolicy.delete(accessPolicy.getId())); + } + + private String getIVString(byte[] iv) { + if (iv == null) { + return null; + } + + // Offset the bytes to ensure that the sign-bit is not set. + // Media Services expects unsigned Int64 values. + byte[] sub = new byte[9]; + System.arraycopy(iv, 0, sub, 1, 8); + BigInteger longIv = new BigInteger(sub); + return longIv.toString(); + } + + private byte[] createIV() { + // Media Services requires 128-bit (16-byte) initialization vectors (IV) + // for AES encryption, but also that only the first 8 bytes are filled. + Random random = new Random(); + byte[] effectiveIv = new byte[8]; + random.nextBytes(effectiveIv); + byte[] iv = new byte[16]; + System.arraycopy(effectiveIv, 0, iv, 0, effectiveIv.length); + return iv; + } + + private String createAssetContentKey(AssetInfo asset, byte[] aesKey) + throws Exception { + if (aesKey == null) { + return null; + } + + String protectionKeyId = service.action(ProtectionKey + .getProtectionKeyId(ContentKeyType.StorageEncryption)); + String protectionKey = service.action(ProtectionKey + .getProtectionKey(protectionKeyId)); + + String contentKeyIdUuid = UUID.randomUUID().toString(); + String contentKeyId = "nb:kid:UUID:" + contentKeyIdUuid; + + byte[] encryptedContentKey = EncryptionHelper.encryptSymmetricKey( + protectionKey, aesKey); + String encryptedContentKeyString = Base64.encode(encryptedContentKey); + String checksum = EncryptionHelper.calculateContentKeyChecksum( + contentKeyIdUuid, aesKey); + + service.create(ContentKey + .create(contentKeyId, ContentKeyType.StorageEncryption, + encryptedContentKeyString).setChecksum(checksum) + .setProtectionKeyId(protectionKeyId)); + service.action(Asset.linkContentKey(asset.getId(), contentKeyId)); + return contentKeyId; + } + + private static class CountingStream extends InputStream { + private final InputStream wrappedStream; + private long count; + + public CountingStream(InputStream wrapped) { + wrappedStream = wrapped; + count = 0; + } + + @Override + public int read() throws IOException { + count++; + return wrappedStream.read(); + } + + public long getCount() { + return count; + } + } + + // Process + public JobInfo createJob(String jobName, AssetInfo inputAsset, + Task.CreateBatchOperation task) throws ServiceException { + List tasks = new ArrayList(); + tasks.add(task); + return createJob(jobName, inputAsset, tasks); + } + + public JobInfo createJob(String jobName, AssetInfo inputAsset, + List tasks) throws ServiceException { + Creator jobCreator = Job.create().setName(jobName) + .addInputMediaAsset(inputAsset.getId()).setPriority(2); + + for (Task.CreateBatchOperation task : tasks) { + jobCreator.addTaskCreator(task); + } + + return service.create(jobCreator); + } + + // Process + public Task.CreateBatchOperation createTaskOptions(String taskName, + int inputAssetId, int outputAssetId, EncoderType encoderType) + throws ServiceException { + String taskBody = getTaskBody(inputAssetId, outputAssetId); + + String processor = null; + String configuration = null; + switch (encoderType) { + case WindowsAzureMediaEncoder: + processor = getMediaProcessorIdByName(MEDIA_PROCESSOR_WINDOWS_AZURE_MEDIA_ENCODER); + // Full list of configurations strings for version 2.1 is at: + // http://msdn.microsoft.com/en-us/library/jj129582.aspx + configuration = "VC1 Broadband SD 4x3"; + break; + case StorageDecryption: + processor = getMediaProcessorIdByName(MEDIA_PROCESSOR_STORAGE_DECRYPTION); + configuration = null; + break; + default: + break; + } + + Task.CreateBatchOperation taskCreate = Task.create(processor, taskBody) + .setName(taskName).setConfiguration(configuration); + + return taskCreate; + } + + private String getTaskBody(int inputAssetId, int outputAssetId) { + return "JobInputAsset(" + inputAssetId + + ")" + "JobOutputAsset(" + + outputAssetId + ")"; + } + + private String getMediaProcessorIdByName(String processorName) + throws ServiceException { + EntityListOperation operation = MediaProcessor + .list(); + operation.getQueryParameters().putSingle("$filter", + "(Name eq '" + processorName + "')"); + MediaProcessorInfo processor = service.list(operation).get(0); + return processor.getId(); + } + + // Process + public boolean isJobFinished(JobInfo initialJobInfo) + throws ServiceException { + JobInfo currentJob = service.get(Job.get(initialJobInfo.getId())); + System.out.println(currentJob.getState()); + switch (currentJob.getState()) { + case Finished: + case Canceled: + case Error: + return true; + default: + return false; + } + } + + public List getJobOutputMediaAssets(JobInfo job) + throws ServiceException { + return service.list(Asset.list(job.getOutputAssetsLink())); + } + + // Process + public void cancelJob(JobInfo job) throws ServiceException { + // Use the service function + service.action(Job.cancel(job.getId())); + } + + // Deliver + private Hashtable createFileURLsFromAsset(AssetInfo asset, + int availabilityWindowInMinutes) throws ServiceException, + MalformedURLException { + Hashtable ret = new Hashtable(); + + AccessPolicyInfo readAP = service.create(AccessPolicy.create( + accessPolicyPrefix + "tempAccessPolicy", + availabilityWindowInMinutes, + EnumSet.of(AccessPolicyPermission.READ))); + LocatorInfo readLocator = service.create(Locator.create(readAP.getId(), + asset.getId(), LocatorType.SAS)); + + List publishedFiles = service.list(AssetFile.list(asset + .getAssetFilesLink())); + for (AssetFileInfo fi : publishedFiles) { + ret.put(fi.getName(), + new URL(readLocator.getBaseUri() + "/" + fi.getName() + + readLocator.getContentAccessToken())); + } + + return ret; + } + + // Deliver + public Hashtable downloadFilesFromAsset( + AssetInfo asset, int downloadWindowInMinutes) throws Exception { + Hashtable urls = createFileURLsFromAsset(asset, + downloadWindowInMinutes); + Hashtable ret = new Hashtable(); + + for (String fileName : urls.keySet()) { + URL url = urls.get(fileName); + InputStream stream = getInputStreamWithRetry(url); + ret.put(fileName, stream); + } + + return ret; + } + + // This method is needed because there can be a delay before a new read + // locator + // is applied for the asset files. + private InputStream getInputStreamWithRetry(URL file) throws IOException, + InterruptedException { + InputStream reader = null; + for (int counter = 0; true; counter++) { + try { + reader = file.openConnection().getInputStream(); + break; + } catch (IOException e) { + System.out.println("Got error, wait a bit and try again"); + if (counter < 6) { + Thread.sleep(10000); + } else { + // No more retries. + throw e; + } + } + } + + return reader; + } + + public void removeAllAssetsWithPrefix(String assetPrefix) + throws ServiceException { + ListResult locators = service.list(Locator.list()); + EntityListOperation operation = Asset.list(); + operation.getQueryParameters().add("$filter", + "startswith(Name,'" + assetPrefix + "')"); + List assets = service.list(operation); + for (AssetInfo asset : assets) { + if (asset.getName().length() > assetPrefix.length() + && asset.getName().substring(0, assetPrefix.length()) + .equals(assetPrefix)) { + for (LocatorInfo locator : locators) { + if (locator.getAssetId().equals(asset.getId())) { + try { + service.delete(Locator.delete(locator.getId())); + } catch (ServiceException e) { + // Don't worry if cannot delete now. + // Might be held on to by a running job + } + } + } + + try { + service.delete(Asset.delete(asset.getId())); + } catch (ServiceException e) { + // Don't worry if cannot delete now. + // Might be held on to by a running job + } + } + } + } + + public void removeAllAccessPoliciesWithPrefix() throws ServiceException { + List accessPolicies = service.list(AccessPolicy + .list()); + for (AccessPolicyInfo accessPolicy : accessPolicies) { + if (accessPolicy.getName().length() > accessPolicyPrefix.length() + && accessPolicy.getName() + .substring(0, accessPolicyPrefix.length()) + .equals(accessPolicyPrefix)) { + try { + service.delete(AccessPolicy.delete(accessPolicy.getId())); + } catch (ServiceException e) { + // Don't worry if cannot delete now. + // Might be held on to by a running job + } + } + } + } + + public void removeAllJobWithPrefix(String testJobPrefix) + throws ServiceException { + List jobInfos = service.list(Job.list()); + for (JobInfo jobInfo : jobInfos) { + if (jobInfo.getName().startsWith(testJobPrefix)) { + try { + service.delete(Job.delete(jobInfo.getId())); + } catch (ServiceException e) { + } + } + } + } + + private static class EncryptionHelper { + public static boolean canUseStrongCrypto() { + try { + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + SecretKeySpec secretKeySpec = new SecretKeySpec(new byte[32], + "AES"); + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); + } catch (Exception e) { + return false; + } + return true; + } + + public static byte[] encryptSymmetricKey(String protectionKey, + byte[] inputData) throws Exception { + Cipher cipher = Cipher + .getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"); + CertificateFactory certificateFactory = CertificateFactory + .getInstance("X.509"); + byte[] protectionKeyBytes = Base64.decode(protectionKey); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( + protectionKeyBytes); + Certificate certificate = certificateFactory + .generateCertificate(byteArrayInputStream); + Key publicKey = certificate.getPublicKey(); + SecureRandom secureRandom = new SecureRandom(); + cipher.init(Cipher.ENCRYPT_MODE, publicKey, secureRandom); + byte[] cipherText = cipher.doFinal(inputData); + return cipherText; + } + + public static String calculateContentKeyChecksum(String uuid, + byte[] aesKey) throws Exception { + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); + SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, "AES"); + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); + byte[] encryptionResult = cipher.doFinal(uuid.getBytes("UTF8")); + byte[] checksumByteArray = new byte[8]; + System.arraycopy(encryptionResult, 0, checksumByteArray, 0, 8); + String checksum = Base64.encode(checksumByteArray); + return checksum; + } + + public static InputStream encryptFile(InputStream inputStream, + byte[] key, byte[] iv) throws Exception { + Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); + SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); + IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); + cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec); + CipherInputStream cipherInputStream = new CipherInputStream( + inputStream, cipher); + return cipherInputStream; + } + } + +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/ScenarioTestBase.java b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/ScenarioTestBase.java similarity index 78% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/ScenarioTestBase.java rename to media/src/test/java/com/microsoft/windowsazure/services/scenarios/ScenarioTestBase.java index ee4c89e662704..18e42893d7ed5 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/ScenarioTestBase.java +++ b/media/src/test/java/com/microsoft/windowsazure/services/scenarios/ScenarioTestBase.java @@ -15,21 +15,18 @@ package com.microsoft.windowsazure.services.scenarios; -import static org.junit.Assert.*; +import static org.junit.Assert.fail; import org.junit.Rule; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; +import com.microsoft.windowsazure.Configuration; import com.microsoft.windowsazure.services.blob.BlobConfiguration; -import com.microsoft.windowsazure.services.core.Configuration; import com.microsoft.windowsazure.services.media.MediaConfiguration; import com.microsoft.windowsazure.services.queue.QueueConfiguration; -import com.microsoft.windowsazure.services.serviceBus.ServiceBusConfiguration; -import com.microsoft.windowsazure.services.table.TableConfiguration; -@SuppressWarnings("deprecation") public abstract class ScenarioTestBase { protected static Configuration config; @@ -47,15 +44,6 @@ protected static void initializeConfig() { overrideWithEnv(config, QueueConfiguration.ACCOUNT_KEY); overrideWithEnv(config, QueueConfiguration.URI); - overrideWithEnv(config, TableConfiguration.ACCOUNT_NAME); - overrideWithEnv(config, TableConfiguration.ACCOUNT_KEY); - overrideWithEnv(config, TableConfiguration.URI); - - overrideWithEnv(config, ServiceBusConfiguration.URI); - overrideWithEnv(config, ServiceBusConfiguration.WRAP_URI); - overrideWithEnv(config, ServiceBusConfiguration.WRAP_NAME); - overrideWithEnv(config, ServiceBusConfiguration.WRAP_PASSWORD); - overrideWithEnv(config, MediaConfiguration.URI); overrideWithEnv(config, MediaConfiguration.OAUTH_URI); overrideWithEnv(config, MediaConfiguration.OAUTH_CLIENT_ID); @@ -83,7 +71,8 @@ protected class SetupManager implements MethodRule { private boolean shouldCapture; @Override - public Statement apply(Statement base, FrameworkMethod method, Object target) { + public Statement apply(Statement base, FrameworkMethod method, + Object target) { return new SetupManagerStatement(base); } @@ -106,13 +95,11 @@ public SetupManagerStatement(Statement base) { public void evaluate() throws Throwable { try { next.evaluate(); - } - catch (Throwable e) { + } catch (Throwable e) { if (shouldCapture) { - e.printStackTrace(); + // e.printStackTrace(); fail("Error occured during setup: " + e.getMessage()); - } - else { + } else { throw e; } } diff --git a/media/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java b/media/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java new file mode 100644 index 0000000000000..d07fcb8c8c30b --- /dev/null +++ b/media/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java @@ -0,0 +1,107 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; + +import java.io.ByteArrayInputStream; +import java.net.SocketTimeoutException; + +import org.junit.Test; + +import com.microsoft.windowsazure.core.ServiceTimeoutException; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class ServiceExceptionFactoryTest { + @Test + public void serviceNameAndMessageAndCauseAppearInException() { + // Arrange + ClientResponse response = new ClientResponse(404, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException cause = new UniformInterfaceException( + response); + + // Act + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException("this is a test", cause)); + + // Assert + assertNotNull(exception); + assertEquals("testing", exception.getServiceName()); + assertEquals("this is a test", exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void httpStatusCodeAndReasonPhraseAppearInException() { + // Arrange + ClientResponse response = new ClientResponse(404, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException cause = new UniformInterfaceException( + response); + + // Act + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException("this is a test", cause)); + + // Assert + assertNotNull(exception); + assertEquals(404, exception.getHttpStatusCode()); + assertEquals("Not Found", exception.getHttpReasonPhrase()); + } + + @Test + public void informationWillPassUpIfServiceExceptionIsRootCauseOfClientHandlerExceptions() { + // Arrange + ClientResponse response = new ClientResponse(503, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException rootCause = new UniformInterfaceException( + response); + ServiceException originalDescription = ServiceExceptionFactory.process( + "underlying", new ServiceException(rootCause)); + ClientHandlerException wrappingException = new ClientHandlerException( + originalDescription); + + // Act + ServiceException exception = ServiceExceptionFactory.process("actual", + new ServiceException(wrappingException)); + + // Assert + assertEquals(503, exception.getHttpStatusCode()); + assertEquals("underlying", exception.getServiceName()); + } + + @Test + public void socketTimeoutWillPassUpIfInsideClientHandlerException() { + String expectedMessage = "connect timeout"; + SocketTimeoutException rootCause = new SocketTimeoutException( + expectedMessage); + ClientHandlerException wrappingException = new ClientHandlerException( + rootCause); + + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException(wrappingException)); + + assertSame(ServiceTimeoutException.class, exception.getClass()); + assertEquals(expectedMessage, exception.getMessage()); + assertEquals("testing", exception.getServiceName()); + } +} diff --git a/media/src/test/resources/META-INF/com.microsoft.windowsazure.properties b/media/src/test/resources/META-INF/com.microsoft.windowsazure.properties new file mode 100644 index 0000000000000..eb2c358c922c9 --- /dev/null +++ b/media/src/test/resources/META-INF/com.microsoft.windowsazure.properties @@ -0,0 +1,27 @@ +serviceBus.uri=https://%SERVICEBUS_NAMESPACE%.servicebus.windows.net/ +serviceBus.wrap.uri=https://%SERVICEBUS_NAMESPACE%-sb.accesscontrol.windows.net/WRAPv0.9 +serviceBus.wrap.name=%SERVICEBUS_SERVICEIDENTITY% +serviceBus.wrap.password=%SERVICEBUS_SHAREDSECRET% +serviceBus.connection.string=EndPoint=sb://%SERVICEBUS_NAMESPACE%.servicebus.windows.net/;SharedSecretIssuer=%SERVICEBUS_SERVICEIDENTITY%;SharedSecretValue=%SERVICEBUS_SHAREDSECRET% +blob.accountName=%BLOB_ACCOUNTNAME% +blob.accountKey=%BLOB_ACCOUNTKEY% +blob.uri=http://%BLOB_ACCOUNTNAME%.blob.core.windows.net +queue.accountName=%QUEUE_ACCOUNTNAME% +queue.accountKey=%QUEUE_ACCOUNTKEY% +queue.uri=http://%QUEUE_ACCOUNTNAME%.queue.core.windows.net +table.accountName=%TABLE_ACCOUNTNAME% +table.accountKey=%TABLE_ACCOUNTKEY% +table.uri=http://%TABLE_ACCOUNTNAME%.table.core.windows.net +media.uri=%MEDIA.URI% +media.oauth.uri=%MEDIA.OAUTH.URI% +media.oauth.client.id=%OMEDIA.AUTH.CLIENT.ID% +media.oauth.client.secret=%MEDIA.OAUTH.CLIENT.SECRET% +media.oauth.scope=urn:WindowsAzureMediaServices +management.keystore.path=%MANAGEMENT.KEYSTORE.PATH% +management.keystore.password=%MANAGEMENT.KEYSTORE.PASSWORD% +management.keystore.type=%MANAGEMENT.KEYSTORE.TYPE% +management.subscription.id=%MANAGEMENT.SUBSCRIPTION.ID% +management.uri=%MANAGEMENT.URI% +testprefix.com.microsoft.windowsazure.services.core.Configuration.connectTimeout=3 +testprefix.com.microsoft.windowsazure.services.core.Configuration.readTimeout=7 + diff --git a/media/src/test/resources/NewFile.xml b/media/src/test/resources/NewFile.xml new file mode 100644 index 0000000000000..5ebbe31bdafda --- /dev/null +++ b/media/src/test/resources/NewFile.xml @@ -0,0 +1,4 @@ + + + + diff --git a/microsoft-azure-api/src/test/resources/certificate/server.crt b/media/src/test/resources/certificate/server.crt similarity index 100% rename from microsoft-azure-api/src/test/resources/certificate/server.crt rename to media/src/test/resources/certificate/server.crt diff --git a/microsoft-azure-api/src/test/resources/certificate/server.der b/media/src/test/resources/certificate/server.der similarity index 100% rename from microsoft-azure-api/src/test/resources/certificate/server.der rename to media/src/test/resources/certificate/server.der diff --git a/microsoft-azure-api/src/test/resources/media/MPEG4-H264.mp4 b/media/src/test/resources/media/MPEG4-H264.mp4 similarity index 100% rename from microsoft-azure-api/src/test/resources/media/MPEG4-H264.mp4 rename to media/src/test/resources/media/MPEG4-H264.mp4 diff --git a/microsoft-azure-api/.settings/org.eclipse.core.resources.prefs b/microsoft-azure-api/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 29abf99956411..0000000000000 --- a/microsoft-azure-api/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,6 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/main/resources=UTF-8 -encoding//src/test/java=UTF-8 -encoding//src/test/resources=UTF-8 -encoding/=UTF-8 diff --git a/microsoft-azure-api/.settings/org.eclipse.jdt.core.prefs b/microsoft-azure-api/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 3f7604ef3b690..0000000000000 --- a/microsoft-azure-api/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,289 +0,0 @@ -#Wed Nov 16 15:46:43 PST 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.6 -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 -org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_after_package=1 -org.eclipse.jdt.core.formatter.blank_lines_before_field=0 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -org.eclipse.jdt.core.formatter.blank_lines_before_package=0 -org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 -org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 -org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false -org.eclipse.jdt.core.formatter.comment.format_block_comments=false -org.eclipse.jdt.core.formatter.comment.format_header=true -org.eclipse.jdt.core.formatter.comment.format_html=true -org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true -org.eclipse.jdt.core.formatter.comment.format_line_comments=false -org.eclipse.jdt.core.formatter.comment.format_source_code=true -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=true -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert -org.eclipse.jdt.core.formatter.comment.line_length=120 -org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true -org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true -org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false -org.eclipse.jdt.core.formatter.compact_else_if=true -org.eclipse.jdt.core.formatter.continuation_indentation=2 -org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 -org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off -org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on -org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false -org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true -org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true -org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_empty_lines=false -org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true -org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true -org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert -org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert -org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert -org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert -org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert -org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert -org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert -org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert -org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.join_lines_in_comments=false -org.eclipse.jdt.core.formatter.join_wrapped_lines=true -org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false -org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false -org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false -org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false -org.eclipse.jdt.core.formatter.lineSplit=120 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false -org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 -org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false -org.eclipse.jdt.core.formatter.tabulation.char=space -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=true -org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false -org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true -org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/microsoft-azure-api/.settings/org.eclipse.jdt.ui.prefs b/microsoft-azure-api/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 1192a0c8bae03..0000000000000 --- a/microsoft-azure-api/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,118 +0,0 @@ -#Sat Nov 12 18:37:54 PST 2011 -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=true -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_methods=false -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_missing_override_annotations_interface_methods=true -cleanup.add_serial_version_id=false -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=false -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.correct_indentation=false -cleanup.format_source_code=false -cleanup.format_source_code_changes_only=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=true -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=false -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=true -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_trailing_whitespaces=true -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=false -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.sort_members=false -cleanup.sort_members_all=false -cleanup.use_blocks=false -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_parentheses_in_expressions=false -cleanup.use_this_for_non_static_field_access=false -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=false -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup_profile=org.eclipse.jdt.ui.default.eclipse_clean_up_profile -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_OneSDK profile -formatter_settings_version=12 -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.ignorelowercasenames=true -org.eclipse.jdt.ui.importorder=java;javax;org;com; -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.ondemandthreshold=99 -org.eclipse.jdt.ui.overrideannotation=true -org.eclipse.jdt.ui.staticondemandthreshold=1 -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=false -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=false -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=false -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=true -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=true -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=false -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=false -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=false -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/microsoft-azure-api/.settings/org.eclipse.m2e.core.prefs b/microsoft-azure-api/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index 55679f3b05ac3..0000000000000 --- a/microsoft-azure-api/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -#Tue Oct 18 09:29:27 PDT 2011 -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/microsoft-azure-api/pom.xml b/microsoft-azure-api/pom.xml deleted file mode 100644 index 6b2b5eedd96e1..0000000000000 --- a/microsoft-azure-api/pom.xml +++ /dev/null @@ -1,311 +0,0 @@ - - - 4.0.0 - com.microsoft.windowsazure - microsoft-windowsazure-api - 0.4.6 - jar - - Microsoft Windows Azure Client API - API for Microsoft Windows Azure Clients - https://github.com/WindowsAzure/azure-sdk-for-java - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - scm:git:https://github.com/WindowsAzure/azure-sdk-for-java - scm:git:git://github.com/WindowsAzure/azure-sdk-for-java.git - - - - UTF-8 - - - - - - microsoft - Microsoft - - - - - - com.sun.jersey - jersey-client - 1.13 - - - javax.xml.bind - jaxb-api - 2.2.7 - provided - - - junit - junit - 4.10 - test - - - org.hamcrest - hamcrest-all - 1.3 - test - - - org.mockito - mockito-all - 1.9.0 - test - - - javax.inject - javax.inject - 1 - - - com.sun.jersey - jersey-json - 1.13 - - - commons-logging - commons-logging - 1.1.1 - - - javax.mail - mail - 1.4.5 - - - org.apache.commons - commons-lang3 - 3.1 - - - org.bouncycastle - bcprov-jdk16 - 1.46 - test - - - - - - - org.apache.maven.plugins - maven-help-plugin - 2.1.1 - - - validate - - evaluate - - - legal - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.6 - 1.6 - - - - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - 0.8.3 - - - serviceBus - generate-sources - - generate - - - target/generated-sources/xjc - src/main/resources/serviceBus - - servicebus-atom.xsd - - com.microsoft.windowsazure.services.serviceBus.implementation - false - true - - - - management - generate-sources - - generate - - - target/generated-sources/xjc - src/main/resources/management/ - - schemas.microsoft.com.windowsazure.xsd - - com.microsoft.windowsazure.services.management.implementation - false - true - - - - - true - true - true - - - org.jvnet.jaxb2_commons - jaxb2-basics - 0.6.4 - - - org.jvnet.jaxb2_commons - jaxb2-basics-annotate - 0.6.4 - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage - /** -
* Copyright Microsoft Corporation -
* -
* Licensed under the Apache License, Version 2.0 (the "License"); -
* you may not use this file except in compliance with the License. -
* You may obtain a copy of the License at -
* http://www.apache.org/licenses/LICENSE-2.0 -
* -
* Unless required by applicable law or agreed to in writing, software -
* distributed under the License is distributed on an "AS IS" BASIS, -
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -
* See the License for the specific language governing permissions and -
* limitations under the License. -
*/]]>
-
-
- - - org.codehaus.mojo - findbugs-maven-plugin - 2.3.2 - - true - true - true - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.8 - - src/config/checkstyle.xml - - - -
- - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.maven.plugins - maven-help-plugin - [2.1.1,) - - evaluate - - - - - - - - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.4.3 - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - **/Test*.java - **/*Test.java - **/*Tests.java - **/*TestCase.java - - - - - -
- - - - org.codehaus.mojo - emma-maven-plugin - 1.0-alpha-3 - true - - - org.codehaus.mojo - surefire-report-maven-plugin - 2.0-beta-1 - true - - - -
diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ObjectFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ObjectFactory.java deleted file mode 100644 index 9f1fdc395fba0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ObjectFactory.java +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2011.11.14 at 04:34:45 PM PST -// - - -package com.microsoft.windowsazure.serviceruntime; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlElementDecl; -import javax.xml.bind.annotation.XmlRegistry; -import javax.xml.namespace.QName; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.microsoft.windowsazure.serviceruntime package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -class ObjectFactory { - - private final static QName _GoalState_QNAME = new QName("", "GoalState"); - private final static QName _RoleEnvironment_QNAME = new QName("", "RoleEnvironment"); - private final static QName _CurrentState_QNAME = new QName("", "CurrentState"); - private final static QName _RuntimeServerDiscovery_QNAME = new QName("", "RuntimeServerDiscovery"); - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.microsoft.windowsazure.serviceruntime - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link StatusLeaseInfo.Release } - * - */ - public StatusLeaseInfo.Release createStatusLeaseInfoRelease() { - return new StatusLeaseInfo.Release(); - } - - /** - * Create an instance of {@link RuntimeServerEndpointsInfo } - * - */ - public RuntimeServerEndpointsInfo createRuntimeServerEndpointsInfo() { - return new RuntimeServerEndpointsInfo(); - } - - /** - * Create an instance of {@link RuntimeServerEndpointInfo } - * - */ - public RuntimeServerEndpointInfo createRuntimeServerEndpointInfo() { - return new RuntimeServerEndpointInfo(); - } - - /** - * Create an instance of {@link RuntimeServerDiscoveryInfo } - * - */ - public RuntimeServerDiscoveryInfo createRuntimeServerDiscoveryInfo() { - return new RuntimeServerDiscoveryInfo(); - } - - /** - * Create an instance of {@link GoalStateInfo } - * - */ - public GoalStateInfo createGoalStateInfo() { - return new GoalStateInfo(); - } - - /** - * Create an instance of {@link LocalResourcesInfo } - * - */ - public LocalResourcesInfo createLocalResourcesInfo() { - return new LocalResourcesInfo(); - } - - /** - * Create an instance of {@link ConfigurationSettingInfo } - * - */ - public ConfigurationSettingInfo createConfigurationSettingInfo() { - return new ConfigurationSettingInfo(); - } - - /** - * Create an instance of {@link CurrentStateInfo } - * - */ - public CurrentStateInfo createCurrentStateInfo() { - return new CurrentStateInfo(); - } - - /** - * Create an instance of {@link CurrentRoleInstanceInfo } - * - */ - public CurrentRoleInstanceInfo createCurrentRoleInstanceInfo() { - return new CurrentRoleInstanceInfo(); - } - - /** - * Create an instance of {@link LocalResourceInfo } - * - */ - public LocalResourceInfo createLocalResourceInfo() { - return new LocalResourceInfo(); - } - - /** - * Create an instance of {@link RolesInfo } - * - */ - public RolesInfo createRolesInfo() { - return new RolesInfo(); - } - - /** - * Create an instance of {@link StatusLeaseInfo } - * - */ - public StatusLeaseInfo createStatusLeaseInfo() { - return new StatusLeaseInfo(); - } - - /** - * Create an instance of {@link DeploymentInfo } - * - */ - public DeploymentInfo createDeploymentInfo() { - return new DeploymentInfo(); - } - - /** - * Create an instance of {@link RoleInstancesInfo } - * - */ - public RoleInstancesInfo createRoleInstancesInfo() { - return new RoleInstancesInfo(); - } - - /** - * Create an instance of {@link RoleInfo } - * - */ - public RoleInfo createRoleInfo() { - return new RoleInfo(); - } - - /** - * Create an instance of {@link ConfigurationSettingsInfo } - * - */ - public ConfigurationSettingsInfo createConfigurationSettingsInfo() { - return new ConfigurationSettingsInfo(); - } - - /** - * Create an instance of {@link EndpointsInfo } - * - */ - public EndpointsInfo createEndpointsInfo() { - return new EndpointsInfo(); - } - - /** - * Create an instance of {@link AcquireLeaseInfo } - * - */ - public AcquireLeaseInfo createAcquireLeaseInfo() { - return new AcquireLeaseInfo(); - } - - /** - * Create an instance of {@link EndpointInfo } - * - */ - public EndpointInfo createEndpointInfo() { - return new EndpointInfo(); - } - - /** - * Create an instance of {@link RoleEnvironmentInfo } - * - */ - public RoleEnvironmentInfo createRoleEnvironmentInfo() { - return new RoleEnvironmentInfo(); - } - - /** - * Create an instance of {@link RoleInstanceInfo } - * - */ - public RoleInstanceInfo createRoleInstanceInfo() { - return new RoleInstanceInfo(); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link GoalStateInfo }{@code >}} - * - */ - @XmlElementDecl(namespace = "", name = "GoalState") - public JAXBElement createGoalState(GoalStateInfo value) { - return new JAXBElement(_GoalState_QNAME, GoalStateInfo.class, null, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link RoleEnvironmentInfo }{@code >}} - * - */ - @XmlElementDecl(namespace = "", name = "RoleEnvironment") - public JAXBElement createRoleEnvironment(RoleEnvironmentInfo value) { - return new JAXBElement(_RoleEnvironment_QNAME, RoleEnvironmentInfo.class, null, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CurrentStateInfo }{@code >}} - * - */ - @XmlElementDecl(namespace = "", name = "CurrentState") - public JAXBElement createCurrentState(CurrentStateInfo value) { - return new JAXBElement(_CurrentState_QNAME, CurrentStateInfo.class, null, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link RuntimeServerDiscoveryInfo }{@code >}} - * - */ - @XmlElementDecl(namespace = "", name = "RuntimeServerDiscovery") - public JAXBElement createRuntimeServerDiscovery(RuntimeServerDiscoveryInfo value) { - return new JAXBElement(_RuntimeServerDiscovery_QNAME, RuntimeServerDiscoveryInfo.class, null, value); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ProtocolEnum.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ProtocolEnum.java deleted file mode 100644 index c48227e85de77..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ProtocolEnum.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2011.11.14 at 04:34:45 PM PST -// - - -package com.microsoft.windowsazure.serviceruntime; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for ProtocolEnum. - * - *

The following schema fragment specifies the expected content contained within this class. - *

- *

- * <simpleType name="ProtocolEnum">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="ip"/>
- *     <enumeration value="tcp"/>
- *     <enumeration value="tls"/>
- *     <enumeration value="http"/>
- *     <enumeration value="https"/>
- *     <enumeration value="wcf:tcp"/>
- *     <enumeration value="wcf:tls"/>
- *     <enumeration value="wcf:http"/>
- *     <enumeration value="wcf:https"/>
- *     <enumeration value="wcf:https:certificate"/>
- *     <enumeration value="udp"/>
- *     <enumeration value="raw"/>
- *   </restriction>
- * </simpleType>
- * 
- * - */ -@XmlType(name = "ProtocolEnum") -@XmlEnum -enum ProtocolEnum { - - @XmlEnumValue("ip") - IP("ip"), - @XmlEnumValue("tcp") - TCP("tcp"), - @XmlEnumValue("tls") - TLS("tls"), - @XmlEnumValue("http") - HTTP("http"), - @XmlEnumValue("https") - HTTPS("https"), - @XmlEnumValue("wcf:tcp") - WCF_TCP("wcf:tcp"), - @XmlEnumValue("wcf:tls") - WCF_TLS("wcf:tls"), - @XmlEnumValue("wcf:http") - WCF_HTTP("wcf:http"), - @XmlEnumValue("wcf:https") - WCF_HTTPS("wcf:https"), - @XmlEnumValue("wcf:https:certificate") - WCF_HTTPS_CERTIFICATE("wcf:https:certificate"), - @XmlEnumValue("udp") - UDP("udp"), - @XmlEnumValue("raw") - RAW("raw"); - private final String value; - - ProtocolEnum(String v) { - value = v; - } - - public String value() { - return value; - } - - public static ProtocolEnum fromValue(String v) { - for (ProtocolEnum c: ProtocolEnum.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Role.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Role.java deleted file mode 100644 index 32674087109be..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Role.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import java.util.Map; - -/** - * Represents a role that is defined as part of a hosted service. - */ -public final class Role { - private final String name; - private final Map instances; - - /** - * Constructor - * - * @param name - * @param instances - */ - Role(String name, Map instances) { - this.name = name; - this.instances = instances; - } - - /** - * Returns the collection of instances for the role. - *

- * The number of instances of a role to be deployed to Windows Azure is specified in the service's configuration - * file. - *

- * A role must define at least one internal endpoint in order for its set of instances to be known at runtime. - * - * @return A read-only java.util.Map object that contains the - * instances for the role, or null if the instances - * could not be retrieved. - */ - public Map getInstances() { - return instances; - } - - /** - * Returns the name of the role as it is declared in the service definition - * file. - * - * @return A String object that represents the name of the role - * as it is declared in the service definition file. - */ - public String getName() { - return name; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironment.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironment.java deleted file mode 100644 index e5e3e865f67c2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironment.java +++ /dev/null @@ -1,603 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; - -/** - * Represents the Windows Azure environment in which an instance of a role is - * running. - */ -public final class RoleEnvironment { - private static final String VersionEndpointEnvironmentName = "WaRuntimeEndpoint"; - private static final String VersionEndpointFixedPath = "\\\\.\\pipe\\WindowsAzureRuntime"; - private static final String clientId; - - private static RuntimeClient runtimeClient; - private static AtomicReference currentGoalState; - private static AtomicReference currentEnvironmentData; - private static List changingListeners; - private static List changedListeners; - private static List stoppingListeners; - private static AtomicReference lastState; - private static final Calendar maxDateTime; - - static { - try { - JAXBContext.newInstance(RoleEnvironment.class.getPackage().getName()); - } - catch (JAXBException e) { - e.printStackTrace(); - } - clientId = UUID.randomUUID().toString(); - maxDateTime = javax.xml.bind.DatatypeConverter.parseDateTime("9999-12-31T23:59:59.9999999"); - } - - private RoleEnvironment() { - }; - - private static synchronized void initialize() { - if (runtimeClient == null) { - String endpoint = System.getenv(VersionEndpointEnvironmentName); - - if (endpoint == null) { - endpoint = VersionEndpointFixedPath; - } - - RuntimeKernel kernel = RuntimeKernel.getKernel(); - - try { - runtimeClient = kernel.getRuntimeVersionManager().getRuntimeClient(endpoint); - } - catch (Throwable t) { - throw new RoleEnvironmentNotAvailableException(t); - } - - changingListeners = new LinkedList(); - changedListeners = new LinkedList(); - stoppingListeners = new LinkedList(); - - try { - currentGoalState = new AtomicReference(runtimeClient.getCurrentGoalState()); - currentEnvironmentData = new AtomicReference( - runtimeClient.getRoleEnvironmentData()); - } - catch (InterruptedException e) { - throw new RoleEnvironmentNotAvailableException(e); - } - - lastState = new AtomicReference(); - - runtimeClient.addGoalStateChangedListener(new GoalStateChangedListener() { - @Override - public void goalStateChanged(GoalState newGoalState) { - switch (newGoalState.getExpectedState()) { - case STARTED: - if (newGoalState.getIncarnation().compareTo(currentGoalState.get().getIncarnation()) > 0) { - processGoalStateChange(newGoalState); - } - break; - case STOPPED: - raiseStoppingEvent(); - - CurrentState stoppedState = new AcquireCurrentState(clientId, - newGoalState.getIncarnation(), CurrentStatus.STOPPED, maxDateTime); - - runtimeClient.setCurrentState(stoppedState); - break; - } - } - }); - } - else { - try { - currentGoalState.set(runtimeClient.getCurrentGoalState()); - currentEnvironmentData.set(runtimeClient.getRoleEnvironmentData()); - } - catch (InterruptedException e) { - throw new RoleEnvironmentNotAvailableException(e); - } - } - } - - private static void processGoalStateChange(GoalState newGoalState) { - List changes = new LinkedList(); - RoleEnvironmentChangingEvent changingEvent = new RoleEnvironmentChangingEvent(changes); - CurrentState last = lastState.get(); - - calculateChanges(changes); - - if (changes.isEmpty()) { - acceptLatestIncarnation(newGoalState, last); - } - else { - for (RoleEnvironmentChangingListener listener : changingListeners) { - try { - listener.roleEnvironmentChanging(changingEvent); - } - catch (Throwable t) { - t.printStackTrace(); - } - } - - if (changingEvent.isCancelled()) { - CurrentState recycleState = new AcquireCurrentState(clientId, newGoalState.getIncarnation(), - CurrentStatus.RECYCLE, maxDateTime); - - runtimeClient.setCurrentState(recycleState); - - return; - } - - acceptLatestIncarnation(newGoalState, last); - - try { - currentEnvironmentData.set(runtimeClient.getRoleEnvironmentData()); - } - catch (InterruptedException e) { - throw new RoleEnvironmentNotAvailableException(e); - } - - for (RoleEnvironmentChangedListener listener : changedListeners) { - try { - listener.roleEnvironmentChanged(new RoleEnvironmentChangedEvent(changes)); - } - catch (Throwable t) { - t.printStackTrace(); - } - } - } - } - - private static void acceptLatestIncarnation(GoalState newGoalState, CurrentState last) { - if (last != null && last instanceof AcquireCurrentState) { - AcquireCurrentState acquireState = (AcquireCurrentState) last; - - CurrentState acceptState = new AcquireCurrentState(clientId, newGoalState.getIncarnation(), - acquireState.getStatus(), acquireState.getExpiration()); - - runtimeClient.setCurrentState(acceptState); - } - - currentGoalState.set(newGoalState); - } - - private static void calculateChanges(List changes) { - RoleEnvironmentData current = currentEnvironmentData.get(); - RoleEnvironmentData newData; - - try { - newData = runtimeClient.getRoleEnvironmentData(); - } - catch (InterruptedException e) { - throw new RoleEnvironmentNotAvailableException(e); - } - - Map currentConfig = current.getConfigurationSettings(); - Map newConfig = newData.getConfigurationSettings(); - Map currentRoles = current.getRoles(); - Map newRoles = newData.getRoles(); - - for (String setting : currentConfig.keySet()) { - if (newConfig.containsKey(setting)) { - if (!newConfig.get(setting).equals(currentConfig.get(setting))) { - changes.add(new RoleEnvironmentConfigurationSettingChange(setting)); - } - } - else { - changes.add(new RoleEnvironmentConfigurationSettingChange(setting)); - } - } - - for (String setting : newConfig.keySet()) { - if (!currentConfig.containsKey(setting)) { - changes.add(new RoleEnvironmentConfigurationSettingChange(setting)); - } - } - - Set changedRoleSet = new HashSet(); - - for (String role : currentRoles.keySet()) { - if (newRoles.containsKey(role)) { - Role currentRole = currentRoles.get(role); - Role newRole = newRoles.get(role); - - for (String instance : currentRole.getInstances().keySet()) { - if (newRole.getInstances().containsKey(instance)) { - RoleInstance currentInstance = currentRole.getInstances().get(instance); - RoleInstance newInstance = newRole.getInstances().get(instance); - - if (currentInstance.getUpdateDomain() == newInstance.getUpdateDomain() - && currentInstance.getFaultDomain() == newInstance.getFaultDomain()) { - for (String endpoint : currentInstance.getInstanceEndpoints().keySet()) { - if (newInstance.getInstanceEndpoints().containsKey(endpoint)) { - RoleInstanceEndpoint currentEndpoint = currentInstance.getInstanceEndpoints().get( - endpoint); - RoleInstanceEndpoint newEndpoint = newInstance.getInstanceEndpoints().get(endpoint); - - if (!currentEndpoint.getProtocol().equals(newEndpoint.getProtocol()) - || !currentEndpoint.getIpEndPoint().equals(newEndpoint.getIpEndPoint())) { - changedRoleSet.add(role); - } - } - else { - changedRoleSet.add(role); - } - } - } - else { - changedRoleSet.add(role); - } - } - else { - changedRoleSet.add(role); - } - } - } - else { - changedRoleSet.add(role); - } - } - - for (String role : newRoles.keySet()) { - if (currentRoles.containsKey(role)) { - Role currentRole = currentRoles.get(role); - Role newRole = newRoles.get(role); - - for (String instance : newRole.getInstances().keySet()) { - if (currentRole.getInstances().containsKey(instance)) { - RoleInstance currentInstance = currentRole.getInstances().get(instance); - RoleInstance newInstance = newRole.getInstances().get(instance); - - if (currentInstance.getUpdateDomain() == newInstance.getUpdateDomain() - && currentInstance.getFaultDomain() == newInstance.getFaultDomain()) { - for (String endpoint : newInstance.getInstanceEndpoints().keySet()) { - if (currentInstance.getInstanceEndpoints().containsKey(endpoint)) { - RoleInstanceEndpoint currentEndpoint = currentInstance.getInstanceEndpoints().get( - endpoint); - RoleInstanceEndpoint newEndpoint = newInstance.getInstanceEndpoints().get(endpoint); - - if (!currentEndpoint.getProtocol().equals(newEndpoint.getProtocol()) - || !currentEndpoint.getIpEndPoint().equals(newEndpoint.getIpEndPoint())) { - changedRoleSet.add(role); - } - } - else { - changedRoleSet.add(role); - } - } - } - else { - changedRoleSet.add(role); - } - } - else { - changedRoleSet.add(role); - } - } - } - else { - changedRoleSet.add(role); - } - } - - for (String role : changedRoleSet) { - changes.add(new RoleEnvironmentTopologyChange(role)); - } - } - - private static synchronized void raiseStoppingEvent() { - for (RoleEnvironmentStoppingListener listener : stoppingListeners) { - try { - listener.roleEnvironmentStopping(); - } - catch (Throwable t) { - t.printStackTrace(); - } - } - } - - /** - * Returns a {@link RoleInstance} object that represents the role instance - * in which this code is currently executing. - * - * @return A RoleInstance object that represents the role - * instance in which this code is currently executing. - */ - public static RoleInstance getCurrentRoleInstance() { - initialize(); - - return currentEnvironmentData.get().getCurrentInstance(); - } - - /** - * Returns the deployment ID that uniquely identifies the deployment in - * which this role instance is running. - * - * @return A String object that represents the deployment ID. - */ - public static String getDeploymentId() { - initialize(); - - return currentEnvironmentData.get().getDeploymentId(); - } - - /** - * Indicates whether the role instance is running in the Windows Azure - * environment. - * - * @return true if this instance is running in the development - * fabric or in the Windows Azure environment in the cloud; - * otherwise, false. - */ - public static boolean isAvailable() { - try { - initialize(); - } - catch (RoleEnvironmentNotAvailableException ex) { - } - - return runtimeClient != null; - } - - /** - * Indicates whether the role instance is running in the development fabric. - * - * @return true if this instance is running in the development - * fabric; otherwise, false. - */ - public static boolean isEmulated() { - initialize(); - - return currentEnvironmentData.get().isEmulated(); - } - - /** - * Returns the set of {@link Role} objects defined for your service. - *

- * Roles are defined in the service definition file. - * - * @return A java.util.Map object containing the set of {@link Role} objects that represent the roles - * defined for your - * service. - */ - public static Map getRoles() { - initialize(); - - return currentEnvironmentData.get().getRoles(); - } - - /** - * Retrieves the settings in the service configuration file. - *

- * A role's configuration settings are defined in the service definition file. Values for configuration settings are - * set in the service configuration file. - * - * @return A java.util.Map object containing the String objects that represent the - * configuration - * settings. - */ - public static Map getConfigurationSettings() { - initialize(); - - return currentEnvironmentData.get().getConfigurationSettings(); - } - - /** - * Retrieves the set of named local storage resources. - * - * @return A java.util.Map object containing the String objects that represent the local - * storage - * resources. - */ - public static Map getLocalResources() { - initialize(); - - return currentEnvironmentData.get().getLocalResources(); - } - - /** - * Requests that the current role instance be stopped and restarted. - *

- * Before the role instance is recycled, the Windows Azure load balancer takes the role instance out of rotation. - * This ensures that no new requests are routed to the instance while it is restarting. - * - * A call to RequestRecycle initiates the normal shutdown cycle. Windows Azure raises the - * Stopping event and calls the OnStop method so that you can run the necessary code to - * prepare the instance to be recycled. - */ - public static void requestRecycle() { - initialize(); - - CurrentState recycleState = new AcquireCurrentState(clientId, currentGoalState.get().getIncarnation(), - CurrentStatus.RECYCLE, maxDateTime); - - runtimeClient.setCurrentState(recycleState); - } - - /** - * Sets the status of the role instance. - *

- * An instance may indicate that it is in one of two states: Ready or Busy. If an instance's state is Ready, it is - * prepared to receive requests from the load balancer. If the instance's state is Busy, it will not receive - * requests from the load balancer. - * - * @param status - * A {@link RoleInstanceStatus} value that indicates whether the - * instance is ready or busy. - * @param expiration_utc - * A java.util.Date value that specifies the - * expiration date and time of the status. - * - */ - public static void setStatus(RoleInstanceStatus status, Date expiration_utc) { - initialize(); - - CurrentStatus currentStatus = CurrentStatus.STARTED; - - switch (status) { - case Busy: - currentStatus = CurrentStatus.BUSY; - break; - case Ready: - currentStatus = CurrentStatus.STARTED; - } - - Calendar expiration = Calendar.getInstance(); - expiration.setTime(expiration_utc); - - CurrentState newState = new AcquireCurrentState(clientId, currentGoalState.get().getIncarnation(), - currentStatus, expiration); - - lastState.set(newState); - - runtimeClient.setCurrentState(newState); - } - - /** - * Clears the status of the role instance. - *

- * An instance may indicate that it has completed communicating status by calling this method. - * - */ - public static void clearStatus() { - initialize(); - - CurrentState newState = new ReleaseCurrentState(clientId); - - lastState.set(newState); - - runtimeClient.setCurrentState(newState); - } - - /** - * Adds an event listener for the Changed event, which occurs - * after a configuration change has been applied to a role instance. - *

- * A Changed event is encapsulated in a {@link RoleEnvironmentChangedEvent} object. - * - * @param listener - * A {@link RoleEnvironmentChangedListener} object that - * represents the event listener to add. - * - * @see #removeRoleEnvironmentChangedListener - */ - public static synchronized void addRoleEnvironmentChangedListener(RoleEnvironmentChangedListener listener) { - initialize(); - - changedListeners.add(listener); - } - - /** - * Removes an event listener for the Changed event. - * - * @param listener - * A {@link RoleEnvironmentChangedListener} object that - * represents the event listener to remove. - * - * @see #addRoleEnvironmentChangedListener - */ - public static synchronized void removeRoleEnvironmentChangedListener(RoleEnvironmentChangedListener listener) { - initialize(); - - changedListeners.remove(listener); - } - - /** - * Adds an event listener for the Changing event, which occurs - * before a change to the service configuration is applied to the running - * instances of the role. - *

- * Service configuration changes are applied on-the-fly to running role instances. Configuration changes include - * changes to the service configuration changes and changes to the number of instances in the service. - *

- * This event occurs after the new configuration file has been submitted to Windows Azure but before the changes - * have been applied to each running role instance. This event can be cancelled for a given instance to prevent the - * configuration change. - *

- * Note that cancelling this event causes the instance to be automatically recycled. When the instance is recycled, - * the configuration change is applied when it restarts. - *

- * A Changing event is encapsulated in a {@link RoleEnvironmentChangingEvent} object. - * - * @param listener - * A {@link RoleEnvironmentChangingListener} object that - * represents the event listener to add. - * - * @see #removeRoleEnvironmentChangingListener - */ - public static synchronized void addRoleEnvironmentChangingListener(RoleEnvironmentChangingListener listener) { - initialize(); - - changingListeners.add(listener); - } - - /** - * Removes an event listener for the Changing event. - * - * @param listener - * A {@link RoleEnvironmentChangingListener} object that - * represents the event listener to remove. - * - * @see #addRoleEnvironmentChangingListener - */ - public static void removeRoleEnvironmentChangingListener(RoleEnvironmentChangingListener listener) { - initialize(); - - changingListeners.remove(listener); - } - - /** - * Adds an event listener for the Stopping event, which occurs - * wheen the role is stopping. - * - * @param listener - * A {@link RoleEnvironmentStoppingListener} object that - * represents the event listener to add. - * - * @see #removeRoleEnvironmentStoppingListener - */ - public static synchronized void addRoleEnvironmentStoppingListener(RoleEnvironmentStoppingListener listener) { - initialize(); - - stoppingListeners.add(listener); - } - - /** - * Removes an event listener for the Stopping event. - * - * @param listener - * A {@link RoleEnvironmentStoppingListener} object that - * represents the event listener to remove. - * - * @see #addRoleEnvironmentStoppingListener - */ - public static synchronized void removeRoleEnvironmentStoppingListener(RoleEnvironmentStoppingListener listener) { - initialize(); - - stoppingListeners.remove(listener); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingListener.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingListener.java deleted file mode 100644 index 128216aff7b17..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingListener.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -/** - * Represents the listener for the environment changing event. - *

- * The environment changing event is encapsulated in an - * {@link com.microsoft.windowsazure.serviceruntime.RoleEnvironmentChangingEvent} object. - */ -public interface RoleEnvironmentChangingListener { - - /** - * Occurs before a change to the service configuration is applied to the - * running instances of the role. - *

- * Service configuration changes are applied on-the-fly to running role instances. Configuration changes include - * changes to the service configuration changes and changes to the number of instances in the service. - *

- * This event occurs after the new configuration file has been submitted to Windows Azure but before the changes - * have been applied to each running role instance. This event can be cancelled for a given instance to prevent the - * configuration change. - *

- * Note that cancelling this event causes the instance to be automatically recycled. When the instance is recycled, - * the configuration change is applied when it restarts. - * - * @param event - * A {@link RoleEnvironmentChangingEvent} object that represents - * the environment changing event. - * - * @see RoleEnvironmentChangedListener#roleEnvironmentChanged - */ - public void roleEnvironmentChanging(RoleEnvironmentChangingEvent event); - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstance.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstance.java deleted file mode 100644 index 4f7a470f2f209..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstance.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import java.util.Map; - -/** - * Represents an instance of a role. - */ -public final class RoleInstance { - private final String id; - private final int faultDomain; - private final int updateDomain; - private final Map endpoints; - private Role role; - - /** - * Constructor - * - * @param id - * @param faultDomain - * @param updateDomain - * @param endpoints - */ - RoleInstance(String id, int faultDomain, int updateDomain, Map endpoints) { - this.id = id; - this.faultDomain = faultDomain; - this.updateDomain = updateDomain; - this.endpoints = endpoints; - } - - void setRole(Role role) { - this.role = role; - } - - /** - * Returns an integer value that indicates the fault domain in which this - * instance resides. - * - * @return The fault domain in which this instance resides. - */ - public int getFaultDomain() { - return faultDomain; - } - - /** - * Returns the ID of this instance. - *

- * The returned ID is unique to the application domain of the role's instance. If an instance is terminated and has - * been configured to restart automatically, the restarted instance will have the same ID as the terminated - * instance. - * - * @return A String object that represents the ID of this - * instance. - */ - public String getId() { - return id; - } - - /** - * Returns an integer value that indicates the update domain in which this - * instance resides. - * - * @return The update domain in which this instance resides. - */ - public int getUpdateDomain() { - return updateDomain; - } - - /** - * Returns the {@link Role} object associated with this instance. - * - * @return The Role object associated with this instance - */ - public Role getRole() { - return role; - } - - /** - * Returns the set of endpoints associated with this role instance. - * - * @return A Map object of {@link RoleInstanceEndpoint} objects - * that represent the set of endpoints associated with this - * role instance. - */ - public Map getInstanceEndpoints() { - return endpoints; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceStatus.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceStatus.java deleted file mode 100644 index 89e62e8e51a10..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceStatus.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -/** - * Defines role instance status values, such as Busy and Ready. - *

- * The {@link RoleEnvironment#setStatus} method uses a value from this enumeration. - */ -public enum RoleInstanceStatus { - /** - * The role instance is unavailable for requests. - */ - Busy, - /** - * The role instance is ready to accept requests. - */ - Ready -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeGoalStateClient.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeGoalStateClient.java deleted file mode 100644 index 8ae17edc65a45..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeGoalStateClient.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -/** - * - */ -interface RuntimeGoalStateClient { - public GoalState getCurrentGoalState() throws InterruptedException; - - public RoleEnvironmentData getRoleEnvironmentData() throws InterruptedException; - - public void addGoalStateChangedListener(GoalStateChangedListener listener); - - public void removeGoalStateChangedListener(GoalStateChangedListener listener); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlCurrentStateSerializer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlCurrentStateSerializer.java deleted file mode 100644 index 2c3b741c6e0c6..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlCurrentStateSerializer.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import java.io.OutputStream; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - -/** - * - */ -class XmlCurrentStateSerializer implements CurrentStateSerializer { - public XmlCurrentStateSerializer() { - } - - public void serialize(CurrentState state, OutputStream stream) { - try { - JAXBContext context = JAXBContext.newInstance(GoalStateInfo.class.getPackage().getName()); - Marshaller marshaller = context.createMarshaller(); - - ObjectFactory factory = new ObjectFactory(); - CurrentStateInfo info = factory.createCurrentStateInfo(); - StatusLeaseInfo leaseInfo = factory.createStatusLeaseInfo(); - - leaseInfo.setClientId(state.getClientId()); - - if (state instanceof AcquireCurrentState) { - AcquireCurrentState acquireState = (AcquireCurrentState) state; - AcquireLeaseInfo acquire = factory.createAcquireLeaseInfo(); - - acquire.setExpiration(acquireState.getExpiration()); - acquire.setIncarnation(acquireState.getIncarnation()); - - switch (acquireState.getStatus()) { - case BUSY: - acquire.setStatus(CurrentStatusEnum.BUSY); - break; - case RECYCLE: - acquire.setStatus(CurrentStatusEnum.RECYCLE); - break; - case STARTED: - acquire.setStatus(CurrentStatusEnum.STARTED); - break; - case STOPPED: - acquire.setStatus(CurrentStatusEnum.STOPPED); - break; - } - - leaseInfo.setAcquire(acquire); - } - else if (state instanceof ReleaseCurrentState) { - leaseInfo.setRelease(factory.createStatusLeaseInfoRelease()); - } - - info.setStatusLease(leaseInfo); - - marshaller.marshal(factory.createCurrentState(info), stream); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializer.java deleted file mode 100644 index 688e5dfc6ef5f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializer.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import java.io.StringReader; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; - -import org.xml.sax.InputSource; - -/** - * - */ -class XmlGoalStateDeserializer { - public XmlGoalStateDeserializer() { - } - - public GoalState deserialize(String document) { - try { - JAXBContext context = JAXBContext.newInstance(GoalStateInfo.class.getPackage().getName()); - Unmarshaller unmarshaller = context.createUnmarshaller(); - InputSource source = new InputSource(new StringReader(document)); - - @SuppressWarnings("unchecked") - GoalStateInfo goalStateInfo = ((JAXBElement) unmarshaller.unmarshal(source)).getValue(); - - return new GoalState(goalStateInfo.incarnation, Enum.valueOf(ExpectedState.class, - goalStateInfo.expectedState.toString()), goalStateInfo.getRoleEnvironmentPath(), - goalStateInfo.getDeadline(), goalStateInfo.getCurrentStateEndpoint()); - - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java deleted file mode 100644 index 6304825adc8cf..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import java.io.InputStream; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; - -/** - * - */ -class XmlRoleEnvironmentDataDeserializer implements RoleEnvironmentDataDeserializer { - public XmlRoleEnvironmentDataDeserializer() { - } - - @Override - public RoleEnvironmentData deserialize(InputStream stream) { - try { - JAXBContext context = JAXBContext.newInstance(RoleEnvironmentInfo.class.getPackage().getName()); - Unmarshaller unmarshaller = context.createUnmarshaller(); - - @SuppressWarnings("unchecked") - RoleEnvironmentInfo environmentInfo = ((JAXBElement) unmarshaller.unmarshal(stream)) - .getValue(); - - Map configurationSettings = translateConfigurationSettings(environmentInfo); - Map localResources = translateLocalResources(environmentInfo); - RoleInstance currentInstance = translateCurrentInstance(environmentInfo); - Map roles = translateRoles(environmentInfo, currentInstance, environmentInfo - .getCurrentInstance().getRoleName()); - - return new RoleEnvironmentData(environmentInfo.getDeployment().getId(), configurationSettings, - localResources, currentInstance, roles, environmentInfo.getDeployment().isEmulated()); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - } - - private Map translateConfigurationSettings(RoleEnvironmentInfo environmentInfo) { - Map configurationSettings = new HashMap(); - - for (ConfigurationSettingInfo settingInfo : environmentInfo.getCurrentInstance().getConfigurationSettings() - .getConfigurationSetting()) { - configurationSettings.put(settingInfo.getName(), settingInfo.getValue()); - } - - return configurationSettings; - } - - private Map translateLocalResources(RoleEnvironmentInfo environmentInfo) { - Map localResources = new HashMap(); - - for (LocalResourceInfo resourceInfo : environmentInfo.getCurrentInstance().getLocalResources() - .getLocalResource()) { - localResources.put(resourceInfo.getName(), - new LocalResource(resourceInfo.getSizeInMB(), resourceInfo.getName(), resourceInfo.getPath())); - } - - return localResources; - } - - private Map translateRoles(RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance, - String currentRole) { - Map roles = new HashMap(); - - for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) { - Map instances = translateRoleInstances(roleInfo.getInstances()); - - if (roleInfo.getName().equals(currentRole)) { - instances.put(currentInstance.getId(), currentInstance); - } - - Role role = new Role(roleInfo.getName(), instances); - - for (RoleInstance instance : role.getInstances().values()) { - instance.setRole(role); - } - - roles.put(roleInfo.getName(), role); - } - - if (!roles.containsKey(currentRole)) { - Map instances = new HashMap(); - - instances.put(currentInstance.getId(), currentInstance); - - Role singleRole = new Role(currentRole, instances); - - currentInstance.setRole(singleRole); - - roles.put(currentRole, singleRole); - } - - return roles; - } - - private Map translateRoleInstances(RoleInstancesInfo instancesInfo) { - Map roleInstances = new HashMap(); - - for (RoleInstanceInfo instanceInfo : instancesInfo.getInstance()) { - RoleInstance instance = new RoleInstance(instanceInfo.getId(), instanceInfo.getFaultDomain(), - instanceInfo.getUpdateDomain(), translateRoleInstanceEndpoints(instanceInfo.getEndpoints())); - - for (RoleInstanceEndpoint endpoint : instance.getInstanceEndpoints().values()) { - endpoint.setRoleInstance(instance); - } - - roleInstances.put(instance.getId(), instance); - } - - return roleInstances; - } - - private Map translateRoleInstanceEndpoints(EndpointsInfo endpointsInfo) { - Map endpoints = new HashMap(); - - for (EndpointInfo endpointInfo : endpointsInfo.getEndpoint()) { - RoleInstanceEndpoint endpoint = new RoleInstanceEndpoint(endpointInfo.getProtocol().toString(), - new InetSocketAddress(endpointInfo.getAddress(), endpointInfo.getPort())); - - endpoints.put(endpointInfo.getName(), endpoint); - } - - return endpoints; - } - - private RoleInstance translateCurrentInstance(RoleEnvironmentInfo environmentInfo) { - CurrentRoleInstanceInfo currentInstanceInfo = environmentInfo.getCurrentInstance(); - RoleInstance currentInstance = new RoleInstance(currentInstanceInfo.getId(), - currentInstanceInfo.getFaultDomain(), currentInstanceInfo.getUpdateDomain(), - translateRoleInstanceEndpoints(environmentInfo.getCurrentInstance().getEndpoints())); - - for (RoleInstanceEndpoint endpoint : currentInstance.getInstanceEndpoints().values()) { - endpoint.setRoleInstance(currentInstance); - } - - return currentInstance; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobConfiguration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobConfiguration.java deleted file mode 100644 index 80c3896d33a3b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobConfiguration.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob; - -/** - * This class contains static strings used to identify parts of a service configuration instance associated with the - * Windows Azure Blob service. - *

- * These values must not be altered. - */ -public class BlobConfiguration { - /** - * The Blob configuration account name constant. This String value is used as a key in the - * configuration file, to identify the value for the DNS prefix name for the storage account. - */ - public final static String ACCOUNT_NAME = "blob.accountName"; - - /** - * The Blob configuration account key constant. This String value is used as a key in the - * configuration file, to identify the value for the storage service account key. - */ - public final static String ACCOUNT_KEY = "blob.accountKey"; - - /** - * The Blob configuration URI constant. This String value is used as a key in the - * configuration file, to identify the URI value for the Blob storage service REST API address for the - * storage account. - */ - public final static String URI = "blob.uri"; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobContract.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobContract.java deleted file mode 100644 index ac52417127140..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobContract.java +++ /dev/null @@ -1,1550 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob; - -import java.io.InputStream; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.models.AcquireLeaseOptions; -import com.microsoft.windowsazure.services.blob.models.AcquireLeaseResult; -import com.microsoft.windowsazure.services.blob.models.BlobServiceOptions; -import com.microsoft.windowsazure.services.blob.models.BlockList; -import com.microsoft.windowsazure.services.blob.models.BreakLeaseResult; -import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.ContainerACL; -import com.microsoft.windowsazure.services.blob.models.CopyBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CopyBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobPagesOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobPagesResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotResult; -import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; -import com.microsoft.windowsazure.services.blob.models.DeleteBlobOptions; -import com.microsoft.windowsazure.services.blob.models.DeleteContainerOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobMetadataOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobResult; -import com.microsoft.windowsazure.services.blob.models.GetContainerACLResult; -import com.microsoft.windowsazure.services.blob.models.GetContainerPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobRegionsOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobRegionsResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobsOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobsResult; -import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; -import com.microsoft.windowsazure.services.blob.models.ListContainersResult; -import com.microsoft.windowsazure.services.blob.models.PageRange; -import com.microsoft.windowsazure.services.blob.models.ServiceProperties; -import com.microsoft.windowsazure.services.blob.models.SetBlobMetadataOptions; -import com.microsoft.windowsazure.services.blob.models.SetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.SetContainerMetadataOptions; -import com.microsoft.windowsazure.services.core.FilterableService; -import com.microsoft.windowsazure.services.core.ServiceException; - -/** - * Defines the methods available on the Windows Azure blob storage service. Construct an object instance implementing - * BlobContract with one of the static create methods on {@link BlobService}. These methods - * associate a Configuration with the implementation, so the methods on the instance of - * BlobContract all work with a particular storage account. - */ -public interface BlobContract extends FilterableService { - /** - * Gets the service properties of the blob storage account. - * - * @return - * A {@link GetServicePropertiesResult} reference to the blob service properties. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetServicePropertiesResult getServiceProperties() throws ServiceException; - - /** - * Gets the service properties of the blob storage account, using the specified options. - *

- * Use the {@link BlobServiceOptions options} parameter to specify a server timeout for the operation. - * - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @return - * A {@link GetServicePropertiesResult} reference to the blob service properties. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetServicePropertiesResult getServiceProperties(BlobServiceOptions options) throws ServiceException; - - /** - * Sets the service properties of the blob storage account. - * - * @param serviceProperties - * A {@link ServiceProperties} instance containing the blob service properties to set. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException; - - /** - * Sets the service properties of the blob storage account, using the specified options. - *

- * Use the {@link BlobServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param serviceProperties - * A {@link ServiceProperties} instance containing the blob service properties to set. - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setServiceProperties(ServiceProperties serviceProperties, BlobServiceOptions options) throws ServiceException; - - /** - * Gets a list of the containers in the blob storage account. - * - * @return - * A {@link ListContainersResult} reference to the result of the list containers operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListContainersResult listContainers() throws ServiceException; - - /** - * Gets a list of the containers in the blob storage account using the specified options. - *

- * Use the {@link ListContainersOptions options} parameter to specify options, including a server response timeout - * for the request, a container name prefix filter, a marker for continuing requests, the maximum number of results - * to return in a request, and whether to include container metadata in the results. - * - * @param options - * A {@link ListContainersOptions} instance containing options for the request. - * @return - * A {@link ListContainersResult} reference to the result of the list containers operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListContainersResult listContainers(ListContainersOptions options) throws ServiceException; - - /** - * Creates a container with the specified name. - *

- * Container names must be unique within a storage account, and must follow the naming rules specified in Naming and Referencing Containers, - * Blobs, and Metadata. - * - * @param container - * A {@link String} containing the name of the container to create. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void createContainer(String container) throws ServiceException; - - /** - * Creates a container with the specified name, using the specified options. - *

- * Use the {@link CreateContainerOptions options} parameter to specify options, including a server response timeout - * for the request, metadata to set on the container, and the public access level for container and blob data. - * Container names must be unique within a storage account, and must follow the naming rules specified in Naming and Referencing Containers, - * Blobs, and Metadata. - * - * @param container - * A {@link String} containing the name of the container to create. - * @param options - * A {@link CreateContainerOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void createContainer(String container, CreateContainerOptions options) throws ServiceException; - - /** - * Marks a container for deletion. The container and any blobs contained within it are later deleted during garbage - * collection. - *

- * When a container is deleted, a container with the same name cannot be created for at least 30 seconds; the - * container may not be available for more than 30 seconds if the service is still processing the request. - * - * @param container - * A {@link String} containing the name of the container to delete. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteContainer(String container) throws ServiceException; - - /** - * Marks a container for deletion, using the specified options. The container and any blobs contained within it are - * later deleted during garbage collection. - *

- * Use the {@link DeleteContainerOptions options} parameter to specify the server response timeout and any access - * conditions for the container deletion operation. Access conditions can be used to make the operation conditional - * on the value of the Etag or last modified time of the container. - *

- * When a container is deleted, a container with the same name cannot be created for at least 30 seconds; the - * container may not be available for more than 30 seconds if the service is still processing the request. - * - * @param container - * A {@link String} containing the name of the container to delete. - * @param options - * A {@link DeleteContainerOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteContainer(String container, DeleteContainerOptions options) throws ServiceException; - - /** - * Gets all metadata and system properties for a container. - * - * @param container - * A {@link String} containing the name of the container to get properties and metadata for. - * @return - * A {@link GetContainerPropertiesResult} reference to the container properties and metadata. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetContainerPropertiesResult getContainerProperties(String container) throws ServiceException; - - /** - * Gets all metadata and system properties for a container, using the specified options. - *

- * Use the {@link BlobServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param container - * A {@link String} containing the name of the container to get properties and metadata for. - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @return - * A {@link GetContainerPropertiesResult} reference to the container properties and metadata. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetContainerPropertiesResult getContainerProperties(String container, BlobServiceOptions options) - throws ServiceException; - - /** - * Gets all metadata for a container. - * - * @param container - * A {@link String} containing the name of the container to get the metadata from. - * @return - * A {@link GetContainerPropertiesResult} reference to the container metadata. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetContainerPropertiesResult getContainerMetadata(String container) throws ServiceException; - - /** - * Gets all metadata for a container, using the specified options. - *

- * Use the {@link BlobServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param container - * A {@link String} containing the name of the container to get the metadata from. - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @return - * A {@link GetContainerPropertiesResult} reference to the container metadata. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetContainerPropertiesResult getContainerMetadata(String container, BlobServiceOptions options) - throws ServiceException; - - /** - * Gets the public access level and container-level access policies for a container. - * - * @param container - * A {@link String} containing the name of the container to get the public access level and - * container-level access policies from. - * @return - * A {@link GetContainerACLResult} reference to the container's public access level and - * container-level access policies. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetContainerACLResult getContainerACL(String container) throws ServiceException; - - /** - * Gets the public access level and container-level access policies for a container, using the specified - * options. - *

- * Use the {@link BlobServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param container - * A {@link String} containing the name of the container to get the public access level and - * container-level access policies from. - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @return - * A {@link GetContainerACLResult} reference to the container's public access level and - * container-level access policies. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetContainerACLResult getContainerACL(String container, BlobServiceOptions options) throws ServiceException; - - /** - * Sets the public access level and container-level access policies for a container. - * - * @param container - * A {@link String} containing the name of the container to set the public access level and - * container-level access policies on. - * @param acl - * A {@link ContainerACL} instance containing the public access level and container-level access policies - * to set on the container. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setContainerACL(String container, ContainerACL acl) throws ServiceException; - - /** - * Sets the public access level and container-level access policies for a container, using the specified options. - *

- * Use the {@link BlobServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param container - * A {@link String} containing the name of the container to set the public access level and - * container-level access policies on. - * @param acl - * A {@link ContainerACL} instance containing the public access level and container-level access policies - * to set on the container. - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setContainerACL(String container, ContainerACL acl, BlobServiceOptions options) throws ServiceException; - - /** - * Sets the metadata on a container. - *

- * Calling this method overwrites all existing metadata that is associated with the container. It is not possible to - * modify an individual name-value pair. To keep the existing metadata and update or add individual values, make a - * copy of the metadata, make your changes, and upload the modified copy. Calling this method also updates the Etag - * and Last-Modified-Time properties for the container. - *

- * Metadata for a container can also be set at the time it is created. - * - * @param container - * A {@link String} containing the name of the container to set metadata on. - * @param metadata - * A {@link java.util.HashMap} of pairs of {@link String} containing the metadata name-value pairs to set - * on the container. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setContainerMetadata(String container, HashMap metadata) throws ServiceException; - - /** - * Sets the metadata on a container, using the specified options. - *

- * Use the {@link SetContainerMetadataOptions options} parameter to specify the server timeout for the operation, - * and to set access conditions on whether to update the metadata or not. - *

- * Calling this method overwrites all existing metadata that is associated with the container. It is not possible to - * modify an individual name-value pair. To keep the existing metadata and update or add individual values, make a - * copy of the metadata, make your changes, and upload the modified copy. Calling this method also updates the ETag - * and last modified time properties for the container. - *

- * Metadata for a container can also be set at the time it is created. - * - * @param container - * A {@link String} containing the name of the container to set metadata on. - * @param metadata - * A {@link java.util.HashMap} of pairs of {@link String} containing the metadata name-value pairs to set - * on the container. - * @param options - * A {@link SetContainerMetadataOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setContainerMetadata(String container, HashMap metadata, SetContainerMetadataOptions options) - throws ServiceException; - - /** - * Lists the blobs in a container. - * - * @param container - * A {@link String} containing the name of the container of blobs to list. - * @return - * A {@link ListBlobsResult} reference to the result of the list blobs operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListBlobsResult listBlobs(String container) throws ServiceException; - - /** - * Lists the blobs in a container, using the specified options. - *

- * Use the {@link ListBlobsOptions options} parameter to optionally specify the server timeout for the operation, a - * prefix for blobs to match, a marker to continue a list operation, a maximum number of results to return with one - * list operation, a delimiter for structuring virtual blob hierarchies, and whether to include blob metadata, blob - * snapshots, and uncommitted blobs in the results. - * - * @param container - * A {@link String} containing the name of the container of blobs to list. - * @param options - * A {@link ListBlobsOptions} instance containing options for the request. - * @return - * A {@link ListBlobsResult} reference to the result of the list blobs operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListBlobsResult listBlobs(String container, ListBlobsOptions options) throws ServiceException; - - /** - * Creates a page blob of the specified maximum length. - *

- * Note that this method only initializes the page blob. To add content to a page blob, use the - * {@link BlobContract#createBlobPages(String, String, PageRange, long, InputStream)} or - * {@link BlobContract#createBlobPages(String, String, PageRange, long, InputStream, CreateBlobPagesOptions)} - * methods. - * - * @param container - * A {@link String} containing the name of the container to create the blob in. - * @param blob - * A {@link String} containing the name of the blob to create. A blob name can contain any combination of - * characters, but reserved URL characters must be properly escaped. A blob name must be at least one - * character long and cannot be more than 1,024 characters long, and must be unique within the container. - * @param length - * The length in bytes of the page blob to create. The length must be a multiple of 512 and may be up to - * 1 TB. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobResult createPageBlob(String container, String blob, long length) throws ServiceException; - - /** - * Creates a page blob of the specified maximum length, using the specified options. - *

- * Use the {@link CreateBlobOptions options} parameter to optionally specify the server timeout for the operation, - * the MIME content type and content encoding for the blob, the content language, the MD5 hash, a cache control - * value, blob metadata, and a sequence number. - *

- * Note that this method only initializes the blob. To add content to a page blob, use the - * {@link BlobContract#createBlobPages(String, String, PageRange, long, InputStream)} or - * {@link BlobContract#createBlobPages(String, String, PageRange, long, InputStream, CreateBlobPagesOptions)} - * methods. - * - * @param container - * A {@link String} containing the name of the container to create the blob in. - * @param blob - * A {@link String} containing the name of the blob to create. A blob name can contain any combination of - * characters, but reserved URL characters must be properly escaped. A blob name must be at least one - * character long and cannot be more than 1,024 characters long, and must be unique within the container. - * @param length - * The length in bytes of the page blob to create. The length must be a multiple of 512 and may be up to - * 1 TB. - * @param options - * A {@link CreateBlobOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobResult createPageBlob(String container, String blob, long length, CreateBlobOptions options) - throws ServiceException; - - /** - * Creates a block blob from a content stream. - * - * @param container - * A {@link String} containing the name of the container to create the blob in. - * @param blob - * A {@link String} containing the name of the blob to create. A blob name can contain any combination of - * characters, but reserved URL characters must be properly escaped. A blob name must be at least one - * character long and cannot be more than 1,024 characters long, and must be unique within the container. - * @param contentStream - * An {@link InputStream} reference to the content stream to upload to the new blob. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobResult createBlockBlob(String container, String blob, InputStream contentStream) throws ServiceException; - - /** - * Creates a block blob from a content stream, using the specified options. - *

- * Use the {@link CreateBlobOptions options} parameter to optionally specify the server timeout for the operation, - * the MIME content type and content encoding for the blob, the content language, the MD5 hash, a cache control - * value, and blob metadata. - * - * @param container - * A {@link String} containing the name of the container to create the blob in. - * @param blob - * A {@link String} containing the name of the blob to create. A blob name can contain any combination of - * characters, but reserved URL characters must be properly escaped. A blob name must be at least one - * character long and cannot be more than 1,024 characters long, and must be unique within the container. - * @param contentStream - * An {@link InputStream} reference to the content to upload to the new blob. - * @param options - * A {@link CreateBlobOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobResult createBlockBlob(String container, String blob, InputStream contentStream, CreateBlobOptions options) - throws ServiceException; - - /** - * Clears a range of pages from a page blob. - *

- * This method clears and releases the storage for the page range specified by the range parameter within - * the page blob specified by the blob and container parameters. The range parameter can - * specify up to the value of the blob's full size. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to clear the range from. - * @param range - * A {@link PageRange} containing the start and end of the range to clear in the page blob. - * @return - * A {@link CreateBlobPagesResult} reference to the result of the clear blob pages operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobPagesResult clearBlobPages(String container, String blob, PageRange range) throws ServiceException; - - /** - * Clears a range of pages from a page blob, using the specified options. - *

- * This method clears and releases the storage for the page range specified by the range parameter within - * the page blob specified by the blob and container parameters. The range parameter can - * specify up to the value of the blob's full size. Use the {@link CreateBlobPagesOptions options} parameter to - * optionally specify the server timeout for the operation, the lease ID if the blob has an active lease, and access - * conditions for the clear pages operation. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to clear the range from. - * @param range - * A {@link PageRange} containing the start and end of the range to clear in the page blob. - * @param options - * A {@link CreateBlobPagesOptions} instance containing options for the request. - * @return - * A {@link CreateBlobPagesResult} reference to the result of the clear blob pages operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobPagesResult clearBlobPages(String container, String blob, PageRange range, CreateBlobPagesOptions options) - throws ServiceException; - - /** - * Creates or updates a range of pages in a page blob. - *

- * This method creates or updates the storage for the page range specified by the range parameter within - * the page blob specified by the blob and container parameters. The range parameter can - * specify up to 4MB of data, and its length must match the length parameter. The operation stores - * length bytes from the contentStream parameter in the specified page range in the blob. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to create or update the range content of. - * @param range - * A {@link PageRange} containing the start and end of the range to create or update in the page blob. - * @param length - * The number of bytes to read from the contentStream parameter into the specified range. - * @param contentStream - * An {@link InputStream} reference to the content to copy to the page blob. - * @return - * A {@link CreateBlobPagesResult} reference to the result of the create blob pages operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobPagesResult createBlobPages(String container, String blob, PageRange range, long length, - InputStream contentStream) throws ServiceException; - - /** - * Creates or updates a range of pages in a page blob, using the specified options. - *

- * This method creates or updates the storage for the page range specified by the range parameter within - * the page blob specified by the blob and container parameters. The range parameter can - * specify up to 4MB of data, and its length must match the length parameter. The operation stores - * length bytes from the contentStream parameter in the specified page range in the blob. Use the - * {@link CreateBlobPagesOptions options} parameter to optionally specify the server timeout for the operation, the - * lease ID if the blob has an active lease, an MD5 hash of the content for verification, and access conditions for - * the create pages operation. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to create or update the range content of. - * @param range - * A {@link PageRange} containing the start and end of the range to create or update in the page blob. - * @param length - * The number of bytes to read from the contentStream parameter into the specified range. - * @param contentStream - * An {@link InputStream} reference to the content to copy to the page blob. - * @param options - * A {@link CreateBlobPagesOptions} instance containing options for the request. - * @return - * A {@link CreateBlobPagesResult} reference to the result of the create blob pages operation. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobPagesResult createBlobPages(String container, String blob, PageRange range, long length, - InputStream contentStream, CreateBlobPagesOptions options) throws ServiceException; - - /** - * Creates a new uncommited block from a content stream. - *

- * This method creates an uncommitted block for a block blob specified by the blob and container - * parameters. The blockId parameter is a client-specified ID for the block, which must be less than or - * equal to 64 bytes in size. For a given blob, the length of the value specified for the blockId parameter - * must be the same size for each block. The contentStream parameter specifies the content to be copied to - * the block. The content for the block must be less than or equal to 4 MB in size. - *

- * To create or update a block blob, the blocks that have been successfully written to the server with this method - * must be committed using a call to {@link BlobContract#commitBlobBlocks(String, String, BlockList)} or - * {@link BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions)}. - * - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to create the block for. - * @param blockId - * A {@link String} containing a client-specified ID for the block. - * @param contentStream - * An {@link InputStream} reference to the content to copy to the block. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void createBlobBlock(String container, String blob, String blockId, InputStream contentStream) - throws ServiceException; - - /** - * Creates a new uncommitted block from a content stream, using the specified options. - *

- * This method creates an uncommitted block for a block blob specified by the blob and container - * parameters. The blockId parameter is a client-specified ID for the block, which must be less than or - * equal to 64 bytes in size. For a given blob, the length of the value specified for the blockId parameter - * must be the same size for each block. The contentStream parameter specifies the content to be copied to - * the block. The content for the block must be less than or equal to 4 MB in size. Use the - * {@link CreateBlobBlockOptions options} parameter to optionally specify the server timeout for the operation, the - * lease ID if the blob has an active lease, and the MD5 hash value for the block content. - *

- * To create or update a block blob, the blocks that have been successfully written to the server with this method - * must be committed using a call to {@link BlobContract#commitBlobBlocks(String, String, BlockList)} or - * {@link BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions)}. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to create the block for. - * @param blockId - * A {@link String} containing a client-specified ID for the block. - * @param contentStream - * An {@link InputStream} reference to the content to copy to the block. - * @param options - * A {@link CreateBlobBlockOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void createBlobBlock(String container, String blob, String blockId, InputStream contentStream, - CreateBlobBlockOptions options) throws ServiceException; - - /** - * Commits a list of blocks to a block blob. - *

- * This method creates or updates the block blob specified by the blob and container parameters. - * You can call this method to update a blob by uploading only those blocks that have changed, then committing the - * new and existing blocks together. You can do this with the blockList parameter by specifying whether to - * commit a block from the committed block list or from the uncommitted block list, or to commit the most recently - * uploaded version of the block, whichever list it may belong to. - *

- * In order to be written as part of a blob, each block in the list must have been successfully written to the - * server with a call to {@link BlobContract#createBlobBlock(String, String, String, InputStream)} or - * {@link BlobContract#createBlobBlock(String, String, String, InputStream, CreateBlobBlockOptions)}. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the block blob to create or update. - * @param blockList - * A {@link BlockList} containing the list of blocks to commit to the block blob. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void commitBlobBlocks(String container, String blob, BlockList blockList) throws ServiceException; - - /** - * Commits a block list to a block blob, using the specified options. - *

- * This method creates or updates the block blob specified by the blob and container parameters. - * You can call this method to update a blob by uploading only those blocks that have changed, then committing the - * new and existing blocks together. You can do this with the blockList parameter by specifying whether to - * commit a block from the committed block list or from the uncommitted block list, or to commit the most recently - * uploaded version of the block, whichever list it may belong to. Use the {@link CommitBlobBlocksOptions options} - * parameter to optionally specify the server timeout for the operation, the MIME content type and content encoding - * for the blob, the content language, the MD5 hash, a cache control value, blob metadata, the lease ID if the blob - * has an active lease, and any access conditions for the operation. - *

- * In order to be written as part of a blob, each block in the list must have been successfully written to the - * server with a call to {@link BlobContract#createBlobBlock(String, String, String, InputStream)} or - * {@link BlobContract#createBlobBlock(String, String, String, InputStream, CreateBlobBlockOptions)}. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the block blob to create or update. - * @param blockList - * A {@link BlockList} containing the list of blocks to commit to the block blob. - * @param options - * A {@link CommitBlobBlocksOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void commitBlobBlocks(String container, String blob, BlockList blockList, CommitBlobBlocksOptions options) - throws ServiceException; - - /** - * Lists the blocks of a blob. - *

- * This method lists the committed blocks of the block blob specified by the blob and container - * parameters. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the block blob to list. - * @return - * A {@link ListBlobBlocksResult} instance containing the list of blocks returned for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListBlobBlocksResult listBlobBlocks(String container, String blob) throws ServiceException; - - /** - * Lists the blocks of a blob, using the specified options. - *

- * This method lists the committed blocks, uncommitted blocks, or both, of the block blob specified by the - * blob and container parameters. Use the {@link ListBlobBlocksOptions options} parameter to - * specify an optional server timeout for the operation, the lease ID if the blob has an active lease, the snapshot - * timestamp to get the committed blocks of a snapshot, whether to return the committed block list, and whether to - * return the uncommitted block list. By default, only the committed blocks of the blob are returned. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the block blob to list. - * @param options - * A {@link ListBlobBlocksOptions} instance containing options for the request. - * @return - * A {@link ListBlobBlocksResult} instance containing the list of blocks returned for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListBlobBlocksResult listBlobBlocks(String container, String blob, ListBlobBlocksOptions options) - throws ServiceException; - - /** - * Gets the properties of a blob. - *

- * This method lists the properties of the blob specified by the blob and container parameters. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get properties for. - * @return - * A {@link GetBlobPropertiesResult} instance containing the blob properties returned for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetBlobPropertiesResult getBlobProperties(String container, String blob) throws ServiceException; - - /** - * Gets the properties of a blob, using the specified options. - *

- * This method lists the properties of the blob specified by the blob and container parameters. - * Use the {@link GetBlobPropertiesOptions options} parameter to set an optional server timeout for the operation, - * the lease ID if the blob has an active lease, the snapshot timestamp to get the properties of a snapshot, and any - * access conditions for the request. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get properties for. - * @param options - * A {@link GetBlobPropertiesOptions} instance containing options for the request. - * @return - * A {@link GetBlobPropertiesResult} instance containing the blob properties returned for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetBlobPropertiesResult getBlobProperties(String container, String blob, GetBlobPropertiesOptions options) - throws ServiceException; - - /** - * Gets the metadata of a blob. - *

- * This method lists the user-specified metadata of the blob specified by the blob and container - * parameters. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get metadata for. - * @return - * A {@link GetBlobMetadataResult} instance containing the blob metadata returned for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetBlobMetadataResult getBlobMetadata(String container, String blob) throws ServiceException; - - /** - * Gets the metadata of a blob, using the specified options. - *

- * This method lists the user-specified metadata of the blob specified by the blob and container - * parameters. Use the {@link GetBlobMetadataOptions options} parameter to set an optional server timeout for the - * operation, the lease ID if the blob has an active lease, the snapshot timestamp to get the properties of a - * snapshot, and any access conditions for the request. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get metadata for. - * @param options - * A {@link GetBlobMetadataOptions} instance containing options for the request. - * @return - * A {@link GetBlobMetadataResult} instance containing the blob metadata returned for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetBlobMetadataResult getBlobMetadata(String container, String blob, GetBlobMetadataOptions options) - throws ServiceException; - - /** - * Gets the list of valid page ranges for a page blob. - *

- * This method lists the valid page ranges of the page blob specified by the blob and container - * parameters. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get page ranges for. - * @return - * A {@link ListBlobRegionsResult} instance containing the valid page ranges of the blob. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListBlobRegionsResult listBlobRegions(String container, String blob) throws ServiceException; - - /** - * Gets a list of valid page ranges for a page blob or snapshot of a page blob, using the specified options. - *

- * This method lists the valid page ranges of the page blob specified by the blob and container - * parameters. Use the {@link ListBlobRegionsOptions options} parameter to set an optional server timeout for the - * operation, the lease ID if the blob has an active lease, the snapshot timestamp to get the valid page ranges of a - * snapshot, the start offset and/or end offset to use to narrow the returned valid page range results, and any - * access conditions for the request. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get page ranges for. - * @param options - * A {@link ListBlobRegionsOptions} instance containing options for the request. - * @return - * A {@link ListBlobRegionsResult} instance containing the valid page ranges of the blob. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - ListBlobRegionsResult listBlobRegions(String container, String blob, ListBlobRegionsOptions options) - throws ServiceException; - - /** - * Sets the specified properties on a blob. - *

- * This method sets properties on the blob specified by the blob and container parameters. Use the - * {@link SetBlobPropertiesOptions options} parameter to set an optional server timeout for the operation, the MIME - * content type and content encoding for the blob, the content length, the content language, the MD5 hash, a cache - * control value, a blob lease ID, a sequence number and sequence number action value, and any access conditions for - * the operation. - *

- * A page blob's sequence number is updated only if the request meets either of the following conditions: - *

    - *
  • The request sets the sequence number action to max or update, and also specifies a - * value for the sequence number.
  • - *
  • The request sets the sequence number action to increment, indicating that the service should - * increment the sequence number by one.
  • - *
- *

- * A page blob's size is modified only if the request specifies a value for the content length. - *

- * If a request sets only a sequence number and/or content length, and no other properties, then none of the blob's - * other properties are modified. - *

- * If any one or more of the following properties is set in the request, then all of these properties are set - * together. If a value is not provided for a given property when at least one of the properties listed below is - * set, then that property will be cleared for the blob. - *

    - *
  • cache control
  • - *
  • content type
  • - *
  • MD5 hash value
  • - *
  • content encoding
  • - *
  • content language
  • - *
- * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to set properties on. - * @param options - * A {@link SetBlobPropertiesOptions} instance containing options for the request. - * @return - * A {@link SetBlobPropertiesResult} instance containing the ETag and last modified time of the blob, and - * the sequence number, if applicable. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - SetBlobPropertiesResult setBlobProperties(String container, String blob, SetBlobPropertiesOptions options) - throws ServiceException; - - /** - * Sets user-specified metadata on a blob. - *

- * This method sets the metadata specified in the metadata parameter on the blob specified by the - * blob and container parameters. - *

- * Blob metadata is a collection of name-value {@link String} pairs for client use and is opaque to the server. This - * request replaces all existing metadata associated with the blob. To remove all metadata from the blob, make this - * request with an empty metadata list. To replace or append a single metadata name-value pair, get the existing - * blob metadata and replace or append the new item, then make this request with the updated metadata. - *

- * Metadata names must adhere to the naming rules for C# identifiers. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to set metadata on. - * @param metadata - * A {@link HashMap} of key-value pairs of {@link String} containing the blob metadata to set. - * @return - * A {@link SetBlobMetadataResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - SetBlobMetadataResult setBlobMetadata(String container, String blob, HashMap metadata) - throws ServiceException; - - /** - * Sets user-specified metadata on a blob, using the specified options. - *

- * This method sets the metadata specified in the metadata parameter on the blob specified by the - * blob and container parameters. Use the {@link SetBlobMetadataOptions options} parameter to set - * an optional server timeout for the operation, a blob lease ID, and any access conditions for the operation. - *

- * Blob metadata is a collection of name-value {@link String} pairs for client use and is opaque to the server. This - * request replaces all existing metadata associated with the blob. To remove all metadata from the blob, make this - * request with an empty metadata list. To replace or append a single metadata name-value pair, get the existing - * blob metadata and replace or append the new item, then make this request with the updated metadata. - *

- * Metadata names must adhere to the naming rules for C# identifiers. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to set metadata on. - * @param metadata - * A {@link HashMap} of key-value pairs of {@link String} containing the blob metadata to set. - * @param options - * A {@link SetBlobMetadataOptions} instance containing options for the request. - * @return - * A {@link SetBlobMetadataResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - SetBlobMetadataResult setBlobMetadata(String container, String blob, HashMap metadata, - SetBlobMetadataOptions options) throws ServiceException; - - /** - * Gets the properties, metadata, and content of a blob. - *

- * This method gets the properties, metadata, and content of the blob specified by the blob and - * container parameters. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get. - * @return - * A {@link GetBlobResult} instance containing the properties, metadata, and content of the blob from the - * server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetBlobResult getBlob(String container, String blob) throws ServiceException; - - /** - * Gets the properties, metadata, and content of a blob or blob snapshot, using the specified options. - *

- * This method gets the properties, metadata, and content of the blob specified by the blob and - * container parameters. Use the {@link GetBlobOptions options} parameter to set an optional server timeout - * for the operation, a snapshot timestamp to specify a snapshot, a blob lease ID to get a blob with an active - * lease, an optional start and end range for blob content to return, and any access conditions to satisfy. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to get. - * @param options - * A {@link GetBlobOptions} instance containing options for the request. - * @return - * A {@link GetBlobResult} instance containing the properties, metadata, and content of the blob from the - * server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetBlobResult getBlob(String container, String blob, GetBlobOptions options) throws ServiceException; - - /** - * Marks a blob for deletion. - *

- * This method marks the properties, metadata, and content of the blob specified by the blob and - * container parameters for deletion. - *

- * When a blob is successfully deleted, it is immediately removed from the storage account's index and is no longer - * accessible to clients. The blob's data is later removed from the service during garbage collection. - *

- * Note that in order to delete a blob, you must delete all of its snapshots. You can delete an individual snapshot, - * only the snapshots, or both the blob and its snapshots with the - * {@link #deleteBlob(String, String, DeleteBlobOptions)} method. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to delete. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteBlob(String container, String blob) throws ServiceException; - - /** - * Marks a blob or snapshot for deletion, using the specified options. - *

- * This method marks the properties, metadata, and content of the blob or snapshot specified by the blob - * and container parameters for deletion. Use the {@link DeleteBlobOptions options} parameter to set an - * optional server timeout for the operation, a snapshot timestamp to specify an individual snapshot to delete, a - * blob lease ID to delete a blob with an active lease, a flag indicating whether to delete all snapshots but not - * the blob, or both the blob and all snapshots, and any access conditions to satisfy. - *

- * When a blob is successfully deleted, it is immediately removed from the storage account's index and is no longer - * accessible to clients. The blob's data is later removed from the service during garbage collection. - *

- * If the blob has an active lease, the client must specify a valid lease ID in the options parameter in - * order to delete it. - *

- * If a blob has a large number of snapshots, it's possible that the delete blob operation will time out. If this - * happens, the client should retry the request. - * - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to delete. - * @param options - * A {@link DeleteBlobOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteBlob(String container, String blob, DeleteBlobOptions options) throws ServiceException; - - /** - * Creates a read-only snapshot of a blob. - *

- * This method creates a read-only snapshot of the blob specified by the blob and container - * parameters as of the time the server processes the request. The current properties and metadata of the blob are - * copied to the snapshot. The base blob's committed block list is also copied to the snapshot, if the blob is a - * block blob. Any uncommitted blocks are not copied. Once a snapshot has been created, it can be read, copied, or - * deleted, but not modified. - *

- * Use the {@link #createBlobSnapshot(String, String, CreateBlobSnapshotOptions)} overload of this method to make a - * create blob snapshot request of a blob with an active lease, to change the metadata on the snapshot, or to set - * access conditions on the request. - *

- * When you create a snapshot, the Blob service returns a timestamp value that uniquely identifies the snapshot - * relative to its base blob. You can use this value to perform further operations on the snapshot. Any method on a - * blob that is valid for a snapshot can be called by specifying the snapshot timestamp as an option. Note that you - * should treat this timestamp value as opaque. - *

- * A snapshot provides a convenient way to back up blob data. You can use a snapshot to restore a blob to an earlier - * version by calling {@link #copyBlob(String, String, String, String, CopyBlobOptions) copyBlob} to overwrite a - * base blob with its snapshot. The snapshot remains, but the base blob is overwritten with a copy that can be both - * read and written. - *

- * Note that each time you make a create blob snapshot request, a new snapshot is created, with a unique timestamp - * value. A blob can support any number of snapshots. Existing snapshots are never overwritten, but must be deleted - * explicitly with a {@link #deleteBlob(String, String, DeleteBlobOptions) deleteBlob} request. - *

- * Note that a lease associated with the base blob is not copied to the snapshot. Snapshots cannot be leased. - *

- * When a base blob is copied with a {@link #copyBlob(String, String, String, String, CopyBlobOptions) copyBlob} - * request, any snapshots of the base blob are not copied to the destination blob. When a destination blob is - * overwritten with a copy, any snapshots associated with the destination blob stay intact under its name. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to create a snapshot of. - * @return - * A {@link CreateBlobSnapshotResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobSnapshotResult createBlobSnapshot(String container, String blob) throws ServiceException; - - /** - * Creates a read-only snapshot of a blob, using the specified options. - *

- * This method creates a read-only snapshot of the blob specified by the blob and container - * parameters as of the time the server processes the request. Use the {@link CreateBlobSnapshotOptions options} - * parameter to set an optional server timeout for the operation, to make a create blob snapshot request of a blob - * with an active lease, to change the metadata on the snapshot, or to set access conditions on the request. Unless - * overridden in the options parameter, the current properties and metadata of the blob are copied to the - * snapshot. The base blob's committed block list is also copied to the snapshot, if the blob is a block blob. Any - * uncommitted blocks are not copied. Once a snapshot has been created, it can be read, copied, or deleted, but not - * modified. - *

- * When you create a snapshot, the Blob service returns a timestamp value that uniquely identifies the snapshot - * relative to its base blob. You can use this value to perform further operations on the snapshot. Any method on a - * blob that is valid for a snapshot can be called by specifying the snapshot timestamp as an option. Note that you - * should treat this timestamp value as opaque. - *

- * A snapshot provides a convenient way to back up blob data. You can use a snapshot to restore a blob to an earlier - * version by calling {@link #copyBlob(String, String, String, String, CopyBlobOptions) copyBlob} to overwrite a - * base blob with its snapshot. The snapshot remains, but the base blob is overwritten with a copy that can be both - * read and written. - *

- * Note that each time you make a create blob snapshot request, a new snapshot is created, with a unique timestamp - * value. A blob can support any number of snapshots. Existing snapshots are never overwritten, but must be deleted - * explicitly with a {@link #deleteBlob(String, String, DeleteBlobOptions) deleteBlob} request. - *

- * Note that a lease associated with the base blob is not copied to the snapshot. Snapshots cannot be leased. - *

- * When a base blob is copied with a {@link #copyBlob(String, String, String, String, CopyBlobOptions) copyBlob} - * request, any snapshots of the base blob are not copied to the destination blob. When a destination blob is - * overwritten with a copy, any snapshots associated with the destination blob stay intact under its name. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to create a snapshot of. - * @param options - * A {@link CreateBlobSnapshotOptions} instance containing options for the request. - * @return - * A {@link CreateBlobSnapshotResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CreateBlobSnapshotResult createBlobSnapshot(String container, String blob, CreateBlobSnapshotOptions options) - throws ServiceException; - - /** - * Copies a source blob to a destination within the storage account. - *

- * This method creates a copy of the properties, metadata, and content of the blob specified by the - * sourceBlob and sourceContainer in the destination specified by the destinationBlob and - * destinationContainer parameters. The sourceContainer and destinationContainer - * parameters may be empty to specify the root container. The destination may be a new or existing blob. - *

- * Use the {@link #copyBlob(String, String, String, String, CopyBlobOptions)} overload of this method to copy a - * snapshot, modify the metadata of the destination, copy from or to a blob with an active lease, or to set access - * conditions on either the source or the destination blob. - *

- * The source blob for a copy operation may be a block blob or a page blob, or a snapshot of either. If the - * destination blob already exists, it must be of the same blob type as the source blob. - *

- * Copying a source blob always copies the entire blob; copying a range of bytes or a set of blocks is not - * supported. - *

- * A copy blob request can take any of the following forms: - *

    - *
  • You can copy a source blob to a destination blob with a different name from that of the source blob. The - * destination blob can be an existing blob, or a new blob created by the copy operation.
  • - *
  • You can copy a source blob to a destination blob with the same name, effectively replacing the source blob. - * Such a copy operation removes any uncommitted blocks and overwrites the blob's metadata.
  • - *
  • - * You can copy a snapshot over its base blob. By promoting a snapshot to the position of the base blob, you can - * restore an earlier version of a blob.
  • - *
  • - * You can copy a snapshot to a destination blob with a different name. The resulting destination blob is a - * writeable blob and not a snapshot.
  • - *
- *

- * The source blob's committed block list is also copied to the destination blob, if the blob is a block blob. Any - * uncommitted blocks are not copied. - *

- * The destination blob is always the same size as the source blob, so the value of the Content-Length header for - * the destination blob will be the same as that for the source blob. - *

- * When the source blob and destination blob are the same, Copy Blob removes any uncommitted blocks. - *

- * When a source blob is copied, any snapshots of the source blob are not copied to the destination. When a - * destination blob is overwritten with a copy, any snapshots associated with the destination blob stay intact under - * its name. - * - * @param destinationContainer - * A {@link String} containing the name of the destination blob's container. - * @param destinationBlob - * A {@link String} containing the name of the destination blob. - * @param sourceContainer - * A {@link String} containing the name of the source blob's container. - * @param sourceBlob - * A {@link String} containing the name of the source blob. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CopyBlobResult copyBlob(String destinationContainer, String destinationBlob, String sourceContainer, - String sourceBlob) throws ServiceException; - - /** - * Copies a source blob to a destination within the storage account, using the specified options. - *

- * This method creates a copy of the properties, metadata, and content of the blob specified by the - * sourceBlob and sourceContainer in the destination specified by the destinationBlob and - * destinationContainer parameters. The sourceContainer and destinationContainer - * parameters may be empty to specify the root container. The destination may be a new or existing blob. Use the - * {@link CopyBlobOptions options} parameter to set an optional server timeout for the operation, an optional source - * snapshot timestamp value to copy from a particular snapshot of the source blob, new blob metadata to set on the - * destination blob, a blob lease ID to overwrite a blob with an active lease, a source lease ID to copy from a - * source blob with an active lease, any access conditions to satisfy on the destination, and any access conditions - * to satisfy on the source. - *

- * The source blob for a copy operation may be a block blob or a page blob, or a snapshot of either. If the - * destination blob already exists, it must be of the same blob type as the source blob. - *

- * Copying a source blob always copies the entire blob; copying a range of bytes or a set of blocks is not - * supported. - *

- * A copy blob request can take any of the following forms: - *

    - *
  • You can copy a source blob to a destination blob with a different name from that of the source blob. The - * destination blob can be an existing blob, or a new blob created by the copy operation.
  • - *
  • You can copy a source blob to a destination blob with the same name, effectively replacing the source blob. - * Such a copy operation removes any uncommitted blocks and overwrites the blob's metadata.
  • - *
  • You can copy a snapshot over its base blob. By promoting a snapshot to the position of the base blob, you can - * restore an earlier version of a blob.
  • - *
  • You can copy a snapshot to a destination blob with a different name. The resulting destination blob is a - * writeable blob and not a snapshot.
  • - *
- *

- * The source blob's committed block list is also copied to the destination blob, if the blob is a block blob. Any - * uncommitted blocks are not copied. - *

- * The destination blob is always the same size as the source blob, so the value of the Content-Length header for - * the destination blob will be the same as that for the source blob. - *

- * You can specify one or more new metadata values for the destination blob by specifying the metadata in the - * options parameter. If this option is not specified, the metadata associated with the source blob is - * copied to the destination blob. - *

- * When the source blob and destination blob are the same, Copy Blob removes any uncommitted blocks. If metadata is - * specified in this case, the existing metadata is overwritten with the new metadata. - *

- * You can specify access conditions on the request to copy the blob only if a condition is met. If the specified - * conditions are not met, the blob is not copied, and the Blob service returns status code 412 (Precondition - * Failed), which causes a {@link ServiceException} to be thrown. - *

- * If the destination blob has an active lease, you must specify a valid lease ID for the active lease in order to - * copy the blob. - *

- * If the source blob has an active lease, you can optionally specify the lease ID for the source blob to copy the - * source blob conditionally. In this case, the source blob will be copied only if the lease ID for the source blob - * matches that specified on the request. - *

- * Copying a blob does not affect an existing lease on the destination blob. The destination blob's lease is - * maintained, whether you are copying a blob to a destination blob with a different name from the source, copying - * the blob to a destination blob with the same name as the source, or copying a snapshot over its base blob. - *

- * When a source blob is copied, any snapshots of the source blob are not copied to the destination. When a - * destination blob is overwritten with a copy, any snapshots associated with the destination blob stay intact under - * its name. - * - * @param destinationContainer - * A {@link String} containing the name of the destination blob's container. - * @param destinationBlob - * A {@link String} containing the name of the destination blob. - * @param sourceContainer - * A {@link String} containing the name of the source blob's container. - * @param sourceBlob - * A {@link String} containing the name of the source blob. - * @param options - * A {@link CopyBlobOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - CopyBlobResult copyBlob(String destinationContainer, String destinationBlob, String sourceContainer, - String sourceBlob, CopyBlobOptions options) throws ServiceException; - - /** - * Gets a new lease on a blob. - *

- * This method requests a lease on the blob specified by the blob and container parameters. If the - * blob does not have an active lease, the Blob service creates a new one-minute lock for write operations on the - * blob and returns a new lease ID. Any operation that writes to the blob's properties, metadata, or content for the - * duration of the lease must include this lease ID to succeed. You may request a new lease only for a blob without - * an unexpired lease. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to acquire a lease on. - * @return - * An {@link AcquireLeaseResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - AcquireLeaseResult acquireLease(String container, String blob) throws ServiceException; - - /** - * Gets a new lease on a blob, using the specified options. - *

- * This method requests a lease on the blob specified by the blob and container parameters. Use - * the {@link AcquireLeaseOptions options} parameter to set an optional server timeout for the operation and any - * access conditions for the operation. If the blob does not have an active lease, the Blob service creates a new - * one-minute lock for write operations on the blob and returns a new lease ID. Any operation that writes to the - * blob's properties, metadata, or content for the duration of the lease must include this lease ID to succeed. You - * may request a new lease only for a blob without an unexpired lease. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to acquire a lease on. - * @param options - * An {@link AcquireLeaseOptions} instance containing options for the request. - * @return - * An {@link AcquireLeaseResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - AcquireLeaseResult acquireLease(String container, String blob, AcquireLeaseOptions options) throws ServiceException; - - /** - * Renews a lease on a blob. - *

- * This method renews the lease on the blob specified by the blob and container parameters with - * its most recent lease ID specified by the leaseId parameter. Note that the lease may be renewed even if - * it has expired or been released as long as the blob has not been modified since the expiration or release of that - * lease. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to renew a lease on. - * @param leaseId - * A {@link String} containing the lease ID. - * @return - * An {@link AcquireLeaseResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - AcquireLeaseResult renewLease(String container, String blob, String leaseId) throws ServiceException; - - /** - * Renews a lease on a blob, using the specified options. - *

- * This method renews the lease on the blob specified by the blob and container parameters with - * its most recent lease ID specified by the leaseId parameter. Use the {@link BlobServiceOptions options} - * parameter to specify an optional server timeout for the operation. Note that the lease may be renewed even if it - * has expired or been released as long as the blob has not been modified since the expiration or release of that - * lease. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to renew a lease on. - * @param leaseId - * A {@link String} containing the lease ID. - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @return - * An {@link AcquireLeaseResult} instance containing the server response to the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - AcquireLeaseResult renewLease(String container, String blob, String leaseId, BlobServiceOptions options) - throws ServiceException; - - /** - * Releases an active or broken lease on a blob. - *

- * This method releases the lease on the blob specified by the blob and container parameters with - * a broken or active lease ID specified by the leaseId parameter. Releasing the lease allows another - * client to immediately acquire the lease for the blob as soon as the release is complete. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to release a lease on. - * @param leaseId - * A {@link String} containing the lease ID. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void releaseLease(String container, String blob, String leaseId) throws ServiceException; - - /** - * Releases an active or broken lease on a blob, using the specified options. - *

- * This method releases the lease on the blob specified by the blob and container parameters with - * a broken or active lease ID specified by the leaseId parameter. Use the {@link BlobServiceOptions - * options} parameter to specify the server timeout for the operation. Releasing the lease allows another client to - * immediately acquire the lease for the blob as soon as the release is complete. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to release a lease on. - * @param leaseId - * A {@link String} containing the lease ID. - * @param options - * A {@link BlobServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void releaseLease(String container, String blob, String leaseId, BlobServiceOptions options) - throws ServiceException; - - /** - * Breaks an active lease on a blob. - *

- * This method breaks the lease on the blob specified by the blob and container parameters. The - * leaseId parameter is not used by the server. - *

- * Once a lease is broken, it cannot be renewed. Any authorized request can break the lease; the request is not - * required to specify a matching lease ID. When a lease is broken, the remaining time on the lease is allowed to - * elapse, during which time no lease operation may be performed on the blob. - *

- * A lease that has been broken but has not yet expired can also be released, in which case another client may - * immediately acquire a new lease on the blob. - * - * @deprecated Server ignores the leaseId parameter, replaced by {@link #breakLease(String, String)} without - * the useless parameter. - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to break a lease on. - * - * @param leaseId lease id to break. Ignored. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - * - * @return result containing time remaining before a new lease can be acquired - */ - @Deprecated() - void breakLease(String container, String blob, String leaseId) throws ServiceException; - - /** - * Breaks an active lease on a blob, using the specified options. - *

- * This method breaks the lease on the blob specified by the blob and container parameters. The - * leaseId parameter is not used by the server. Use the {@link BlobServiceOptions options} parameter to - * specify the server timeout for the operation. - *

- * Once a lease is broken, it cannot be renewed. Any authorized request can break the lease; the request is not - * required to specify a matching lease ID. When a lease is broken, the remaining time on the lease is allowed to - * elapse, during which time no lease operation may be performed on the blob. - *

- * A lease that has been broken but has not yet expired can also be released, in which case another client may - * immediately acquire a new lease on the blob. - * - * @deprecated Server ignores the leaseId parameter, replaced by - * {@link #breakLease(String, String, com.microsoft.windowsazure.services.blob.models.BlobServiceOptions)} - * without the useless parameter. - * - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to break a lease on. - * @param options - * A {@link com.microsoft.windowsazure.services.blob.models.BlobServiceOptions} instance containing options for the request. - * @param leaseId lease id to break. Ignored. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - * @return result containing time remaining before a new lease can be acquired - */ - @Deprecated() - void breakLease(String container, String blob, String leaseId, BlobServiceOptions options) throws ServiceException; - - /** - * Breaks an active lease on a blob. - *

- * This method breaks the lease on the blob specified by the blob and container parameters. The - * leaseId parameter is not used by the server. - *

- * Once a lease is broken, it cannot be renewed. Any authorized request can break the lease; the request is not - * required to specify a matching lease ID. When a lease is broken, the remaining time on the lease is allowed to - * elapse, during which time no lease operation may be performed on the blob. - *

- * A lease that has been broken but has not yet expired can also be released, in which case another client may - * immediately acquire a new lease on the blob. - * - * - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to break a lease on. - * @throws ServiceException - * if an error occurs accessing the storage service. - * - * @return result containing time remaining before a new lease can be acquired - */ - BreakLeaseResult breakLease(String container, String blob) throws ServiceException; - - /** - * Breaks an active lease on a blob, using the specified options. - *

- * This method breaks the lease on the blob specified by the blob and container parameters. The - * leaseId parameter is not used by the server. Use the {@link BlobServiceOptions options} parameter to - * specify the server timeout for the operation. - *

- * Once a lease is broken, it cannot be renewed. Any authorized request can break the lease; the request is not - * required to specify a matching lease ID. When a lease is broken, the remaining time on the lease is allowed to - * elapse, during which time no lease operation may be performed on the blob. - *

- * A lease that has been broken but has not yet expired can also be released, in which case another client may - * immediately acquire a new lease on the blob. - * - * - * - * @param container - * A {@link String} containing the name of the blob's container. - * @param blob - * A {@link String} containing the name of the blob to break a lease on. - * @param options - * A {@link com.microsoft.windowsazure.services.blob.models.BlobServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - * @return result containing time remaining before a new lease can be acquired - */ - BreakLeaseResult breakLease(String container, String blob, BlobServiceOptions options) throws ServiceException; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobService.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobService.java deleted file mode 100644 index f09cb8e888da5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/BlobService.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob; - -import com.microsoft.windowsazure.services.core.Configuration; - -/** - * A class for static factory methods that return instances implementing {@link BlobContract}. - */ -public class BlobService { - private BlobService() { - } - - /** - * A static factory method that returns an instance implementing {@link BlobContract} using default values for - * initializing a {@link Configuration} instance. Note that the returned interface will not work unless storage - * account credentials have been added to the "META-INF/com.microsoft.windowsazure.properties" resource file. - * - * @return - * An instance implementing {@link BlobContract} for interacting with the blob service. - */ - public static BlobContract create() { - return create(null, Configuration.getInstance()); - } - - /** - * A static factory method that returns an instance implementing {@link BlobContract} using the specified - * {@link Configuration} instance. The {@link Configuration} instance must have storage account information and - * credentials set before this method is called for the returned interface to work. - * - * @param config - * A {@link Configuration} instance configured with storage account information and credentials. - * - * @return - * An instance implementing {@link BlobContract} for interacting with the blob service. - */ - public static BlobContract create(Configuration config) { - return create(null, config); - } - - /** - * A static factory method that returns an instance implementing {@link BlobContract} using default values for - * initializing a {@link Configuration} instance, and using the specified profile prefix for service settings. Note - * that the returned interface will not work unless storage account settings and credentials have been added to the - * "META-INF/com.microsoft.windowsazure.properties" resource file with the specified profile prefix. - * - * @param profile - * A string prefix for the account name and credentials settings in the {@link Configuration} instance. - * @return - * An instance implementing {@link BlobContract} for interacting with the blob service. - */ - public static BlobContract create(String profile) { - return create(profile, Configuration.getInstance()); - } - - /** - * A static factory method that returns an instance implementing {@link BlobContract} using the specified - * {@link Configuration} instance and profile prefix for service settings. The {@link Configuration} instance must - * have storage account information and credentials set with the specified profile prefix before this method is - * called for the returned interface to work. - * - * @param profile - * A string prefix for the account name and credentials settings in the {@link Configuration} instance. - * @param config - * A {@link Configuration} instance configured with storage account information and credentials. - * - * @return - * An instance implementing {@link BlobContract} for interacting with the blob service. - */ - public static BlobContract create(String profile, Configuration config) { - return config.create(profile, BlobContract.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/Exports.java deleted file mode 100644 index d4a5a7269bd65..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/Exports.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob; - -import com.microsoft.windowsazure.services.blob.implementation.BlobExceptionProcessor; -import com.microsoft.windowsazure.services.blob.implementation.BlobRestProxy; -import com.microsoft.windowsazure.services.blob.implementation.SharedKeyFilter; -import com.microsoft.windowsazure.services.blob.implementation.SharedKeyLiteFilter; -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.ISO8601DateConverter; -import com.microsoft.windowsazure.services.core.UserAgentFilter; - -public class Exports implements Builder.Exports { - @Override - public void register(Builder.Registry registry) { - registry.add(BlobContract.class, BlobExceptionProcessor.class); - registry.add(BlobExceptionProcessor.class); - registry.add(BlobRestProxy.class); - registry.add(SharedKeyLiteFilter.class); - registry.add(SharedKeyFilter.class); - registry.add(ISO8601DateConverter.class); - registry.add(UserAgentFilter.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobAccessPolicyResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobAccessPolicyResponse.java deleted file mode 100644 index a4bccf20ddb4c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobAccessPolicyResponse.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.InputStream; -import java.text.ParseException; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.AccessPolicyResponseBase; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse SharedAccessPolicies from an input stream. - */ -final class BlobAccessPolicyResponse extends AccessPolicyResponseBase { - - /** - * Initializes the AccessPolicyResponse object - * - * @param stream - * the input stream to read error details from. - */ - public BlobAccessPolicyResponse(final InputStream stream) { - super(stream); - } - - /** - * Populates the object from the XMLStreamReader, reader must be at Start element of AccessPolicy. - * - * @param xmlr - * the XMLStreamReader object - * @throws XMLStreamException - * if there is a parsing exception - * @throws ParseException - * if a date value is not correctly encoded - */ - @Override - protected SharedAccessBlobPolicy readPolicyFromXML(final XMLStreamReader xmlr) throws XMLStreamException, - ParseException { - int eventType = xmlr.getEventType(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.ACCESS_POLICY); - final SharedAccessBlobPolicy retPolicy = new SharedAccessBlobPolicy(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.PERMISSION)) { - retPolicy.setPermissions(SharedAccessBlobPolicy.permissionsFromString(Utility - .readElementFromXMLReader(xmlr, Constants.PERMISSION))); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.START)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.START); - retPolicy.setSharedAccessStartTime(Utility.parseISO8061LongDateFromString(tempString)); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.EXPIRY)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.EXPIRY); - retPolicy.setSharedAccessExpiryTime(Utility.parseISO8061LongDateFromString(tempString)); - } - else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(Constants.ACCESS_POLICY)) { - break; - } - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.ACCESS_POLICY); - return retPolicy; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobAttributes.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobAttributes.java deleted file mode 100644 index 0fd33658c8627..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobAttributes.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.URI; -import java.util.HashMap; - -/** - * RESERVED FOR INTERNAL USE. Represents a blob's attributes. - * - */ -final class BlobAttributes { - - /** - * Holds the metadata for the blob. - */ - private HashMap metadata; - - /** - * Represents the state of the most recent or pending copy operation. - */ - private CopyState copyState; - - /** - * Holds the properties of the blob. - */ - private BlobProperties properties; - - /** - * Holds the snapshot ID - */ - public String snapshotID; - - /** - * Holds the URI of the blob. RESERVED for internal use. - */ - protected URI uri; - - /** - * Initializes a new instance of the BlobAttributes class. RESERVED FOR INTERNAL USE. - * - * @param type - * The type of blob to set. - */ - public BlobAttributes(final BlobType type) { - this.setMetadata(new HashMap()); - this.setProperties(new BlobProperties(type)); - } - - /** - * Gets the metadata for the blob. RESERVED FOR INTERNAL USE. - * - * @return A HashMap object containing the metadata for the blob. - */ - public HashMap getMetadata() { - return this.metadata; - } - - /** - * Gets the copy state of the blob. RESERVED FOR INTERNAL USE. - * - * @return A CopyState object representing the copy state. - */ - public CopyState getCopyState() { - return this.copyState; - } - - /** - * Gets the properties for the blob. RESERVED FOR INTERNAL USE. - * - * @return A BlobProperties object that represents the blob properties. - */ - public BlobProperties getProperties() { - return this.properties; - } - - /** - * Sets the metadata for a blob. RESERVED FOR INTERNAL USE. - * - * @param metadata - * The blob meta data to set. - */ - protected void setMetadata(final HashMap metadata) { - this.metadata = metadata; - } - - /** - * Sets the properties for a blob. RESERVED FOR INTERNAL USE. - * - * @param properties - * The blob properties to set. - */ - protected void setProperties(final BlobProperties properties) { - this.properties = properties; - } - - /** - * Sets the copy state for a blob. RESERVED FOR INTERNAL USE. - * - * @param copyState - * The blob copy state to set. - */ - public void setCopyState(final CopyState copyState) { - this.copyState = copyState; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobConstants.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobConstants.java deleted file mode 100644 index 0c56cc1f93775..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobConstants.java +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Holds the Constants used for the Queue Service. - */ -final class BlobConstants { - /** - * XML element for authentication error details. - */ - public static final String AUTHENTICATION_ERROR_DETAIL = "AuthenticationErrorDetail"; - - /** - * The header that specifies blob content MD5. - */ - public static final String BLOB_CONTENT_MD5_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-content-md5"; - - /** - * XML element for a blob. - */ - public static final String BLOB_ELEMENT = "Blob"; - - /** - * XML element for blob prefixes. - */ - public static final String BLOB_PREFIX_ELEMENT = "BlobPrefix"; - - /** - * The header that specifies public access to blobs. - */ - public static final String BLOB_PUBLIC_ACCESS_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-public-access"; - - /** - * XML element for a blob type. - */ - public static final String BLOB_TYPE_ELEMENT = "BlobType"; - /** - * The header for the blob type. - */ - public static final String BLOB_TYPE_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-type"; - - /** - * XML element for blobs. - */ - public static final String BLOBS_ELEMENT = "Blobs"; - - /** - * Specifies the block blob type. - */ - public static final String BLOCK_BLOB = "BlockBlob"; - - /** - * Constant signaling a block blob. - */ - public static final String BLOCK_BLOB_VALUE = "BlockBlob"; - - /** - * XML element for blocks. - */ - public static final String BLOCK_ELEMENT = "Block"; - - /** - * XML element for a block list. - */ - public static final String BLOCK_LIST_ELEMENT = "BlockList"; - - /** - * XML element for committed blocks. - */ - public static final String COMMITTED_BLOCKS_ELEMENT = "CommittedBlocks"; - - /** - * XML element for committed blocks. - */ - public static final String COMMITTED_ELEMENT = "Committed"; - - /** - * XML element for a container. - */ - public static final String CONTAINER_ELEMENT = "Container"; - - /** - * XML element for containers. - */ - public static final String CONTAINERS_ELEMENT = "Containers"; - - /** - * The header that specifies blob content encoding. - */ - public static final String CONTENT_ENCODING_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-content-encoding"; - - /** - * The header that specifies blob content language. - */ - public static final String CONTENT_LANGUAGE_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-content-language"; - - /** - * The header that specifies blob content length. - */ - public static final String CONTENT_LENGTH_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-content-length"; - - /** - * The header that specifies blob content type. - */ - public static final String CONTENT_TYPE_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-content-type"; - - /** - * The number of default concurrent requests for parallel operation. - */ - public static final int DEFAULT_CONCURRENT_REQUEST_COUNT = 1; - - /** - * The default delimiter used to create a virtual directory structure of blobs. - */ - public static final String DEFAULT_DELIMITER = "/"; - - /** - * The default write pages size, in bytes, used by blob stream for page blobs. - */ - public static final int DEFAULT_MINIMUM_PAGE_STREAM_WRITE_IN_BYTES = 4 * com.microsoft.windowsazure.services.core.storage.Constants.MB; - - /** - * The default minimum read size, in bytes, for streams. - */ - public static final int DEFAULT_MINIMUM_READ_SIZE_IN_BYTES = 4 * com.microsoft.windowsazure.services.core.storage.Constants.MB; - - /** - * The default maximum size, in bytes, of a blob before it must be separated into blocks. - */ - public static final int DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES = 32 * com.microsoft.windowsazure.services.core.storage.Constants.MB; - - /** - * The default write block size, in bytes, used by blob streams. - */ - public static final int DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES = 4 * com.microsoft.windowsazure.services.core.storage.Constants.MB; - - /** - * Specifies snapshots are to be included. - */ - public static final String INCLUDE_SNAPSHOTS_VALUE = "include"; - - /** - * XML element for the latest. - */ - public static final String LATEST_ELEMENT = "Latest"; - - /** - * The maximum size, in bytes, of a blob before it must be separated into blocks - */ - // Note if this is updated then Constants.MAX_MARK_LENGTH needs to be as well. - public static final int MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES = 64 * com.microsoft.windowsazure.services.core.storage.Constants.MB; - - /** - * Specifies the page blob type. - */ - public static final String PAGE_BLOB = "PageBlob"; - - /** - * Constant signaling a page blob. - */ - public static final String PAGE_BLOB_VALUE = "PageBlob"; - - /** - * XML element for page list elements. - */ - public static final String PAGE_LIST_ELEMENT = "PageList"; - - /** - * XML element for a page range. - */ - public static final String PAGE_RANGE_ELEMENT = "PageRange"; - - /** - * The size of a page, in bytes, in a page blob. - */ - public static final int PAGE_SIZE = 512; - - /** - * The header that specifies page write mode. - */ - public static final String PAGE_WRITE = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "page-write"; - - /** - * XML element for properties. - */ - public static final String PROPERTIES = "Properties"; - - /** - * The header for specifying the sequence number. - */ - public static final String SEQUENCE_NUMBER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-sequence-number"; - - /** - * The header for the blob content length. - */ - public static final String SIZE = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "blob-content-length"; - - /** - * XML element for the block length. - */ - public static final String SIZE_ELEMENT = "Size"; - - /** - * The Snapshot value. - */ - public static final String SNAPSHOT = "snapshot"; - - /** - * XML element for a snapshot. - */ - public static final String SNAPSHOT_ELEMENT = "Snapshot"; - - /** - * The header for snapshots. - */ - public static final String SNAPSHOT_HEADER = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "snapshot"; - - /** - * Specifies only snapshots are to be included. - */ - public static final String SNAPSHOTS_ONLY_VALUE = "only"; - - /** - * XML element for page range start elements. - */ - public static final String START_ELEMENT = "Start"; - - /** - * XML element for uncommitted blocks. - */ - public static final String UNCOMMITTED_BLOCKS_ELEMENT = "UncommittedBlocks"; - - /** - * XML element for uncommitted blocks. - */ - public static final String UNCOMMITTED_ELEMENT = "Uncommitted"; - - /** - * The default timeout of a copy operation. - */ - public static final int DEFAULT_COPY_TIMEOUT_IN_SECONDS = 3600; - - /** - * The default polling interval of a copy operation. - */ - public static final int DEFAULT_POLLING_INTERVAL_IN_SECONDS = 30; - - /** - * Private Default Ctor - */ - private BlobConstants() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerAttributes.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerAttributes.java deleted file mode 100644 index fb6481bee0019..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerAttributes.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.URI; -import java.util.HashMap; - -/** - * RESERVED FOR INTERNAL USE. Represents a container's attributes, including its properties and metadata. - * - */ -final class BlobContainerAttributes { - /** - * Holds the Container Metadata - */ - private HashMap metadata; - - /** - * Holds the Container Properties - */ - private BlobContainerProperties properties; - - /** - * Holds the Name of the Container - */ - private String name; - - /** - * Holds the URI of the container - */ - private URI uri; - - /** - * Initializes a new instance of the BlobContainerAttributes class - */ - public BlobContainerAttributes() { - this.setMetadata(new HashMap()); - this.setProperties(new BlobContainerProperties()); - } - - public HashMap getMetadata() { - return this.metadata; - } - - public String getName() { - return this.name; - } - - public BlobContainerProperties getProperties() { - return this.properties; - } - - public URI getUri() { - return this.uri; - } - - public void setMetadata(final HashMap metadata) { - this.metadata = metadata; - } - - public void setName(final String name) { - this.name = name; - } - - public void setProperties(final BlobContainerProperties properties) { - this.properties = properties; - } - - public void setUri(final URI uri) { - this.uri = uri; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerPermissions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerPermissions.java deleted file mode 100644 index 3838342e0873b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerPermissions.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.HashMap; - -/** - * Represents the permissions for a container. - *

- * The container's permissions encompass two types of access settings for the container: - *

    - *
  • The container's public access setting, represented by the {@link #publicAccess} property. The public access - * setting indicates whether the container and its blobs can be read via an anonymous request.
  • - *
  • The container's access policies, represented by the {@link #getSharedAccessPolicies} method. This setting - * references a collection of shared access policies for the container. A shared access policy may be used to control - * the start time, expiry time, and permissions for one or more shared access signatures. A shared access signature - * provides delegated access to the container's resources.
  • - *
- * For more information on managing container permissions, see Managing Access to Containers and Blobs. - * - */ -public final class BlobContainerPermissions { - - /** - * Represents the public access setting for the container. - *

- * The public access setting indicates whether the container and its blobs can be read via an anonymous request. - *

- * The {@link BlobContainerPublicAccessType} enumeration provides three levels of anonymous read access: - *

    - *
  • {@link BlobContainerPublicAccessType#OFF}, which prevents anonymous access.
  • - *
  • {@link BlobContainerPublicAccessType#BLOB}, which permits anonymous read access to blob resources, but not to - * container metadata or to the list of blobs in the container.
  • - *
  • {@link BlobContainerPublicAccessType#CONTAINER}, which permits anonymous read access to blob resources, - * container metadata, and the list of blobs in the container.
  • - *
- * For more information on managing anonymous access to Blob service resources, see Setting Access Control for Containers. - */ - private BlobContainerPublicAccessType publicAccess; - - /** - * Gets the set of shared access policies for the container. - */ - private HashMap sharedAccessPolicies; - - /** - * Creates an instance of the BlobContainerPermissions class. - */ - public BlobContainerPermissions() { - this.setPublicAccess(BlobContainerPublicAccessType.OFF); - this.sharedAccessPolicies = new HashMap(); - } - - /** - * @return the publicAccess - */ - public BlobContainerPublicAccessType getPublicAccess() { - return this.publicAccess; - } - - /** - * Returns the set of shared access policies for the container. - * - * @return A HashMap object of {@link SharedAccessBlobPolicy} objects that represent the set of shared - * access policies for the container. - */ - public HashMap getSharedAccessPolicies() { - return this.sharedAccessPolicies; - } - - /** - * @param publicAccess - * the publicAccess to set - */ - public void setPublicAccess(final BlobContainerPublicAccessType publicAccess) { - this.publicAccess = publicAccess; - } - - /** - * @param sharedAccessPolicies - * the sharedAccessPolicies to set - */ - public void setSharedAccessPolicies(final HashMap sharedAccessPolicies) { - this.sharedAccessPolicies = sharedAccessPolicies; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerProperties.java deleted file mode 100644 index 516183818f699..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerProperties.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.Date; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.LeaseDuration; -import com.microsoft.windowsazure.services.core.storage.LeaseState; -import com.microsoft.windowsazure.services.core.storage.LeaseStatus; - -/** - * Represents the system properties for a container. - */ -public final class BlobContainerProperties { - - /** - * Represents the ETag value for the container. - *

- * The ETag value is a unique identifier that is updated when a write operation is performed against the container. - * It may be used to perform operations conditionally, providing concurrency control and improved efficiency. - *

- * The {@link AccessCondition#ifMatch} and {@link AccessCondition#ifNoneMatch} methods take an ETag value and return - * an {@link AccessCondition} object that may be specified on the request. - */ - private String etag; - - /** - * Represents the container's last-modified time. - */ - private Date lastModified; - - /** - * Represents the container's lease status. - */ - private LeaseStatus leaseStatus; - - /** - * Represents the container's lease state. - */ - private LeaseState leaseState; - - /** - * Represents the container's lease duration. - */ - private LeaseDuration leaseDuration; - - /** - * @return the etag - */ - public String getEtag() { - return this.etag; - } - - /** - * @return the lastModified - */ - public Date getLastModified() { - return this.lastModified; - } - - /** - * Gets the lease status of the container. - * - * @return The lease status as a LeaseStatus object. - */ - public LeaseStatus getLeaseStatus() { - return this.leaseStatus; - } - - /** - * Gets the lease state of the container. - * - * @return The lease state as a LeaseState object. - */ - public LeaseState getLeaseState() { - return this.leaseState; - } - - /** - * Gets the lease duration of the container. - * - * @return The lease duration as a LeaseDuration object. - */ - public LeaseDuration getLeaseDuration() { - return this.leaseDuration; - } - - /** - * Sets the ETag value on the container. - * - * @param etag - * The ETag value to set, as a string. - */ - public void setEtag(final String etag) { - this.etag = etag; - } - - /** - * Sets the last modified time on the container. - * - * @param lastModified - * The last modified time to set, as a Date object. - */ - public void setLastModified(final Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Sets the lease status on the container. Reserved for internal use. - * - * @param leaseStatus - * The lease status to set, as a LeaseStatus object. - */ - public void setLeaseStatus(final LeaseStatus leaseStatus) { - this.leaseStatus = leaseStatus; - } - - /** - * Sets the lease status on the container. Reserved for internal use. - * - * @param leaseState - * The lease state to set, as a LeaseState object. - */ - public void setLeaseState(final LeaseState leaseState) { - this.leaseState = leaseState; - } - - /** - * Sets the lease duration on the container. Reserved for internal use. - * - * @param leaseDuration - * The lease duration to set, as a LeaseDuration object. - */ - public void setLeaseDuration(final LeaseDuration leaseDuration) { - this.leaseDuration = leaseDuration; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerPublicAccessType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerPublicAccessType.java deleted file mode 100644 index 51c6cdcbafad7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobContainerPublicAccessType.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Specifies the level of public access that is allowed on the container. - * - */ -public enum BlobContainerPublicAccessType { - /** - * Specifies blob-level public access. Clients can read the content and metadata of blobs within this container, but - * cannot read container metadata or list the blobs within the container. - */ - BLOB, - - /** - * Specifies container-level public access. Clients can read blob content and metadata and container metadata, and - * can list the blobs within the container. - **/ - CONTAINER, - - /** - * Specifies no public access. Only the account owner can access resources in this container. - */ - OFF -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobDeserializationHelper.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobDeserializationHelper.java deleted file mode 100644 index 290d529b6a21c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobDeserializationHelper.java +++ /dev/null @@ -1,676 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.LeaseDuration; -import com.microsoft.windowsazure.services.core.storage.LeaseState; -import com.microsoft.windowsazure.services.core.storage.LeaseStatus; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.DeserializationHelper; - -/** - * RESERVED FOR INTERNAL USE. Class to provide object deserialization for blobs and containers. - */ -final class BlobDeserializationHelper { - /** - * Reserved for internal use. Populates the blob from an XMLStreamReader, reader must be at Start element of Blob - * - * @param xmlr - * the XMLStreamReader to read from - * @param serviceClient - * the CloudBlobClient associated with the objects. - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - * @throws StorageException - */ - protected static CloudBlob readBlob(final XMLStreamReader xmlr, final CloudBlobClient serviceClient, - final CloudBlobContainer container) throws XMLStreamException, ParseException, URISyntaxException, - StorageException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.BLOB_ELEMENT); - - String blobName = Constants.EMPTY_STRING; - - String snapshotID = null; - String urlString = null; - HashMap metadata = null; - BlobProperties properties = null; - CopyState copyState = null; - - int eventType = xmlr.getEventType(); - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(Constants.URL_ELEMENT)) { - urlString = Utility.readElementFromXMLReader(xmlr, Constants.URL_ELEMENT); - } - else if (name.equals(BlobConstants.SNAPSHOT_ELEMENT)) { - snapshotID = Utility.readElementFromXMLReader(xmlr, BlobConstants.SNAPSHOT_ELEMENT); - } - else if (name.equals(Constants.NAME_ELEMENT)) { - blobName = Utility.readElementFromXMLReader(xmlr, Constants.NAME_ELEMENT); - } - else if (name.equals(BlobConstants.PROPERTIES)) { - properties = BlobDeserializationHelper.readBlobProperties(xmlr); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.PROPERTIES); - } - else if (name.equals(Constants.METADATA_ELEMENT)) { - metadata = DeserializationHelper.parseMetadateFromXML(xmlr); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.METADATA_ELEMENT); - } - else if (name.equals(Constants.COPY_ID_ELEMENT)) { - if (copyState == null) { - copyState = new CopyState(); - } - copyState.setCopyId(Utility.readElementFromXMLReader(xmlr, Constants.COPY_ID_ELEMENT)); - } - else if (name.equals(Constants.COPY_COMPLETION_TIME_ELEMENT)) { - if (copyState == null) { - copyState = new CopyState(); - } - copyState.setCompletionTime(Utility.parseRFC1123DateFromStringInGMT(Utility - .readElementFromXMLReader(xmlr, Constants.COPY_COMPLETION_TIME_ELEMENT))); - } - else if (name.equals(Constants.COPY_STATUS_ELEMENT)) { - if (copyState == null) { - copyState = new CopyState(); - } - copyState.setStatus(CopyStatus.parse(Utility.readElementFromXMLReader(xmlr, - Constants.COPY_STATUS_ELEMENT))); - } - else if (name.equals(Constants.COPY_SOURCE_ELEMENT)) { - if (copyState == null) { - copyState = new CopyState(); - } - copyState.setSource(new URI(Utility.readElementFromXMLReader(xmlr, Constants.COPY_SOURCE_ELEMENT))); - } - else if (name.equals(Constants.COPY_PROGRESS_ELEMENT)) { - if (copyState == null) { - copyState = new CopyState(); - } - - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.COPY_PROGRESS_ELEMENT); - String[] progressSequence = tempString.split("/"); - copyState.setBytesCopied(Long.parseLong(progressSequence[0])); - copyState.setTotalBytes(Long.parseLong(progressSequence[1])); - } - else if (name.equals(Constants.COPY_STATUS_DESCRIPTION_ELEMENT)) { - if (copyState == null) { - copyState = new CopyState(); - } - copyState.setStatusDescription(Utility.readElementFromXMLReader(xmlr, - Constants.COPY_STATUS_DESCRIPTION_ELEMENT)); - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(BlobConstants.BLOB_ELEMENT)) { - break; - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.BLOB_ELEMENT); - - // Assemble and return - if (properties != null) { - CloudBlob retBlob = null; - final int blobNameSectionIndex = urlString.lastIndexOf("/".concat(blobName)); - final URI baseUri = new URI(urlString.substring(0, blobNameSectionIndex + 1)); - String query = null; - if (blobNameSectionIndex + 1 + blobName.length() < urlString.length()) { - // Snapshot blob URI - // example:http://.blob.core.windows.net//?snapshot=2009-12-03T15%3a26%3a19.4466877Z - query = urlString.substring(blobNameSectionIndex + blobName.length() + 1); - } - - final URI blobURI = new URI(baseUri.getScheme(), baseUri.getAuthority(), baseUri.getRawPath().concat( - blobName), query, null); - - if (properties.getBlobType() == BlobType.BLOCK_BLOB) { - retBlob = new CloudBlockBlob(blobURI, serviceClient, container); - } - else if (properties.getBlobType() == BlobType.PAGE_BLOB) { - retBlob = new CloudPageBlob(blobURI, serviceClient, container); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - retBlob.uri = blobURI; - retBlob.snapshotID = snapshotID; - retBlob.properties = properties; - retBlob.metadata = metadata; - retBlob.copyState = copyState; - return retBlob; - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - - /** - * Reads BlobItems from the XMLStreamReader, reader must be at Start element of BlobsElement - * - * @param xmlr - * the XMLStreamReader to read from - * @param searchMode - * the block search mode - * @return BlockEntry from the stream. - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - * @throws StorageException - */ - public static ArrayList readBlobBlocks(final XMLStreamReader xmlr, final BlockSearchMode searchMode) - throws XMLStreamException, StorageException { - int eventType = xmlr.getEventType(); - final ArrayList retBlocks = new ArrayList(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.BLOCK_ELEMENT); - - // check if there are more events in the input stream - while (xmlr.hasNext() && BlobConstants.BLOCK_ELEMENT.equals(xmlr.getName().toString())) { - String blockName = null; - long blockSize = -1; - - // Read a block - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(Constants.NAME_ELEMENT)) { - blockName = Utility.readElementFromXMLReader(xmlr, Constants.NAME_ELEMENT); - } - else if (name.equals(BlobConstants.SIZE_ELEMENT)) { - final String sizeString = Utility.readElementFromXMLReader(xmlr, BlobConstants.SIZE_ELEMENT); - blockSize = Long.parseLong(sizeString); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT) { - final BlockEntry newBlock = new BlockEntry(blockName, searchMode); - newBlock.setSize(blockSize); - retBlocks.add(newBlock); - break; - } - } - - eventType = xmlr.next(); - } - - return retBlocks; - } - - /** - * Populates the object from the XMLStreamReader - * - * @param xmlr - * the XMLStreamReader to read from - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - */ - protected static BlobContainerAttributes readBlobContainerAttributes(final XMLStreamReader xmlr) - throws XMLStreamException, ParseException, URISyntaxException { - int eventType = xmlr.getEventType(); - - final BlobContainerAttributes attributes = new BlobContainerAttributes(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(BlobConstants.PROPERTIES)) { - attributes.setProperties(BlobDeserializationHelper.readBlobContainerProperties(xmlr)); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.PROPERTIES); - } - else if (name.equals(Constants.URL_ELEMENT)) { - attributes.setUri(new URI(Utility.readElementFromXMLReader(xmlr, Constants.URL_ELEMENT))); - } - else if (name.equals(Constants.NAME_ELEMENT)) { - attributes.setName(Utility.readElementFromXMLReader(xmlr, Constants.NAME_ELEMENT)); - } - else if (name.equals(Constants.METADATA_ELEMENT)) { - // parse metadata - attributes.setMetadata(DeserializationHelper.parseMetadateFromXML(xmlr)); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.METADATA_ELEMENT); - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(BlobConstants.CONTAINER_ELEMENT)) { - break; - } - } - - return attributes; - } - - /** - * Populates the object from the XMLStreamReader, reader must be at Start element of Properties - * - * @param xmlr - * the XMLStreamReader object - * @throws XMLStreamException - * if there is a parsing exception - * @throws ParseException - * if a date value is not correctly encoded - */ - protected static BlobContainerProperties readBlobContainerProperties(final XMLStreamReader xmlr) - throws XMLStreamException, ParseException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.PROPERTIES); - int eventType = xmlr.getEventType(); - final BlobContainerProperties properties = new BlobContainerProperties(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(Constants.LAST_MODIFIED_ELEMENT)) { - properties.setLastModified(Utility.parseRFC1123DateFromStringInGMT(Utility - .readElementFromXMLReader(xmlr, Constants.LAST_MODIFIED_ELEMENT))); - } - else if (name.equals(Constants.ETAG_ELEMENT)) { - properties.setEtag(Utility.readElementFromXMLReader(xmlr, Constants.ETAG_ELEMENT)); - } - else if (name.equals(Constants.LEASE_STATUS_ELEMENT)) { - properties.setLeaseStatus(LeaseStatus.parse(Utility.readElementFromXMLReader(xmlr, - Constants.LEASE_STATUS_ELEMENT))); - } - else if (name.equals(Constants.LEASE_STATE_ELEMENT)) { - properties.setLeaseState(LeaseState.parse(Utility.readElementFromXMLReader(xmlr, - Constants.LEASE_STATE_ELEMENT))); - } - else if (name.equals(Constants.LEASE_DURATION_ELEMENT)) { - properties.setLeaseDuration(LeaseDuration.parse(Utility.readElementFromXMLReader(xmlr, - Constants.LEASE_DURATION_ELEMENT))); - } - } - else { - // expect end of properties - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.PROPERTIES); - break; - } - } - - return properties; - } - - /** - * Reads BlobItems from the XMLStreamReader, reader must be at Start element of BlobsElement - * - * @param xmlr - * the XMLStreamReader to read from - * @param serviceClient - * the CloudBlobClient associated with the objects. - * @param container - * the container associated with the objects. - * @return the BlobItems from the stream - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - * @throws StorageException - */ - public static ArrayList readBlobItems(final XMLStreamReader xmlr, - final CloudBlobClient serviceClient, final CloudBlobContainer container) throws XMLStreamException, - ParseException, URISyntaxException, StorageException { - int eventType = xmlr.getEventType(); - final ArrayList retBlobs = new ArrayList(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.BLOBS_ELEMENT); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(BlobConstants.BLOB_ELEMENT)) { - retBlobs.add(BlobDeserializationHelper.readBlob(xmlr, serviceClient, container)); - } - else if (name.equals(BlobConstants.BLOB_PREFIX_ELEMENT)) { - retBlobs.add(BlobDeserializationHelper.readDirectory(xmlr, serviceClient, container)); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else { - break; - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.BLOBS_ELEMENT); - return retBlobs; - } - - /** - * Populates the object from the XMLStreamReader, reader must be at Start element of Properties - * - * @param xmlr - * the XMLStreamReader object - * @return the BlobProperties that was read. - * @throws XMLStreamException - * if there is a parsing exception - * @throws ParseException - * if a date value is not correctly encoded - * @throws StorageException - * @throws URISyntaxException - */ - protected static BlobProperties readBlobProperties(final XMLStreamReader xmlr) throws XMLStreamException, - ParseException, StorageException, URISyntaxException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.PROPERTIES); - int eventType = xmlr.getEventType(); - final BlobProperties properties = new BlobProperties(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(Constants.LAST_MODIFIED_ELEMENT)) { - properties.setLastModified(Utility.parseRFC1123DateFromStringInGMT(Utility - .readElementFromXMLReader(xmlr, Constants.LAST_MODIFIED_ELEMENT))); - } - else if (name.equals(Constants.ETAG_ELEMENT)) { - properties.setEtag(Utility.readElementFromXMLReader(xmlr, Constants.ETAG_ELEMENT)); - } - else if (name.equals(Constants.HeaderConstants.CONTENT_LENGTH)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, - Constants.HeaderConstants.CONTENT_LENGTH); - properties.setLength(Long.parseLong(tempString)); - } - else if (name.equals(Constants.HeaderConstants.CONTENT_TYPE)) { - properties.setContentType(Utility.readElementFromXMLReader(xmlr, - Constants.HeaderConstants.CONTENT_TYPE)); - } - else if (name.equals(Constants.HeaderConstants.CONTENT_ENCODING)) { - properties.setContentEncoding(Utility.readElementFromXMLReader(xmlr, - Constants.HeaderConstants.CONTENT_ENCODING)); - } - else if (name.equals(Constants.HeaderConstants.CONTENT_LANGUAGE)) { - properties.setContentLanguage(Utility.readElementFromXMLReader(xmlr, - Constants.HeaderConstants.CONTENT_LANGUAGE)); - } - else if (name.equals(Constants.HeaderConstants.CONTENT_MD5)) { - properties.setContentMD5(Utility.readElementFromXMLReader(xmlr, - Constants.HeaderConstants.CONTENT_MD5)); - } - else if (name.equals(Constants.HeaderConstants.CACHE_CONTROL)) { - properties.setCacheControl(Utility.readElementFromXMLReader(xmlr, - Constants.HeaderConstants.CACHE_CONTROL)); - } - else if (name.equals(Constants.HeaderConstants.CACHE_CONTROL)) { - properties.setCacheControl(Utility.readElementFromXMLReader(xmlr, - Constants.HeaderConstants.CACHE_CONTROL)); - } - else if (name.equals(BlobConstants.SEQUENCE_NUMBER)) { - Utility.readElementFromXMLReader(xmlr, BlobConstants.SEQUENCE_NUMBER); - } - else if (name.equals(BlobConstants.BLOB_TYPE_ELEMENT)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, BlobConstants.BLOB_TYPE_ELEMENT); - if (tempString.equals(BlobConstants.BLOCK_BLOB_VALUE)) { - properties.setBlobType(BlobType.BLOCK_BLOB); - } - else if (tempString.equals(BlobConstants.PAGE_BLOB_VALUE)) { - properties.setBlobType(BlobType.PAGE_BLOB); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else if (name.equals(Constants.LEASE_STATUS_ELEMENT)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.LEASE_STATUS_ELEMENT); - if (tempString.equals(Constants.LOCKED_VALUE.toLowerCase())) { - properties.setLeaseStatus(LeaseStatus.LOCKED); - } - else if (tempString.equals(Constants.UNLOCKED_VALUE.toLowerCase())) { - properties.setLeaseStatus(LeaseStatus.UNLOCKED); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else if (name.equals(Constants.LEASE_STATE_ELEMENT)) { - properties.setLeaseState(LeaseState.parse(Utility.readElementFromXMLReader(xmlr, - Constants.LEASE_STATE_ELEMENT))); - } - else if (name.equals(Constants.LEASE_DURATION_ELEMENT)) { - properties.setLeaseDuration(LeaseDuration.parse(Utility.readElementFromXMLReader(xmlr, - Constants.LEASE_DURATION_ELEMENT))); - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT) { - // expect end of properties - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.PROPERTIES); - break; - } - } - - return properties; - } - - /** - * Populates the container from an XMLStreamReader - * - * @param xmlr - * the XMLStreamReader to read from - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - * @throws StorageException - */ - protected static CloudBlobContainer readContainer(final XMLStreamReader xmlr, final CloudBlobClient serviceClient) - throws XMLStreamException, ParseException, URISyntaxException, StorageException { - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.CONTAINER_ELEMENT); - - final BlobContainerAttributes attributes = BlobDeserializationHelper.readBlobContainerAttributes(xmlr); - - final CloudBlobContainer retContainer = new CloudBlobContainer(attributes.getUri(), serviceClient); - retContainer.setMetadata(attributes.getMetadata()); - retContainer.setName(attributes.getName()); - retContainer.setProperties(attributes.getProperties()); - retContainer.setUri(attributes.getUri()); - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.CONTAINER_ELEMENT); - return retContainer; - } - - /** - * Populates CloudBlobContainer objects from the XMLStreamReader, reader must be at Start element of - * ContainersElement - * - * @param xmlr - * the XMLStreamReader object - * @param serviceClient - * the CloudBlobClient associated with the objects. - * @return an ArrayList of CloudBlobContainer from the stream. - * @throws XMLStreamException - * if there is a parsing exception - * @throws ParseException - * if a date value is not correctly encoded - * @throws URISyntaxException - * @throws StorageException - */ - public static ArrayList readContainers(final XMLStreamReader xmlr, - final CloudBlobClient serviceClient) throws XMLStreamException, ParseException, URISyntaxException, - StorageException { - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.CONTAINERS_ELEMENT); - - final ArrayList containers = new ArrayList(); - - eventType = xmlr.next(); - while (eventType == XMLStreamConstants.START_ELEMENT && xmlr.hasName() - && BlobConstants.CONTAINER_ELEMENT.equals(xmlr.getName().toString())) { - containers.add(BlobDeserializationHelper.readContainer(xmlr, serviceClient)); - eventType = xmlr.next(); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.CONTAINERS_ELEMENT); - return containers; - } - - /** - * Populates the CloudBlobDirectory from an XMLStreamReader, reader must be at Start element of BlobPrefix - * - * @param xmlr - * the XMLStreamReader to read from - * @param serviceClient - * the CloudBlobClient associated with the objects. - * @param container - * the container associated with the objects. - * @return a CloudBlobDirectory parsed from the stream. - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - * @throws StorageException - */ - protected static CloudBlobDirectory readDirectory(final XMLStreamReader xmlr, final CloudBlobClient serviceClient, - final CloudBlobContainer container) throws XMLStreamException, ParseException, URISyntaxException, - StorageException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.BLOB_PREFIX_ELEMENT); - - // Move to Name element - xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.NAME_ELEMENT); - - final String prefixName = Utility.readElementFromXMLReader(xmlr, Constants.NAME_ELEMENT); - - // Move from End name element to end prefix element - xmlr.next(); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.BLOB_PREFIX_ELEMENT); - - return container.getDirectoryReference(prefixName); - } - - /** - * Reads PageRanges from the XMLStreamReader, reader must be at Start element of PageRangeElement - * - * @param xmlr - * the XMLStreamReader to read from - * @return the PageRange from the stream. - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - * @throws StorageException - */ - public static ArrayList readPageRanges(final XMLStreamReader xmlr) throws XMLStreamException, - StorageException { - int eventType = xmlr.getEventType(); - final ArrayList retRanges = new ArrayList(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.PAGE_RANGE_ELEMENT); - - // check if there are more events in the input stream - while (xmlr.hasNext() && BlobConstants.PAGE_RANGE_ELEMENT.equals(xmlr.getName().toString())) { - long startOffset = -1; - long endOffset = -1; - - // Read a Page Range - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(BlobConstants.START_ELEMENT)) { - final String sizeString = Utility.readElementFromXMLReader(xmlr, BlobConstants.START_ELEMENT); - startOffset = Long.parseLong(sizeString); - } - else if (name.equals(Constants.END_ELEMENT)) { - final String sizeString = Utility.readElementFromXMLReader(xmlr, Constants.END_ELEMENT); - endOffset = Long.parseLong(sizeString); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT) { - if (startOffset == -1 || endOffset == -1) { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - final PageRange pageRef = new PageRange(startOffset, endOffset); - retRanges.add(pageRef); - break; - } - } - - eventType = xmlr.next(); - } - - return retRanges; - } - - /** - * Private Default Ctor - */ - private BlobDeserializationHelper() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobInputStream.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobInputStream.java deleted file mode 100644 index ac68dc7e15e96..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobInputStream.java +++ /dev/null @@ -1,649 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCode; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Provides an input stream to read a given blob resource. - */ -public final class BlobInputStream extends InputStream { - /** - * Holds the reference to the blob this stream is associated with. - */ - private final CloudBlob parentBlobRef; - - /** - * Holds the reference to the MD5 digest for the blob. - */ - private MessageDigest md5Digest; - - /** - * A flag to determine if the stream is faulted, if so the lasterror will be thrown on next operation. - */ - private volatile boolean streamFaulted; - - /** - * Holds the last exception this stream encountered. - */ - private IOException lastError; - - /** - * Holds the OperationContext for the current stream. - */ - private final OperationContext opContext; - - /** - * Holds the options for the current stream - */ - private final BlobRequestOptions options; - - /** - * Holds the stream length. - */ - private long streamLength = -1; - - /** - * Holds the stream read size for both block and page blobs. - */ - private final int readSize; - - /** - * A flag indicating if the Blob MD5 should be validated. - */ - private boolean validateBlobMd5; - - /** - * Holds the Blob MD5. - */ - private final String retrievedContentMD5Value; - - /** - * Holds the reference to the current buffered data. - */ - private ByteArrayInputStream currentBuffer; - - /** - * Holds an absolute byte position for the mark feature. - */ - private long markedPosition; - - /** - * Holds the mark delta for which the mark position is expired. - */ - private int markExpiry; - - /** - * Holds the List of PageRanges when reading a page blob and using the sparse page blob feature. - */ - private ArrayList pageBlobRanges; - - /** - * Holds an index to the current page range. - */ - private int currentPageRangeIndex; - - /** - * Holds an absolute byte position of the current read position. - */ - private long currentAbsoluteReadPosition; - - /** - * Holds the absolute byte position of the start of the current buffer. - */ - private long bufferStartOffset; - - /** - * Holds the length of the current buffer in bytes. - */ - private int bufferSize; - - /** - * Holds the {@link AccessCondition} object that represents the access conditions for the blob. - */ - private AccessCondition accessCondition = null; - - /** - * Initializes a new instance of the BlobInputStream class. - * - * @param parentBlob - * the blob that this stream is associated with. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * An object that specifies any additional options for the request - * @param opContext - * an object used to track the execution of the operation - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - @DoesServiceRequest - protected BlobInputStream(final CloudBlob parentBlob, final AccessCondition accessCondition, - final BlobRequestOptions options, final OperationContext opContext) throws StorageException { - this.parentBlobRef = parentBlob; - this.parentBlobRef.assertCorrectBlobType(); - this.options = new BlobRequestOptions(options); - this.opContext = opContext; - this.streamFaulted = false; - this.currentAbsoluteReadPosition = 0; - this.readSize = parentBlob.blobServiceClient.getStreamMinimumReadSizeInBytes(); - - if (options.getUseTransactionalContentMD5() && this.readSize > 4 * Constants.MB) { - throw new IllegalArgumentException( - "Cannot specify x-ms-range-get-content-md5 header on ranges larger than 4 MB"); - } - - parentBlob.downloadAttributes(accessCondition, this.options, this.opContext); - - final HttpURLConnection attributesRequest = this.opContext.getCurrentRequestObject(); - - this.retrievedContentMD5Value = attributesRequest.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); - - // Will validate it if it was returned - this.validateBlobMd5 = !options.getDisableContentMD5Validation() - && !Utility.isNullOrEmpty(this.retrievedContentMD5Value); - - // Validates the first option, and sets future requests to use if match - // request option. - - // If there is an existing conditional validate it, as we intend to - // replace if for future requests. - String previousLeaseId = null; - if (accessCondition != null) { - previousLeaseId = accessCondition.getLeaseID(); - - if (!accessCondition.verifyConditional(this.parentBlobRef.getProperties().getEtag(), this.parentBlobRef - .getProperties().getLastModified())) { - throw new StorageException(StorageErrorCode.CONDITION_FAILED.toString(), - "The conditionals specified for this operation did not match server.", - HttpURLConnection.HTTP_PRECON_FAILED, null, null); - } - } - - this.accessCondition = AccessCondition.generateIfMatchCondition(this.parentBlobRef.getProperties().getEtag()); - this.accessCondition.setLeaseID(previousLeaseId); - - this.streamLength = parentBlob.getProperties().getLength(); - - if (this.validateBlobMd5) { - try { - this.md5Digest = MessageDigest.getInstance("MD5"); - } - catch (final NoSuchAlgorithmException e) { - // This wont happen, throw fatal. - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - if (this.parentBlobRef.getProperties().getBlobType() == BlobType.PAGE_BLOB - && this.options.getUseSparsePageBlob()) { - this.pageBlobRanges = ((CloudPageBlob) parentBlob).downloadPageRanges(this.accessCondition, options, - opContext); - } - else if (this.parentBlobRef.getProperties().getBlobType() == BlobType.BLOCK_BLOB) { - if (this.options.getUseSparsePageBlob()) { - throw new IllegalArgumentException( - "The UseSparsePageBlob option is not applicable of Block Blob streams."); - } - } - this.reposition(0); - } - - /** - * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without - * blocking by the next invocation of a method for this input stream. The next invocation might be the same thread - * or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. - * - * @throws IOException - * - if an I/O error occurs. - * @return an estimate of the number of bytes that can be read (or skipped over) from this input stream without - * blocking or 0 when it reaches the end of the input stream. - */ - @Override - public synchronized int available() throws IOException { - return this.bufferSize - (int) (this.currentAbsoluteReadPosition - this.bufferStartOffset); - } - - /** - * Helper function to check if the stream is faulted, if it is it surfaces the exception. - * - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - private synchronized void checkStreamState() throws IOException { - if (this.streamFaulted) { - throw this.lastError; - } - } - - /** - * Closes this input stream and releases any system resources associated with the stream. - * - * @throws IOException - * - if an I/O error occurs. - */ - @Override - public synchronized void close() throws IOException { - this.currentBuffer = null; - this.streamFaulted = true; - this.lastError = new IOException("Stream is closed"); - } - - /** - * Dispatches a read operation of N bytes. When using sparspe page blobs the page ranges are evaluated and zero - * bytes may be generated on the client side for some ranges that do not exist. - * - * @param readLength - * the number of bytes to read. - * @throws IOException - * if an I/O error occurs. - */ - @DoesServiceRequest - private synchronized void dispatchRead(final int readLength) throws IOException { - try { - final byte[] byteBuffer = new byte[readLength]; - if (this.options.getUseSparsePageBlob()) { - long resolvedReadStart = this.currentAbsoluteReadPosition; - long resolvedReadEnd = this.currentAbsoluteReadPosition + readLength; - - PageRange startRange = this.getCurrentRange(); - if (startRange != null) { - resolvedReadStart = startRange.getStartOffset(); - resolvedReadEnd = startRange.getEndOffset() + 1; - - // seek start range - while (this.currentAbsoluteReadPosition > startRange.getEndOffset()) { - this.currentPageRangeIndex++; - startRange = this.getCurrentRange(); - - if (startRange != null) { - resolvedReadStart = startRange.getStartOffset(); - resolvedReadEnd = startRange.getEndOffset() + 1; - } - else { - break; - } - } - } - - if (startRange != null) { - // seek end range - int endDex = this.currentPageRangeIndex + 1; - PageRange endRange = endDex < this.pageBlobRanges.size() ? this.pageBlobRanges.get(endDex) : null; - - while (endDex < this.pageBlobRanges.size() - 1 - && this.currentAbsoluteReadPosition + readLength >= endRange.getEndOffset()) { - endDex++; - endRange = this.pageBlobRanges.get(endDex); - resolvedReadEnd = endRange.getEndOffset() + 1; - } - - resolvedReadEnd = Math.min(resolvedReadEnd, this.currentAbsoluteReadPosition + readLength); - - final int bufferOffset = (int) (resolvedReadStart - this.currentAbsoluteReadPosition); - final int opReadLength = (int) Math.min(readLength - bufferOffset, resolvedReadEnd - - resolvedReadStart); - - // Do read - if (opReadLength > 0) { - this.parentBlobRef.downloadRangeInternal(resolvedReadStart, opReadLength, byteBuffer, - bufferOffset, this.accessCondition, this.options, this.opContext); - } - } - - // ELSE=> no op, buffer already contains zeros. - - } - else { - // Non sparse read, do entire read length - this.parentBlobRef.downloadRangeInternal(this.currentAbsoluteReadPosition, readLength, byteBuffer, 0, - this.accessCondition, this.options, this.opContext); - } - - this.currentBuffer = new ByteArrayInputStream(byteBuffer); - this.bufferSize = readLength; - this.bufferStartOffset = this.currentAbsoluteReadPosition; - } - catch (final StorageException e) { - this.streamFaulted = true; - this.lastError = Utility.initIOException(e); - throw this.lastError; - } - } - - /** - * A helper method to get the current Page Range based on the current page range index. - * - * @return the current Page Range based on the current page range index. - */ - private PageRange getCurrentRange() { - if (this.currentPageRangeIndex >= this.pageBlobRanges.size()) { - return null; - } - return this.pageBlobRanges.get(this.currentPageRangeIndex); - } - - /** - * Gets a value indicating if MD5 should be validated. - * - * @return a value indicating if MD5 should be validated. - */ - protected synchronized boolean getValidateBlobMd5() { - return this.validateBlobMd5; - } - - /** - * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at - * the last marked position so that subsequent reads re-read the same bytes. - * - * @param readlimit - * - the maximum limit of bytes that can be read before the mark position becomes invalid. - */ - @Override - public synchronized void mark(final int readlimit) { - this.markedPosition = this.currentAbsoluteReadPosition; - this.markExpiry = readlimit; - } - - /** - * Tests if this input stream supports the mark and reset methods. Whether or not mark and reset are supported is an - * invariant property of a particular input stream instance. The markSupported method of InputStream returns false. - * - * @return True if this stream instance supports the mark and reset methods; False - * otherwise. - */ - @Override - public boolean markSupported() { - return true; - } - - /** - * Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If - * no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks - * until input data is available, the end of the stream is detected, or an exception is thrown. - * - * @return the next byte of data, or -1 if the end of the stream is reached. - * @throws IOException - * - if an I/O error occurs. - */ - @Override - @DoesServiceRequest - public int read() throws IOException { - final byte[] tBuff = new byte[1]; - final int numberOfBytesRead = this.read(tBuff, 0, 1); - - if (numberOfBytesRead > 0) { - return tBuff[0] & 0xFF; - } - else if (numberOfBytesRead == 0) { - throw new IOException("Unexpected error. Stream returned unexpected number of bytes."); - } - else { - return -1; - } - } - - /** - * Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes - * actually read is returned as an integer. This method blocks until input data is available, end of file is - * detected, or an exception is thrown. If the length of b is zero, then no bytes are read and 0 is returned; - * otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the - * end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b. - * - * The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, - * at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in - * elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected. - * - * The read(b) method for class InputStream has the same effect as: - * - * read(b, 0, b.length) - * - * @param b - * - the buffer into which the data is read. - * @return the total number of bytes read into the buffer, or -1 is there is no more data because the end of the - * stream has been reached. - * - * @throws IOException - * - If the first byte cannot be read for any reason other than the end of the file, if the input stream - * has been closed, or if some other I/O error occurs. - * @throws NullPointerException - * - if b is null. - */ - @Override - @DoesServiceRequest - public int read(final byte[] b) throws IOException { - return this.read(b, 0, b.length); - } - - /** - * Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as - * len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer. This - * method blocks until input data is available, end of file is detected, or an exception is thrown. - * - * If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one - * byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least - * one byte is read and stored into b. - * - * The first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes - * read is, at most, equal to len. Let k be the number of bytes actually read; these bytes will be stored in - * elements b[off] through b[off+k-1], leaving elements b[off+k] through b[off+len-1] unaffected. - * - * In every case, elements b[0] through b[off] and elements b[off+len] through b[b.length-1] are unaffected. - * - * The read(b, off, len) method for class InputStream simply calls the method read() repeatedly. If the first such - * call results in an IOException, that exception is returned from the call to the read(b, off, len) method. If any - * subsequent call to read() results in a IOException, the exception is caught and treated as if it were end of - * file; the bytes read up to that point are stored into b and the number of bytes read before the exception - * occurred is returned. The default implementation of this method blocks until the requested amount of input data - * len has been read, end of file is detected, or an exception is thrown. Subclasses are encouraged to provide a - * more efficient implementation of this method. - * - * @param b - * the buffer into which the data is read. - * @param off - * the start offset in array b at which the data is written. - * @param len - * the maximum number of bytes to read. - * @return the total number of bytes read into the buffer, or -1 if there is no more data because the end of the - * stream has been reached. - * @throws IOException - * If the first byte cannot be read for any reason other than end of file, or if the input stream has - * been closed, or if some other I/O error occurs. - * @throws NullPointerException - * If b is null. - * @throws IndexOutOfBoundsException - * If off is negative, len is negative, or len is greater than b.length - off - */ - @Override - @DoesServiceRequest - public int read(final byte[] b, final int off, final int len) throws IOException { - if (off < 0 || len < 0 || len > b.length - off) { - throw new IndexOutOfBoundsException(); - } - - return this.readInternal(b, off, len); - } - - /** - * Performs internal read to the given byte buffer. - * - * @param b - * the buffer into which the data is read. - * @param off - * the start offset in array b at which the data is written. - * @param len - * the maximum number of bytes to read. - * @return the total number of bytes read into the buffer, or -1 if there is no more data because the end of the - * stream has been reached. - * @throws IOException - * If the first byte cannot be read for any reason other than end of file, or if the input stream has - * been closed, or if some other I/O error occurs. - */ - @DoesServiceRequest - private synchronized int readInternal(final byte[] b, final int off, int len) throws IOException { - this.checkStreamState(); - - // if buffer is empty do next get operation - if ((this.currentBuffer == null || this.currentBuffer.available() == 0) - && this.currentAbsoluteReadPosition < this.streamLength) { - this.dispatchRead((int) Math.min(this.readSize, this.streamLength - this.currentAbsoluteReadPosition)); - } - - len = Math.min(len, this.readSize); - - // do read from buffer - final int numberOfBytesRead = this.currentBuffer.read(b, off, len); - - if (numberOfBytesRead > 0) { - this.currentAbsoluteReadPosition += numberOfBytesRead; - - if (this.validateBlobMd5) { - this.md5Digest.update(b, off, numberOfBytesRead); - - if (this.currentAbsoluteReadPosition == this.streamLength) { - // Reached end of stream, validate md5. - final String calculatedMd5 = Base64.encode(this.md5Digest.digest()); - if (!calculatedMd5.equals(this.retrievedContentMD5Value)) { - this.lastError = Utility - .initIOException(new StorageException( - StorageErrorCodeStrings.INVALID_MD5, - String.format( - "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", - this.retrievedContentMD5Value, calculatedMd5), - Constants.HeaderConstants.HTTP_UNUSED_306, null, null)); - this.streamFaulted = true; - throw this.lastError; - } - } - } - } - - // update markers - if (this.markExpiry > 0 && this.markedPosition + this.markExpiry < this.currentAbsoluteReadPosition) { - this.markedPosition = 0; - this.markExpiry = 0; - } - - return numberOfBytesRead; - } - - /** - * Repositions the stream to the given absolute byte offset. - * - * @param absolutePosition - * the absolute byte offset to reposition to. - */ - private synchronized void reposition(final long absolutePosition) { - this.currentAbsoluteReadPosition = absolutePosition; - this.currentBuffer = new ByteArrayInputStream(new byte[0]); - } - - /** - * Repositions this stream to the position at the time the mark method was last called on this input stream. Note - * repositioning the blob read stream will disable blob MD5 checking. - * - * @throws IOException - * if this stream has not been marked or if the mark has been invalidated. - */ - @Override - public synchronized void reset() throws IOException { - if (this.markedPosition + this.markExpiry < this.currentAbsoluteReadPosition) { - throw new IOException("Mark expired!"); - } - - this.validateBlobMd5 = false; - this.md5Digest = null; - this.reposition(this.markedPosition); - } - - /** - * Sets a value indicating if MD5 should be validated. - * - * @param validateBlobMd5 - * a value indicating if MD5 should be validated. - */ - protected synchronized void setValidateBlobMd5(final boolean validateBlobMd5) { - this.validateBlobMd5 = validateBlobMd5; - } - - /** - * Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, - * end up skipping over some smaller number of bytes, possibly 0. This may result from any of a number of - * conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of - * bytes skipped is returned. If n is negative, no bytes are skipped. - * - * Note repositioning the blob read stream will disable blob MD5 checking. - * - * @param n - * the number of bytes to skip - */ - @Override - public synchronized long skip(final long n) throws IOException { - if (n == 0) { - return 0; - } - - if (n < 0 || this.currentAbsoluteReadPosition + n > this.streamLength) { - throw new IndexOutOfBoundsException(); - } - - this.validateBlobMd5 = false; - this.md5Digest = null; - this.reposition(this.currentAbsoluteReadPosition + n); - return n; - } - - /** - * Writes the entire blob contents from the Windows Azure Blob service to the given output stream. - * - * @param outStream - * the output stream to write to. - * @return the number of bytes written. - * @throws IOException - * if an I/O Error occurs - */ - @DoesServiceRequest - protected long writeTo(final OutputStream outStream) throws IOException { - final byte[] buffer = new byte[Constants.BUFFER_COPY_LENGTH]; - long total = 0; - int count = this.read(buffer); - - while (count != -1) { - outStream.write(buffer, 0, count); - total += count; - count = this.read(buffer); - } - - return total; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobListingContext.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobListingContext.java deleted file mode 100644 index d697d0a69ba8c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobListingContext.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.EnumSet; - -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ListingContext; - -/** - * RESERVED FOR INTERNAL USE. Provides the listing context for blobs including the delimiter and listingdetails - */ -final class BlobListingContext extends ListingContext { - - /** - * Gets or sets the delimiter for a blob listing operation. The delimiter parameter enables the caller to traverse - * the blob namespace by using a user-configured delimiter. Using this parameter, it is possible to traverse a - * virtual hierarchy of blobs as though it were a file system. - */ - private String delimiter; - - /** - * Gets or sets the details for the listing operation, which indicates the types of data to include in the response. - * The include parameter specifies that the response should include one or more of the following subsets: snapshots, - * metadata, uncommitted blobs. - */ - private EnumSet listingDetails; - - /** - * Initializes a new instance of the BlobListingContext class - * - * @param prefix - * the prefix to use. - * @param maxResults - * the maximum results to download. - */ - public BlobListingContext(final String prefix, final Integer maxResults) { - super(prefix, maxResults); - } - - /** - * Initializes a new instance of the BlobListingContext class - * - * @param prefix - * the prefix to use. - * @param maxResults - * the maximum results to download. - * @param delimiter - * the delimiter to use - * @param listingDetails - * the BlobListingDetails to use. - */ - public BlobListingContext(final String prefix, final Integer maxResults, final String delimiter, - final EnumSet listingDetails) { - super(prefix, maxResults); - this.setDelimiter(delimiter); - this.setListingDetails(listingDetails); - } - - /** - * @return the delimiter - */ - protected String getDelimiter() { - return this.delimiter; - } - - /** - * @return the listingDetails - */ - protected EnumSet getListingDetails() { - return this.listingDetails; - } - - /** - * @param delimiter - * the delimiter to set - */ - protected void setDelimiter(final String delimiter) { - this.delimiter = delimiter; - } - - /** - * @param listingDetails - * the listingDetails to set - */ - protected void setListingDetails(final EnumSet listingDetails) { - this.listingDetails = listingDetails; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobListingDetails.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobListingDetails.java deleted file mode 100644 index db0b7f9a2dbd7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobListingDetails.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Specifies which items to include when listing a set of blobs. - *

- * By default, committed blocks are always returned. Use the values in this enum to include snapshots, metadata, and/or - * uncommitted blocks. - *

- */ -public enum BlobListingDetails { - /** - * Specifies listing committed blobs and blob snapshots. - */ - SNAPSHOTS(1), - - /** - * Specifies listing blob metadata for each blob returned in the listing. - */ - METADATA(2), - - /** - * Specifies listing uncommitted blobs. - */ - UNCOMMITTED_BLOBS(4); - - /** - * Returns the value of this enum. - */ - public int value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - BlobListingDetails(final int val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobOutputStream.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobOutputStream.java deleted file mode 100644 index 93d870b15e1bf..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobOutputStream.java +++ /dev/null @@ -1,628 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.CompletionService; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * The class is an append-only stream for writing into storage. - */ -public final class BlobOutputStream extends OutputStream { - /** - * Holds the random number generator used to create starting blockIDs. - */ - private static Random blockSequenceGenerator = new Random(); - - /** - * Holds the reference to the blob this stream is associated with. - */ - private final CloudBlob parentBlobRef; - - /** - * Determines if this stream is used against a page blob or block blob. - */ - private BlobType streamType = BlobType.UNSPECIFIED; - - /** - * A flag to determine if the stream is faulted, if so the lasterror will be thrown on next operation. - */ - volatile boolean streamFaulted; - - /** - * Holds the lock for synchronized access to the last error. - */ - Object lastErrorLock = new Object(); - - /** - * Holds the last exception this stream encountered. - */ - IOException lastError; - - /** - * Holds the OperationContext for the current stream. - */ - OperationContext opContext; - - /** - * Holds the options for the current stream. - */ - BlobRequestOptions options; - - /** - * Holds the reference to the MD5 digest for the blob. - */ - private MessageDigest md5Digest; - - /** - * Used for block blobs, holds the current BlockID Sequence number. - */ - private long blockIdSequenceNumber = -1; - - /** - * Used for block blobs, holds the block list. - */ - private ArrayList blockList; - - /** - * Used for page blobs, holds the currentOffset the stream is writing to. - */ - private long currentPageOffset; - - /** - * Used for page blobs, when uploading UseSparsePageBlob is true holds the buffer index of the first non zero byte. - */ - private long firstNonZeroBufferedByte = -1; - - /** - * Used for page blobs, when uploading UseSparsePageBlob is true holds the buffer index of the last non zero byte. - */ - private long lastNonZeroBufferedByte = -1; - - /** - * A private buffer to store data prior to committing to the cloud. - */ - private ByteArrayOutputStream outBuffer; - - /** - * Holds the number of currently buffered bytes. - */ - private int currentBufferedBytes; - - /** - * Holds the write threshold of number of bytes to buffer prior to dispatching a write. For block blob this is the - * block size, for page blob this is the Page commit size. - */ - private int internalWriteThreshold = -1; - - /** - * Holds the number of current outstanding requests. - */ - private volatile int outstandingRequests; - - /** - * The ExecutorService used to schedule tasks for this stream. - */ - private final ExecutorService threadExecutor; - - /** - * The CompletionService used to await task completion for this stream. - */ - private final CompletionService completionService; - - /** - * Holds the {@link AccessCondition} object that represents the access conditions for the blob. - */ - AccessCondition accessCondition = null; - - /** - * Initializes a new instance of the BlobWriteStream class. - * - * @param parentBlob - * the blob that this stream is associated with. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * An object that specifies any additional options for the request - * @param opContext - * an object used to track the execution of the operation - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - protected BlobOutputStream(final CloudBlob parentBlob, final AccessCondition accessCondition, - final BlobRequestOptions options, final OperationContext opContext) throws StorageException { - this.accessCondition = accessCondition; - this.parentBlobRef = parentBlob; - this.parentBlobRef.assertCorrectBlobType(); - this.options = new BlobRequestOptions(options); - this.outBuffer = new ByteArrayOutputStream(); - this.opContext = opContext; - this.streamFaulted = false; - - if (this.options.getConcurrentRequestCount() < 1) { - throw new IllegalArgumentException("ConcurrentRequestCount"); - } - - if (this.options.getStoreBlobContentMD5()) { - try { - this.md5Digest = MessageDigest.getInstance("MD5"); - } - catch (final NoSuchAlgorithmException e) { - // This wont happen, throw fatal. - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - // V2 cachedThreadPool for perf. - this.threadExecutor = Executors.newFixedThreadPool(this.options.getConcurrentRequestCount()); - this.completionService = new ExecutorCompletionService(this.threadExecutor); - } - - /** - * Initializes a new instance of the BlobWriteStream class for a CloudBlockBlob - * - * @param parentBlob - * the blob that this stream is associated with. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * An object that specifies any additional options for the request - * @param opContext - * an object used to track the execution of the operation - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - protected BlobOutputStream(final CloudBlockBlob parentBlob, final AccessCondition accessCondition, - final BlobRequestOptions options, final OperationContext opContext) throws StorageException { - this((CloudBlob) parentBlob, accessCondition, options, opContext); - this.blockIdSequenceNumber = (long) (blockSequenceGenerator.nextInt(Integer.MAX_VALUE)) - + blockSequenceGenerator.nextInt(Integer.MAX_VALUE - 100000); - this.blockList = new ArrayList(); - - this.streamType = BlobType.BLOCK_BLOB; - this.internalWriteThreshold = this.parentBlobRef.blobServiceClient.getWriteBlockSizeInBytes(); - } - - /** - * Initializes a new instance of the BlobWriteStream class for a CloudPageBlob - * - * @param parentBlob - * the blob that this stream is associated with. - * @param length - * the length of the page blob in bytes, must be a multiple of 512. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * An object that specifies any additional options for the request - * @param opContext - * an object used to track the execution of the operation - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - @DoesServiceRequest - protected BlobOutputStream(final CloudPageBlob parentBlob, final long length, - final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext) - throws StorageException { - this(parentBlob, accessCondition, options, opContext); - this.streamType = BlobType.PAGE_BLOB; - this.internalWriteThreshold = (int) Math.min( - this.parentBlobRef.blobServiceClient.getPageBlobStreamWriteSizeInBytes(), length); - - if (length % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("Page blob length must be multiple of 512."); - } - - if (this.options.getStoreBlobContentMD5()) { - throw new IllegalArgumentException("Blob Level MD5 is not supported for PageBlob"); - } - - parentBlob.create(length, accessCondition, options, opContext); - } - - /** - * Helper function to check if the stream is faulted, if it is it surfaces the exception. - * - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - private void checkStreamState() throws IOException { - synchronized (this.lastErrorLock) { - if (this.streamFaulted) { - throw this.lastError; - } - } - } - - /** - * Closes this output stream and releases any system resources associated with this stream. If any data remains in - * the buffer it is committed to the service. - */ - @Override - @DoesServiceRequest - public void close() throws IOException { - this.flush(); - this.checkStreamState(); - Exception tempException = null; - - synchronized (this.lastErrorLock) { - this.streamFaulted = true; - this.lastError = new IOException("Stream is already closed."); - tempException = this.lastError; - } - - while (this.outstandingRequests > 0) { - this.waitForTaskToComplete(); - } - - this.threadExecutor.shutdown(); - synchronized (this.lastErrorLock) { - // if one of the workers threw an exception, realize it now. - if (tempException != this.lastError) { - throw this.lastError; - } - } - - try { - this.commit(); - } - catch (final StorageException e) { - throw Utility.initIOException(e); - } - } - - /** - * Commits the blob, for block blob this uploads the block list. - * - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - @DoesServiceRequest - private void commit() throws StorageException, IOException { - if (this.options.getStoreBlobContentMD5()) { - this.parentBlobRef.getProperties().setContentMD5(Base64.encode(this.md5Digest.digest())); - } - - if (this.streamType == BlobType.BLOCK_BLOB) { - // wait for all blocks to finish - final CloudBlockBlob blobRef = (CloudBlockBlob) this.parentBlobRef; - - blobRef.commitBlockList(this.blockList, this.accessCondition, this.options, this.opContext); - } - else if (this.streamType == BlobType.PAGE_BLOB) { - this.parentBlobRef.uploadProperties(this.accessCondition, this.options, this.opContext); - } - } - - /** - * Dispatches a write operation for a given length. - * - * @param writeLength - * the length of the data to write, this is the write threshold that triggered the write. - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - @DoesServiceRequest - private synchronized void dispatchWrite(final int writeLength) throws IOException { - if (writeLength == 0) { - return; - } - - Callable worker = null; - - if (this.outstandingRequests > this.options.getConcurrentRequestCount() * 2) { - this.waitForTaskToComplete(); - } - - final ByteArrayInputStream bufferRef = new ByteArrayInputStream(this.outBuffer.toByteArray()); - - if (this.streamType == BlobType.BLOCK_BLOB) { - final CloudBlockBlob blobRef = (CloudBlockBlob) this.parentBlobRef; - final String blockID = Base64.encode(Utility.getBytesFromLong(this.blockIdSequenceNumber++)); - this.blockList.add(new BlockEntry(blockID, BlockSearchMode.LATEST)); - - worker = new Callable() { - @Override - public Void call() { - try { - blobRef.uploadBlock(blockID, bufferRef, writeLength, BlobOutputStream.this.accessCondition, - BlobOutputStream.this.options, BlobOutputStream.this.opContext); - } - catch (final IOException e) { - synchronized (BlobOutputStream.this.lastErrorLock) { - BlobOutputStream.this.streamFaulted = true; - BlobOutputStream.this.lastError = e; - } - } - catch (final StorageException e) { - synchronized (BlobOutputStream.this.lastErrorLock) { - BlobOutputStream.this.streamFaulted = true; - BlobOutputStream.this.lastError = Utility.initIOException(e); - } - } - return null; - } - }; - } - else if (this.streamType == BlobType.PAGE_BLOB) { - final CloudPageBlob blobRef = (CloudPageBlob) this.parentBlobRef; - long tempOffset = this.currentPageOffset; - long tempLength = writeLength; - - if (this.options.getUseSparsePageBlob()) { - if (this.lastNonZeroBufferedByte == -1) { - // All zero page range, reset buffer and return - this.firstNonZeroBufferedByte = -1; - this.lastNonZeroBufferedByte = -1; - this.currentBufferedBytes = 0; - this.currentPageOffset += writeLength; - this.outBuffer = new ByteArrayOutputStream(); - return; - } - - // Offset is currentOffset - extra data to page align write - final long bufferOffset = this.firstNonZeroBufferedByte - this.firstNonZeroBufferedByte - % BlobConstants.PAGE_SIZE; - - tempOffset = this.currentPageOffset + bufferOffset; - - // Find end of last full page - to do this Calculate the end of - // last full page of non zero - // data and subtract the bufferStarting offset calculated above - tempLength = (this.lastNonZeroBufferedByte - bufferOffset) - + (BlobConstants.PAGE_SIZE - (this.lastNonZeroBufferedByte % BlobConstants.PAGE_SIZE)); - - // Reset buffer markers. - this.firstNonZeroBufferedByte = -1; - this.lastNonZeroBufferedByte = -1; - - // Fast forward buffer past zero data if applicable - if (bufferOffset > 0) { - if (bufferOffset != bufferRef.skip(bufferOffset)) { - // Since this buffer is a byte array buffer this should - // always skip the correct number - // of bytes. - throw Utility.initIOException(Utility.generateNewUnexpectedStorageException(null)); - } - } - } - - final long opWriteLength = tempLength; - final long opOffset = tempOffset; - this.currentPageOffset += writeLength; - - worker = new Callable() { - @Override - public Void call() { - try { - blobRef.uploadPages(bufferRef, opOffset, opWriteLength, BlobOutputStream.this.accessCondition, - BlobOutputStream.this.options, BlobOutputStream.this.opContext); - } - catch (final IOException e) { - synchronized (BlobOutputStream.this.lastErrorLock) { - BlobOutputStream.this.streamFaulted = true; - BlobOutputStream.this.lastError = e; - } - } - catch (final StorageException e) { - synchronized (BlobOutputStream.this.lastErrorLock) { - BlobOutputStream.this.streamFaulted = true; - BlobOutputStream.this.lastError = Utility.initIOException(e); - } - } - return null; - } - }; - } - - // Do work and rest buffer. - this.completionService.submit(worker); - this.outstandingRequests++; - this.currentBufferedBytes = 0; - this.outBuffer = new ByteArrayOutputStream(); - } - - /** - * Flushes this output stream and forces any buffered output bytes to be written out. If any data remains in the - * buffer it is committed to the service. - */ - @Override - @DoesServiceRequest - public synchronized void flush() throws IOException { - this.checkStreamState(); - - if (this.streamType == BlobType.PAGE_BLOB && this.currentBufferedBytes > 0 - && (this.currentBufferedBytes % BlobConstants.PAGE_SIZE != 0)) { - throw new IOException(String.format( - "Page data must be a multiple of 512 bytes, buffer currently contains %d bytes.", - this.currentBufferedBytes)); - - // Non 512 byte remainder, uncomment to pad with bytes and commit. - /* - * byte[] nullBuff = new byte[BlobConstants.PageSize - this.currentBufferedBytes % BlobConstants.PageSize]; - * this.write(nullBuff); - */ - } - - this.dispatchWrite(this.currentBufferedBytes); - } - - /** - * Waits for one task to complete - * - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - private void waitForTaskToComplete() throws IOException { - try { - final Future future = this.completionService.take(); - future.get(); - } - catch (final InterruptedException e) { - throw Utility.initIOException(e); - } - catch (final ExecutionException e) { - throw Utility.initIOException(e); - } - - this.outstandingRequests--; - } - - /** - * Writes b.length bytes from the specified byte array to this output stream. - * - * @param data - * the byte array to write. - * - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - @Override - @DoesServiceRequest - public void write(final byte[] data) throws IOException { - this.write(data, 0, data.length); - } - - /** - * Writes length bytes from the specified byte array starting at offset to this output stream. - * - * @param data - * the byte array to write. - * @param offset - * the start offset in the data. - * @param length - * the number of bytes to write. - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - @Override - @DoesServiceRequest - public void write(final byte[] data, final int offset, final int length) throws IOException { - if (offset < 0 || length < 0 || length > data.length - offset) { - throw new IndexOutOfBoundsException(); - } - - this.writeInternal(data, offset, length); - } - - /** - * Writes all data from the InputStream to the Blob. - * - * @param sourceStream - * the InputStram to consume. - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - * @throws StorageException - */ - @DoesServiceRequest - public void write(final InputStream sourceStream, final long writeLength) throws IOException, StorageException { - Utility.writeToOutputStream(sourceStream, this, writeLength, false, false, null, this.opContext); - } - - /** - * Writes the specified byte to this output stream. The general contract for write is that one byte is written to - * the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits - * of b are ignored. - * - * @param byteVal - * the byteValue to write. - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - @Override - public void write(final int byteVal) throws IOException { - this.write(new byte[] { (byte) (byteVal & 0xFF) }); - } - - /** - * Writes the data to the buffer and triggers writes to the service as needed. - * - * @param data - * the byte array to write. - * @param offset - * the start offset in the data. - * @param length - * the number of bytes to write. - * @throws IOException - * if an I/O error occurs. In particular, an IOException may be thrown if the output stream has been - * closed. - */ - @DoesServiceRequest - private synchronized void writeInternal(final byte[] data, int offset, int length) throws IOException { - while (length > 0) { - this.checkStreamState(); - final int availableBufferBytes = this.internalWriteThreshold - this.currentBufferedBytes; - final int nextWrite = Math.min(availableBufferBytes, length); - - // If we need to set MD5 then update the digest accordingly - if (this.options.getStoreBlobContentMD5()) { - this.md5Digest.update(data, offset, nextWrite); - } - - // If Page blob and UseSparsePageBlob is true, then track first and - // last non zero bytes. - if (this.options.getUseSparsePageBlob()) { - for (int m = 0; m < nextWrite; m++) { - if (data[m + offset] != 0) { - if (this.firstNonZeroBufferedByte == -1) { - this.firstNonZeroBufferedByte = this.currentBufferedBytes + m; - } - - this.lastNonZeroBufferedByte = this.currentBufferedBytes + m; - } - } - } - - this.outBuffer.write(data, offset, nextWrite); - this.currentBufferedBytes += nextWrite; - offset += nextWrite; - length -= nextWrite; - - if (this.currentBufferedBytes == this.internalWriteThreshold) { - this.dispatchWrite(this.internalWriteThreshold); - } - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobProperties.java deleted file mode 100644 index 0eaff8e5789a4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobProperties.java +++ /dev/null @@ -1,364 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.Date; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.LeaseDuration; -import com.microsoft.windowsazure.services.core.storage.LeaseState; -import com.microsoft.windowsazure.services.core.storage.LeaseStatus; - -/** - * Represents the system properties for a blob. - */ -public final class BlobProperties { - - /** - * Represents the type of the blob. - */ - private BlobType blobType = BlobType.UNSPECIFIED; - - /** - * Represents the cache-control value stored for the blob. - */ - private String cacheControl; - - /** - * Represents the content-encoding value stored for the blob. If this field has not been set for the blob, the field - * returns null. - */ - private String contentEncoding; - - /** - * Represents the content-language value stored for the blob. If this field has not been set for the blob, the field - * returns null. - */ - private String contentLanguage; - - /** - * Represents the content MD5 value stored for the blob. - */ - private String contentMD5; - - /** - * Represents the content type value stored for the blob. If this field has not been set for the blob, the field - * returns null. - */ - private String contentType; - - /** - * Represents the blob's ETag value. - *

- * The ETag value is a unique identifier that is updated when a write operation is performed against the container. - * It may be used to perform operations conditionally, providing concurrency control and improved efficiency. - *

- * The {@link AccessCondition#ifMatch} and {@link AccessCondition#ifNoneMatch} methods take an ETag value and return - * an {@link AccessCondition} object that may be specified on the request. - */ - private String etag; - - /** - * Represents the last-modified time for the blob. - */ - private Date lastModified; - - /** - * Represents the blob's lease status. - */ - private LeaseStatus leaseStatus = com.microsoft.windowsazure.services.core.storage.LeaseStatus.UNLOCKED; - - /** - * Represents the blob's lease state. - */ - private LeaseState leaseState; - - /** - * Represents the blob's lease duration. - */ - private LeaseDuration leaseDuration; - - /** - * Represents the size, in bytes, of the blob. - */ - private long length; - - /** - * Creates an instance of the BlobProperties class. - */ - public BlobProperties() { - // No op - } - - /** - * Creates an instance of the BlobProperties class by copying values from another instance of the - * BlobProperties class. - * - * @param other - * A BlobProperties object that represents the blob properties to copy. - */ - public BlobProperties(final BlobProperties other) { - this.blobType = other.blobType; - this.contentEncoding = other.contentEncoding; - this.contentLanguage = other.contentLanguage; - this.contentType = other.contentType; - this.etag = other.etag; - this.leaseStatus = other.leaseStatus; - this.leaseState = other.leaseState; - this.leaseDuration = other.leaseDuration; - this.length = other.length; - this.lastModified = other.lastModified; - this.contentMD5 = other.contentMD5; - this.cacheControl = other.cacheControl; - } - - /** - * Creates an instance of the BlobProperties class. - */ - public BlobProperties(final BlobType type) { - this.blobType = type; - } - - /** - * Returns the blob type for the blob. - * - * @return A {@link BlobType} value that represents the blob type. - */ - public BlobType getBlobType() { - return this.blobType; - } - - /** - * Returns the cache control value for the blob. - * - * @return A string that represents the cache control value for the blob. - */ - public String getCacheControl() { - return this.cacheControl; - } - - /** - * Gets the content encoding value for the blob. - * - * @return A string containing the content encoding, or null if content encoding has not been set - * on the blob. - */ - public String getContentEncoding() { - return this.contentEncoding; - } - - /** - * Gets the content language value for the blob. - * - * @return A string containing the content language, or null if content language has not been set on - * the blob. - */ - public String getContentLanguage() { - return this.contentLanguage; - } - - /** - * Gets the content MD5 value for the blob. - * - * @return A string containing the content MD5 value. - */ - public String getContentMD5() { - return this.contentMD5; - } - - /** - * Gets the content type value for the blob. - * - * @return A string containing content type, or null if the content type has not be set for the blob. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Gets the ETag value for the blob. - * - * @return A string containing the ETag value. - */ - public String getEtag() { - return this.etag; - } - - /** - * Gets the last modified time for the blob. - * - * @return A Date containing the last modified time for the blob. - */ - public Date getLastModified() { - return this.lastModified; - } - - /** - * Gets the lease status for the blob. Reserved for internal use. - * - * @return A LeaseStatus object representing the lease status. - */ - public LeaseStatus getLeaseStatus() { - return this.leaseStatus; - } - - /** - * Gets the lease state for the blob. - * - * @return A LeaseState object representing the lease state. - */ - public LeaseState getLeaseState() { - return this.leaseState; - } - - /** - * Gets the lease duration for the blob. - * - * @return A LeaseDuration object representing the lease duration. - */ - public LeaseDuration getLeaseDuration() { - return this.leaseDuration; - } - - /** - * Gets the size, in bytes, of the blob. - * - * @return The length of the blob. - */ - public long getLength() { - return this.length; - } - - /** - * Sets the blob type. Reserved for internal use. - * - * @param blobType - * The blob type to set, represented by a BlobType object. - */ - protected void setBlobType(final BlobType blobType) { - this.blobType = blobType; - } - - /** - * Sets the cache control value for the blob. - * - * @param cacheControl - * The cache control value to set. - */ - public void setCacheControl(final String cacheControl) { - this.cacheControl = cacheControl; - } - - /** - * Sets the content encoding value for the blob. - * - * @param contentEncoding - * The content encoding value to set. - */ - public void setContentEncoding(final String contentEncoding) { - this.contentEncoding = contentEncoding; - } - - /** - * Sets the content language for the blob. - * - * @param contentLanguage - * The content language value to set. - */ - public void setContentLanguage(final String contentLanguage) { - this.contentLanguage = contentLanguage; - } - - /** - * Sets the content MD5 value for the blob. - * - * @param contentMD5 - * The content MD5 value to set. - */ - public void setContentMD5(final String contentMD5) { - this.contentMD5 = contentMD5; - } - - /** - * Sets the content type value for the blob. - * - * @param contentType - * The content type value to set. - */ - public void setContentType(final String contentType) { - this.contentType = contentType; - } - - /** - * Sets the ETag value for the blob. Reserved for internal use. - * - * @param etag - * The ETag value to set. - */ - public void setEtag(final String etag) { - this.etag = etag; - } - - /** - * Sets the last modified time for the blob. Reserved for internal use. - * - * @param lastModified - * The last modified time to set. - */ - public void setLastModified(final Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Sets the lease status for the blob. Reserved for internal use. - * - * @param leaseStatus - * The lease status to set, represented by a LeaseStatus object. - */ - public void setLeaseStatus(final LeaseStatus leaseStatus) { - this.leaseStatus = leaseStatus; - } - - /** - * Sets the lease state for the blob. Reserved for internal use. - * - * @param leaseState - * The lease state to set, represented by a LeaseState object. - */ - public void setLeaseState(final LeaseState leaseState) { - this.leaseState = leaseState; - } - - /** - * Sets the lease duration for the blob. Reserved for internal use. - * - * @param leaseDuration - * The lease duration value to set, represented by a LeaseDuration object. - */ - public void setLeaseDuration(final LeaseDuration leaseDuration) { - this.leaseDuration = leaseDuration; - } - - /** - * Sets the content length, in bytes, for the blob. Reserved for internal use. - * - * @param length - * The length to set. - */ - public void setLength(final long length) { - this.length = length; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobRequest.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobRequest.java deleted file mode 100644 index 97dd33e6b9e66..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobRequest.java +++ /dev/null @@ -1,1041 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseRequest; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LeaseAction; - -/** - * RESERVED FOR INTERNAL USE. Provides a set of methods for constructing requests for blob operations. - */ -final class BlobRequest { - /** - * Adds the metadata. - * - * @param request - * The request. - * @param metadata - * The metadata. - */ - public static void addMetadata(final HttpURLConnection request, final HashMap metadata, - final OperationContext opContext) { - BaseRequest.addMetadata(request, metadata, opContext); - } - - /** - * Adds the metadata. - * - * @param request - * The request. - * @param name - * The metadata name. - * @param value - * The metadata value. - */ - public static void addMetadata(final HttpURLConnection request, final String name, final String value, - final OperationContext opContext) { - BaseRequest.addMetadata(request, name, value, opContext); - } - - /** - * Creates a request to copy a blob, Sign with 0 length. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @param source - * The canonical path to the source blob, in the form ///. - * @param sourceSnapshotID - * The snapshot version, if the source blob is a snapshot. - * @param sourceAccessConditionType - * A type of condition to check on the source blob. - * @param sourceAccessConditionValue - * The value of the condition to check on the source blob - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - * @throws IOException - * @throws URISyntaxException - */ - public static HttpURLConnection copyFrom(final URI uri, final int timeout, String source, - final String sourceSnapshotID, final AccessCondition sourceAccessCondition, - final AccessCondition destinationAccessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws StorageException, IOException, URISyntaxException { - - if (sourceSnapshotID != null) { - source = source.concat("?snapshot="); - source = source.concat(sourceSnapshotID); - } - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, null, opContext); - - request.setFixedLengthStreamingMode(0); - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - request.setRequestProperty(Constants.HeaderConstants.COPY_SOURCE_HEADER, source); - - if (sourceAccessCondition != null) { - sourceAccessCondition.applyConditionToRequest(request, true); - } - - if (destinationAccessCondition != null) { - destinationAccessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Generates a web request to abort a copy operation. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @param copyId - * A String object that identifying the copy operation. - * @param accessCondition - * The access condition to apply to the request. Only lease conditions are supported for this operation. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - * @throws IOException - * @throws URISyntaxException - */ - public static HttpURLConnection abortCopy(final URI uri, final int timeout, final String copyId, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws StorageException, IOException, URISyntaxException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - - builder.add("comp", "copy"); - builder.add("copyid", copyId); - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setFixedLengthStreamingMode(0); - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - request.setRequestProperty("x-ms-copy-action", "abort"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request, true); - } - - return request; - } - - /** - * Creates the web request. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @param query - * The query builder to use. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - private static HttpURLConnection createURLConnection(final URI uri, final int timeout, final UriQueryBuilder query, - final BlobRequestOptions blobOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - return BaseRequest.createURLConnection(uri, timeout, query, opContext); - } - - /** - * Constructs a HttpURLConnection to delete the blob, Sign with no length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param snapshotVersion - * The snapshot version, if the blob is a snapshot. - * @param deleteSnapshotsOption - * A set of options indicating whether to delete only blobs, only snapshots, or both. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection delete(final URI uri, final int timeout, final String snapshotVersion, - final DeleteSnapshotsOption deleteSnapshotsOption, final AccessCondition accessCondition, - final BlobRequestOptions blobOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - - if (snapshotVersion != null && deleteSnapshotsOption != DeleteSnapshotsOption.NONE) { - throw new IllegalArgumentException(String.format( - "The option '%s' must be 'None' to delete a specific snapshot specified by '%s'", - "deleteSnapshotsOption", "snapshot")); - } - - final UriQueryBuilder builder = new UriQueryBuilder(); - BaseRequest.addSnapshot(builder, snapshotVersion); - final HttpURLConnection request = BaseRequest.delete(uri, timeout, builder, opContext); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - switch (deleteSnapshotsOption) { - case NONE: - // nop - break; - case INCLUDE_SNAPSHOTS: - request.setRequestProperty(Constants.HeaderConstants.DELETE_SNAPSHOT_HEADER, - BlobConstants.INCLUDE_SNAPSHOTS_VALUE); - break; - case DELETE_SNAPSHOTS_ONLY: - request.setRequestProperty(Constants.HeaderConstants.DELETE_SNAPSHOT_HEADER, - BlobConstants.SNAPSHOTS_ONLY_VALUE); - break; - default: - break; - } - - return request; - } - - /** - * Constructs a HttpURLConnection to download the blob, Sign with no length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param snapshotVersion - * The snapshot version, if the blob is a snapshot. - * @param offset - * The offset at which to begin returning content. - * @param count - * The number of bytes to return. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection get(final URI uri, final int timeout, final String snapshotVersion, - final long offset, final long count, final AccessCondition accessCondition, - final BlobRequestOptions blobOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - final HttpURLConnection request = get(uri, timeout, snapshotVersion, accessCondition, blobOptions, opContext); - - final String rangeHeaderValue = String.format(Utility.LOCALE_US, Constants.HeaderConstants.RANGE_HEADER_FORMAT, - offset, offset + count - 1); - - request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, rangeHeaderValue); - - return request; - } - - /** - * Constructs a HttpURLConnection to download the blob, Sign with no length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param snapshotVersion - * The snapshot version, if the blob is a snapshot. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection get(final URI uri, final int timeout, final String snapshotVersion, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - BaseRequest.addSnapshot(builder, snapshotVersion); - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - request.setRequestMethod("GET"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Constructs a HttpURLConnection to return a list of the block blobs blocks. Sign with no length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param snapshotVersion - * The snapshot version, if the blob is a snapshot. - * @param blockFilter - * The types of blocks to include in the list: committed, uncommitted, or both. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection getBlockList(final URI uri, final int timeout, final String snapshotVersion, - final BlockListingFilter blockFilter, final AccessCondition accessCondition, - final BlobRequestOptions blobOptions, final OperationContext opContext) throws StorageException, - IOException, URISyntaxException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - - builder.add("comp", "blocklist"); - builder.add("blocklisttype", blockFilter.toString()); - BaseRequest.addSnapshot(builder, snapshotVersion); - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - request.setRequestMethod("GET"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Constructs a HttpURLConnection to return a list of the PageBlob's page ranges. Sign with no length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param snapshotVersion - * The snapshot version, if the blob is a snapshot. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection getPageRanges(final URI uri, final int timeout, final String snapshotVersion, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws StorageException, IOException, URISyntaxException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "pagelist"); - BaseRequest.addSnapshot(builder, snapshotVersion); - - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - request.setRequestMethod("GET"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - BaseRequest.addOptionalHeader(request, BlobConstants.SNAPSHOT, snapshotVersion); - return request; - } - - /** - * Constructs a HttpURLConnection to return the blob's system properties, Sign with no length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param snapshotVersion - * The snapshot version, if the blob is a snapshot. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection getProperties(final URI uri, final int timeout, final String snapshotVersion, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws StorageException, IOException, URISyntaxException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - BaseRequest.addSnapshot(builder, snapshotVersion); - final HttpURLConnection request = BaseRequest.getProperties(uri, timeout, builder, opContext); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Constructs a HttpURLConnection to Acquire,Release,Break, or Renew a blob lease. Sign with 0 length. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param action - * the LeaseAction to perform - * - * @param visibilityTimeoutInSeconds - * Specifies the the span of time for which to acquire the lease, in seconds. - * If null, an infinite lease will be acquired. If not null, this must be greater than zero. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param breakPeriodInSeconds - * Specifies the amount of time to allow the lease to remain, in seconds. - * If null, the break period is the remainder of the current lease, or zero for infinite leases. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection lease(final URI uri, final int timeout, final LeaseAction action, - final Integer leaseTimeInSeconds, final String proposedLeaseId, final Integer breakPeriodInSeconds, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "lease"); - - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - - request.setDoOutput(true); - request.setRequestMethod("PUT"); - request.setFixedLengthStreamingMode(0); - request.setRequestProperty("x-ms-lease-action", action.toString()); - - if (leaseTimeInSeconds != null) { - request.setRequestProperty("x-ms-lease-duration", leaseTimeInSeconds.toString()); - } - else { - request.setRequestProperty("x-ms-lease-duration", "-1"); - } - - if (proposedLeaseId != null) { - request.setRequestProperty("x-ms-proposed-lease-id", proposedLeaseId); - } - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - return request; - } - - /** - * Constructs a HttpURLConnection to list blobs. Sign with no length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param listingContext - * A set of parameters for the listing operation. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection configured for the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - * */ - public static HttpURLConnection list(final URI uri, final int timeout, final BlobListingContext listingContext, - final BlobRequestOptions blobOptions, final OperationContext opContext) throws URISyntaxException, - IOException, StorageException { - - final UriQueryBuilder builder = ContainerRequest.getContainerUriQueryBuilder(); - builder.add("comp", "list"); - - if (listingContext != null) { - if (!Utility.isNullOrEmpty(listingContext.getPrefix())) { - builder.add("prefix", listingContext.getPrefix()); - } - - if (!Utility.isNullOrEmpty(listingContext.getDelimiter())) { - builder.add("delimiter", listingContext.getDelimiter()); - } - - if (!Utility.isNullOrEmpty(listingContext.getMarker())) { - builder.add("marker", listingContext.getMarker()); - } - - if (listingContext.getMaxResults() != null && listingContext.getMaxResults() > 0) { - builder.add("maxresults", listingContext.getMaxResults().toString()); - } - - if (listingContext.getListingDetails().size() > 0) { - final StringBuilder sb = new StringBuilder(); - - boolean started = false; - - if (listingContext.getListingDetails().contains(BlobListingDetails.SNAPSHOTS)) { - if (!started) { - started = true; - } - else { - sb.append(","); - } - - sb.append("snapshots"); - } - - if (listingContext.getListingDetails().contains(BlobListingDetails.UNCOMMITTED_BLOBS)) { - if (!started) { - started = true; - } - else { - sb.append(","); - } - - sb.append("uncommittedblobs"); - } - - if (listingContext.getListingDetails().contains(BlobListingDetails.METADATA)) { - if (!started) { - started = true; - } - else { - sb.append(","); - } - - sb.append("metadata"); - } - - builder.add("include", sb.toString()); - } - } - - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - - request.setRequestMethod("GET"); - - return request; - } - - /** - * Constructs a HttpURLConnection to upload a blob. Sign with blob length, or -1 for pageblob create. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param properties - * The properties to set for the blob. - * @param blobType - * The type of the blob. - * @param pageBlobSize - * For a page blob, the size of the blob. This parameter is ignored for block blobs. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection put(final URI uri, final int timeout, final BlobProperties properties, - final BlobType blobType, final long pageBlobSize, final AccessCondition accessCondition, - final BlobRequestOptions blobOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - if (blobType == BlobType.UNSPECIFIED) { - throw new IllegalArgumentException("The blob type cannot be undefined."); - } - - final HttpURLConnection request = BlobRequest.createURLConnection(uri, timeout, null, blobOptions, opContext); - - request.setDoOutput(true); - - request.setRequestMethod("PUT"); - - // use set optional header - BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CACHE_CONTROL, properties.getCacheControl()); - BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CONTENT_TYPE, properties.getContentType()); - BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CONTENT_MD5, properties.getContentMD5()); - BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CONTENT_LANGUAGE, - properties.getContentLanguage()); - BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CONTENT_ENCODING, - properties.getContentEncoding()); - - if (blobType == BlobType.PAGE_BLOB) { - request.setFixedLengthStreamingMode(0); - request.setRequestProperty(Constants.HeaderConstants.CONTENT_LENGTH, "0"); - - request.setRequestProperty(BlobConstants.BLOB_TYPE_HEADER, BlobConstants.PAGE_BLOB); - request.setRequestProperty(BlobConstants.SIZE, String.valueOf(pageBlobSize)); - - properties.setLength(pageBlobSize); - } - else { - request.setRequestProperty(BlobConstants.BLOB_TYPE_HEADER, BlobConstants.BLOCK_BLOB); - } - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Constructs a HttpURLConnection to upload a block. Sign with length of block data. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param blockId - * the Base64 ID for the block - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection putBlock(final URI uri, final int timeout, final String blockId, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "block"); - builder.add("blockid", blockId); - - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Constructs a HttpURLConnection to set the blob's properties, Sign with zero length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection putBlockList(final URI uri, final int timeout, final BlobProperties properties, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "blocklist"); - - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CACHE_CONTROL_HEADER, - properties.getCacheControl()); - BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_ENCODING_HEADER, properties.getContentEncoding()); - BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_LANGUAGE_HEADER, properties.getContentLanguage()); - BaseRequest.addOptionalHeader(request, BlobConstants.BLOB_CONTENT_MD5_HEADER, properties.getContentMD5()); - BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_TYPE_HEADER, properties.getContentType()); - - return request; - } - - /** - * Constructs a HttpURLConnection to upload a block. Sign with page length for update, or 0 for clear. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param properties - * the page properties - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection putPage(final URI uri, final int timeout, final PageProperties properties, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "page"); - - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - if (properties.getPageOperation() == PageOperationType.CLEAR) { - request.setFixedLengthStreamingMode(0); - } - - // Page write is either update or clean; required - request.setRequestProperty(BlobConstants.PAGE_WRITE, properties.getPageOperation().toString()); - request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, properties.getRange().toString()); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Constructs a HttpURLConnection to set the blob's metadata, Sign with 0 length. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection setMetadata(final URI uri, final int timeout, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - final HttpURLConnection request = BaseRequest.setMetadata(uri, timeout, null, opContext); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Constructs a HttpURLConnection to set the blob's properties, Sign with zero length specified. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param newBlobSize - * The new blob size, if the blob is a page blob. Set this parameter to null to keep the existing blob - * size. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection setProperties(final URI uri, final int timeout, final BlobProperties properties, - final Long newBlobSize, final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "properties"); - - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - - request.setFixedLengthStreamingMode(0); - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - if (newBlobSize != null) { - request.setRequestProperty(BlobConstants.SIZE, newBlobSize.toString()); - properties.setLength(newBlobSize); - } - - BaseRequest.addOptionalHeader(request, Constants.HeaderConstants.CACHE_CONTROL_HEADER, - properties.getCacheControl()); - BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_ENCODING_HEADER, properties.getContentEncoding()); - BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_LANGUAGE_HEADER, properties.getContentLanguage()); - BaseRequest.addOptionalHeader(request, BlobConstants.BLOB_CONTENT_MD5_HEADER, properties.getContentMD5()); - BaseRequest.addOptionalHeader(request, BlobConstants.CONTENT_TYPE_HEADER, properties.getContentType()); - - return request; - } - - /** - * Constructs a HttpURLConnection to create a snapshot of the blob. Sign with 0 length. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection snapshot(final URI uri, final int timeout, final AccessCondition accessCondition, - final BlobRequestOptions blobOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add(Constants.HeaderConstants.COMP, BlobConstants.SNAPSHOT); - final HttpURLConnection request = BlobRequest - .createURLConnection(uri, timeout, builder, blobOptions, opContext); - - request.setFixedLengthStreamingMode(0); - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - - return request; - } - - /** - * Writes a Block List and returns the corresponding UTF8 bytes. - * - * @param blockList - * the Iterable of BlockEntry to write - * @param opContext - * a tracking object for the request - * @return a byte array of the UTF8 bytes representing the serialized block list. - * @throws XMLStreamException - * if there is an error writing the block list. - * @throws StorageException - */ - public static byte[] writeBlockListToStream(final Iterable blockList, final OperationContext opContext) - throws XMLStreamException, StorageException { - - final StringWriter outWriter = new StringWriter(); - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outWriter); - - // default is UTF8 - xmlw.writeStartDocument(); - xmlw.writeStartElement(BlobConstants.BLOCK_LIST_ELEMENT); - - for (final BlockEntry block : blockList) { - if (block.searchMode == BlockSearchMode.COMMITTED) { - xmlw.writeStartElement(BlobConstants.COMMITTED_ELEMENT); - } - else if (block.searchMode == BlockSearchMode.UNCOMMITTED) { - xmlw.writeStartElement(BlobConstants.UNCOMMITTED_ELEMENT); - } - else if (block.searchMode == BlockSearchMode.LATEST) { - xmlw.writeStartElement(BlobConstants.LATEST_ELEMENT); - } - - xmlw.writeCharacters(block.getId()); - xmlw.writeEndElement(); - } - - // end BlockListElement - xmlw.writeEndElement(); - - // end doc - xmlw.writeEndDocument(); - try { - return outWriter.toString().getBytes("UTF8"); - } - catch (final UnsupportedEncodingException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - /** - * Private Default Ctor - */ - private BlobRequest() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobRequestOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobRequestOptions.java deleted file mode 100644 index 8c1b5e055a51f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobRequestOptions.java +++ /dev/null @@ -1,176 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.blob.client; - -import com.microsoft.windowsazure.services.core.storage.RequestOptions; - -/** - * Represents a set of options that may be specified on a request. - */ -public final class BlobRequestOptions extends RequestOptions { - - /** - * Represents the concurrent number of simultaneous requests per operation. If it's null, it will be set to the - * value specified by the cloud blob client's {@link CloudBlobClient#getConcurrentRequestCount} method during upload - * operations. - */ - private Integer concurrentRequestCount = null; - - /** - * Specifies whether a range PUT or GET operation will use the Content-MD5 header to enforce transactional security. - * All partial blob uploads or downloads will be restricted to 4 MB. The default value is false. - */ - private Boolean useTransactionalContentMD5 = false; - - /** - * Specifies whether the blob's ContentMD5 header should be set on uploads. This field is not supported for page - * blobs. The default value is false. - */ - private Boolean storeBlobContentMD5 = false; - - /** - * Specifies whether download and {@link BlobInputStream} methods should ignore the blob's ContentMD5 header. The - * default value is false. - */ - private Boolean disableContentMD5Validation = false; - - /** - * Specifies whether to use sparse page blobs. - * - * When true, "zero" pages are not explicitly uploaded for a page blob; additionally, GET page ranges - * are used only to download explicit information for the page blob. The default value is false. - */ - private Boolean useSparsePageBlob = false; - - /** - * Creates an instance of the BlobRequestOptions class. - */ - public BlobRequestOptions() { - // Empty Default Ctor - } - - /** - * Creates an instance of the BlobRequestOptions class by copying values from another - * BlobRequestOptions instance. - * - * @param other - * A BlobRequestOptions object that represents the blob request options to copy. - */ - public BlobRequestOptions(final BlobRequestOptions other) { - super(other); - this.setConcurrentRequestCount(other.getConcurrentRequestCount()); - this.setStoreBlobContentMD5(other.getStoreBlobContentMD5()); - this.setUseTransactionalContentMD5(other.getUseTransactionalContentMD5()); - this.setUseSparsePageBlob(other.getUseSparsePageBlob()); - this.disableContentMD5Validation = other.disableContentMD5Validation; - } - - /** - * Uses the default timeout interval and retry policy from the specified client if the timeout interval and retry - * policy are null, and also sets the concurrent request count (whether or not it has already been - * assigned a value). - * - * @param client - * A {@link CloudBlobClient} object that represents the service client used to set the default timeout - * interval and retry policy, if they are null. Additionally, if the - * {@link #concurrentRequestCount} field's value is null, it will be set to the value specified by the - * cloud blob client's {@link CloudBlobClient#getConcurrentRequestCount} method. - */ - protected void applyDefaults(final CloudBlobClient client) { - super.applyBaseDefaults(client); - - if (this.getConcurrentRequestCount() == null) { - this.setConcurrentRequestCount(client.getConcurrentRequestCount()); - } - } - - /** - * @return the concurrentRequestCount - */ - public Integer getConcurrentRequestCount() { - return this.concurrentRequestCount; - } - - /** - * @return the disableContentMD5Validation - */ - protected boolean getDisableContentMD5Validation() { - return this.disableContentMD5Validation; - } - - /** - * @return the storeBlobContentMD5 - */ - public boolean getStoreBlobContentMD5() { - return this.storeBlobContentMD5; - } - - /** - * @return the useSparsePageBlob - */ - public boolean getUseSparsePageBlob() { - return this.useSparsePageBlob; - } - - /** - * @return the useTransactionalContentMD5 - */ - public boolean getUseTransactionalContentMD5() { - return this.useTransactionalContentMD5; - } - - /** - * @param concurrentRequestCount - * the concurrentRequestCount to set - */ - public void setConcurrentRequestCount(final Integer concurrentRequestCount) { - this.concurrentRequestCount = concurrentRequestCount; - } - - /** - * @param disableContentMD5Validation - * the disableContentMD5Validation to set - */ - public void setDisableContentMD5Validation(final boolean disableContentMD5Validation) { - this.disableContentMD5Validation = disableContentMD5Validation; - } - - /** - * @param storeBlobContentMD5 - * the storeBlobContentMD5 to set - */ - public void setStoreBlobContentMD5(final boolean storeBlobContentMD5) { - this.storeBlobContentMD5 = storeBlobContentMD5; - } - - /** - * @param useSparsePageBlob - * the useSparsePageBlob to set - */ - public void setUseSparsePageBlob(final boolean useSparsePageBlob) { - this.useSparsePageBlob = useSparsePageBlob; - } - - /** - * @param useTransactionalContentMD5 - * the useTransactionalContentMD5 to set - */ - public void setUseTransactionalContentMD5(final boolean useTransactionalContentMD5) { - this.useTransactionalContentMD5 = useTransactionalContentMD5; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobResponse.java deleted file mode 100644 index 24c3d5eb9ff60..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobResponse.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.Calendar; -import java.util.Date; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseResponse; - -/** - * RESERVED FOR INTERNAL USE. A class for parsing various responses from the blob service - */ -final class BlobResponse extends BaseResponse { - - /** - * Gets the BlobAttributes from the given request - * - * @param request - * The response from server. - * @param resourceURI - * The blob uri to set. - * @param snapshotID - * The snapshot version, if the blob is a snapshot. - * @param opContext - * a tracking object for the request - * @return the BlobAttributes from the given request - * @throws ParseException - * @throws URISyntaxException - */ - public static BlobAttributes getAttributes(final HttpURLConnection request, final URI resourceURI, - final String snapshotID, final OperationContext opContext) throws URISyntaxException, ParseException { - - final String blobType = request.getHeaderField(BlobConstants.BLOB_TYPE_HEADER); - final BlobAttributes attributes = new BlobAttributes(BlobType.parse(blobType)); - final BlobProperties properties = attributes.getProperties(); - - properties.setCacheControl(request.getHeaderField(Constants.HeaderConstants.CACHE_CONTROL)); - properties.setContentEncoding(request.getHeaderField(Constants.HeaderConstants.CONTENT_ENCODING)); - properties.setContentLanguage(request.getHeaderField(Constants.HeaderConstants.CONTENT_LANGUAGE)); - properties.setContentMD5(request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5)); - properties.setContentType(request.getHeaderField(Constants.HeaderConstants.CONTENT_TYPE)); - properties.setEtag(request.getHeaderField(Constants.HeaderConstants.ETAG)); - - final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US); - lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE); - lastModifiedCalendar.setTime(new Date(request.getLastModified())); - properties.setLastModified(lastModifiedCalendar.getTime()); - - properties.setLeaseStatus(BaseResponse.getLeaseStatus(request)); - properties.setLeaseState(BaseResponse.getLeaseState(request)); - properties.setLeaseDuration(BaseResponse.getLeaseDuration(request)); - - final String rangeHeader = request.getHeaderField(Constants.HeaderConstants.CONTENT_RANGE); - final String xContentLengthHeader = request.getHeaderField(BlobConstants.CONTENT_LENGTH_HEADER); - - if (!Utility.isNullOrEmpty(rangeHeader)) { - properties.setLength(Long.parseLong(rangeHeader)); - } - else if (!Utility.isNullOrEmpty(xContentLengthHeader)) { - properties.setLength(Long.parseLong(xContentLengthHeader)); - } - else { - // using this instead of the request property since the request - // property only returns an int. - final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); - - if (!Utility.isNullOrEmpty(contentLength)) { - properties.setLength(Long.parseLong(contentLength)); - } - } - - attributes.uri = resourceURI; - attributes.snapshotID = snapshotID; - - attributes.setMetadata(getMetadata(request)); - - attributes.setCopyState(BaseResponse.getCopyState(request)); - return attributes; - } - - /** - * Gets the lease id from the request header. - * - * @param request - * The response from server. - * @param opContext - * a tracking object for the request - * @return the lease id from the request header. - */ - public static String getLeaseID(final HttpURLConnection request, final OperationContext opContext) { - return request.getHeaderField("x-ms-lease-id"); - } - - /** - * Gets the lease Time from the request header. - * - * @param request - * The response from server. - * @param opContext - * a tracking object for the request - * @return the lease Time from the request header. - */ - public static String getLeaseTime(final HttpURLConnection request, final OperationContext opContext) { - return request.getHeaderField("x-ms-lease-time"); - } - - /** - * Gets the snapshot ID from the request header. - * - * @param request - * The response from server. - * @param opContext - * a tracking object for the request - * @return the snapshot ID from the request header. - */ - public static String getSnapshotTime(final HttpURLConnection request, final OperationContext opContext) { - return request.getHeaderField("x-ms-snapshot"); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobType.java deleted file mode 100644 index 5cef258dde152..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlobType.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.Locale; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Specifies the type of a blob. - */ -public enum BlobType { - /** - * Specifies the blob type is not specified. - */ - UNSPECIFIED, - - /** - * Specifies the blob is a block blob. - */ - BLOCK_BLOB, - - /** - * Specifies the blob is a page blob. - */ - PAGE_BLOB; - - /** - * Returns the enum value representing the blob type for the specified string. - * - * @param typeString - * A String that represents a blob type, such as "blockblob" or "pageblob". - * - * @return A BlobType value corresponding to the string specified by typeString. - */ - public static BlobType parse(final String typeString) { - if (Utility.isNullOrEmpty(typeString)) { - return UNSPECIFIED; - } - else if ("blockblob".equals(typeString.toLowerCase(Locale.US))) { - return BLOCK_BLOB; - } - else if ("pageblob".equals(typeString.toLowerCase(Locale.US))) { - return PAGE_BLOB; - } - else { - return UNSPECIFIED; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockEntry.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockEntry.java deleted file mode 100644 index 5e01358333def..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockEntry.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * A class which is used to list and commit blocks of a {@link CloudBlockBlob}. - */ -public final class BlockEntry { - /** - * Represents the name of the block. - */ - private String id; - - /** - * Represents the size, in bytes, of the block. - */ - private long size; - - /** - * Represents the block search mode. The default value is {@link BlockSearchMode#LATEST}. - */ - public BlockSearchMode searchMode = BlockSearchMode.LATEST; - - /** - * Creates an instance of the BlockEntry class. - * - * @param id - * A String that represents the name of the block. - * @param searchMode - * A {@link BlockSearchMode} value that represents the block search mode. - */ - public BlockEntry(final String id, final BlockSearchMode searchMode) { - this.setId(id); - this.searchMode = searchMode; - } - - /** - * @return the id - */ - public String getId() { - return this.id; - } - - /** - * @return the size - */ - public long getSize() { - return this.size; - } - - /** - * @param id - * the id to set - */ - public void setId(final String id) { - this.id = id; - } - - /** - * @param size - * the size to set - */ - public void setSize(final long size) { - this.size = size; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockListingFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockListingFilter.java deleted file mode 100644 index 78295959d61c7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockListingFilter.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Specifies whether to list only committed blocks, only uncommitted blocks, or all blocks. - */ -public enum BlockListingFilter { - /** - * List only committed blocks. - */ - COMMITTED, - - /** - * List only uncommitted blocks. - */ - UNCOMMITTED, - - /** - * List both committed and uncommitted blocks. - */ - ALL -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockSearchMode.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockSearchMode.java deleted file mode 100644 index e96875f9ac376..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/BlockSearchMode.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Specifies which block lists should be searched to find a specified block. - */ -public enum BlockSearchMode { - /** - * Specifies searching only the committed block list. - */ - COMMITTED, - - /** - * Specifies searching only the uncommitted block list. - */ - UNCOMMITTED, - - /** - * Specifies searching the uncommitted block list first, and if the block is not found, then search the committed - * block list. - */ - LATEST -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlob.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlob.java deleted file mode 100644 index 578019fa34c03..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlob.java +++ /dev/null @@ -1,2563 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.core.storage.SharedAccessSignatureHelper; -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.LeaseStatus; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.RetryNoRetry; -import com.microsoft.windowsazure.services.core.storage.RetryPolicy; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.StorageExtendedErrorInformation; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.StreamMd5AndLength; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseResponse; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LeaseAction; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * - * Represents a Windows Azure blob. This is the base class for the {@link CloudBlockBlob} and {@link CloudPageBlob} - * classes. - */ -public abstract class CloudBlob implements ListBlobItem { - /** - * Holds the metadata for the blob. - */ - HashMap metadata; - - /** - * Holds the properties of the blob. - */ - BlobProperties properties; - - /** - * Holds the URI of the blob, Setting this is RESERVED for internal use. - */ - URI uri; - - /** - * Holds the snapshot ID. - */ - String snapshotID; - - /** - * Represents the state of the most recent or pending copy operation. - */ - CopyState copyState; - - /** - * Holds the Blobs container Reference. - */ - private CloudBlobContainer container; - - /** - * Represents the blob's directory. - */ - protected CloudBlobDirectory parent; - - /** - * Holds the Blobs Name. - */ - private String name; - - /** - * Represents the blob client. - */ - protected CloudBlobClient blobServiceClient; - - /** - * Creates an instance of the CloudBlob class. - * - * @param type - * the type of the blob. - */ - protected CloudBlob(final BlobType type) { - this.metadata = new HashMap(); - this.properties = new BlobProperties(type); - } - - /** - * Creates an instance of the CloudBlob class using the specified URI and cloud blob client. - * - * @param type - * the type of the blob. - * @param uri - * A java.net.URI object that represents the URI to the blob, beginning with the container - * name. - * @param client - * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. - * - * @throws StorageException - * If a storage service error occurred. - */ - protected CloudBlob(final BlobType type, final URI uri, final CloudBlobClient client) throws StorageException { - this(type); - - Utility.assertNotNull("blobAbsoluteUri", uri); - - this.blobServiceClient = client; - this.uri = uri; - - this.parseURIQueryStringAndVerify(uri, client, client.isUsePathStyleUris()); - } - - /** - * Creates an instance of the CloudBlob class using the specified URI, cloud blob client, and cloud - * blob container. - * - * @param type - * the type of the blob. - * @param uri - * A java.net.URI object that represents the absolute URI to the blob, beginning with the - * container name. - * @param client - * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. - * @param container - * A {@link CloudBlobContainer} object that represents the container to use for the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - protected CloudBlob(final BlobType type, final URI uri, final CloudBlobClient client, - final CloudBlobContainer container) throws StorageException { - this(type, uri, client); - this.container = container; - } - - /** - * Creates an instance of the CloudBlob class using the specified URI, snapshot ID, and cloud blob - * client. - * - * @param type - * the type of the blob. - * @param uri - * A java.net.URI object that represents the absolute URI to the blob, beginning with the - * container name. - * @param snapshotID - * A String that represents the snapshot version, if applicable. - * @param client - * A {@link CloudBlobContainer} object that represents the container to use for the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - protected CloudBlob(final BlobType type, final URI uri, final String snapshotID, final CloudBlobClient client) - throws StorageException { - this(type, uri, client); - if (snapshotID != null) { - if (this.snapshotID != null) { - throw new IllegalArgumentException( - "Snapshot query parameter is already defined in the blobUri. Either pass in a snapshotTime parameter or use a full URL with a snapshot query parameter."); - } - else { - this.snapshotID = snapshotID; - } - } - } - - /** - * Creates an instance of the CloudBlob class by copying values from another blob. - * - * @param otherBlob - * A CloudBlob object that represents the blob to copy. - */ - protected CloudBlob(final CloudBlob otherBlob) { - this.metadata = new HashMap(); - this.properties = new BlobProperties(otherBlob.properties); - - if (otherBlob.metadata != null) { - this.metadata = new HashMap(); - for (final String key : otherBlob.metadata.keySet()) { - this.metadata.put(key, otherBlob.metadata.get(key)); - } - } - - this.snapshotID = otherBlob.snapshotID; - this.uri = otherBlob.uri; - this.container = otherBlob.container; - this.parent = otherBlob.parent; - this.blobServiceClient = otherBlob.blobServiceClient; - this.name = otherBlob.name; - this.copyState = otherBlob.copyState; - } - - /** - * Acquires a new lease on the blob with the specified lease time and proposed lease ID. - * - * @param leaseTimeInSeconds - * Specifies the span of time for which to acquire the lease, in seconds. - * If null, an infinite lease will be acquired. If not null, the value must be greater than - * zero. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @return A String that represents the lease ID. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId) - throws StorageException { - return this.acquireLease(leaseTimeInSeconds, proposedLeaseId, null, null, null); - } - - /** - * Acquires a new lease on the blob with the specified lease time, proposed lease ID, request - * options, and operation context. - * - * @param leaseTimeInSeconds - * Specifies the span of time for which to acquire the lease, in seconds. - * If null, an infinite lease will be acquired. If not null, the value must be greater than - * zero. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A String that represents the lease ID. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId, - final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public String execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.ACQUIRE, leaseTimeInSeconds, - proposedLeaseId, null, accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.properties.setLeaseStatus(LeaseStatus.LOCKED); - - return BlobResponse.getLeaseID(request, opContext); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Asserts that the blob has the correct blob type specified in the blob attributes. - * - * @throws StorageException - * If an incorrect blob type is used. - */ - protected final void assertCorrectBlobType() throws StorageException { - if (this instanceof CloudBlockBlob && this.properties.getBlobType() != BlobType.BLOCK_BLOB) { - throw new StorageException( - StorageErrorCodeStrings.INCORRECT_BLOB_TYPE, - String.format( - "Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s", - BlobType.BLOCK_BLOB, this.properties.getBlobType()), - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - if (this instanceof CloudPageBlob && this.properties.getBlobType() != BlobType.PAGE_BLOB) { - throw new StorageException( - StorageErrorCodeStrings.INCORRECT_BLOB_TYPE, - String.format( - "Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s", - BlobType.PAGE_BLOB, this.properties.getBlobType()), - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - - } - } - - /** - * Breaks the lease and ensures that another client cannot acquire a new lease until the current lease period - * has expired. - * - * @param breakPeriodInSeconds - * Specifies the time to wait, in seconds, until the current lease is broken. - * If null, the break period is the remainder of the current lease, or zero for infinite leases. - * - * @return The time, in seconds, remaining in the lease period. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final long breakLease(final Integer breakPeriodInSeconds) throws StorageException { - return this.breakLease(breakPeriodInSeconds, null, null, null); - } - - /** - * Breaks the existing lease, using the specified request options and operation context, and ensures that another - * client cannot acquire a new lease until the current lease period has expired. - * - * @param breakPeriodInSeconds - * Specifies the time to wait, in seconds, until the current lease is broken. - * If null, the break period is the remainder of the current lease, or zero for infinite leases. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return The time, in seconds, remaining in the lease period. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final long breakLease(final Integer breakPeriodInSeconds, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Long execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.BREAK, null, null, - breakPeriodInSeconds, accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return -1L; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - final String leaseTime = BlobResponse.getLeaseTime(request, opContext); - - blob.properties.setLeaseStatus(LeaseStatus.UNLOCKED); - return Utility.isNullOrEmpty(leaseTime) ? -1L : Long.parseLong(leaseTime); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Copies an existing blob's contents, properties, and metadata to this instance of the CloudBlob - * class. - * - * @param sourceBlob - * A CloudBlob object that represents the source blob to copy. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - */ - @DoesServiceRequest - public final void copyFromBlob(final CloudBlob sourceBlob) throws StorageException, URISyntaxException { - this.copyFromBlob(sourceBlob, null, null, null, null); - } - - /** - * Copies an existing blob's contents, properties, and metadata to this instance of the CloudBlob - * class, using the specified access conditions, lease ID, request options, and operation context. - * - * @param sourceBlob - * A CloudBlob object that represents the source blob to copy. - * @param sourceAccessCondition - * An {@link AccessCondition} object that represents the access conditions for the source blob. - * @param destinationAccessCondition - * An {@link AccessCondition} object that represents the access conditions for the destination blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * - */ - @DoesServiceRequest - public final void copyFromBlob(final CloudBlob sourceBlob, final AccessCondition sourceAccessCondition, - final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException, URISyntaxException { - this.copyFromBlob(sourceBlob.uri, sourceAccessCondition, destinationAccessCondition, options, opContext); - - } - - /** - * Copies an existing blob's contents, properties, and metadata to this instance of the CloudBlob - * class. - * - * @param source - * A URI The URI of a source blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void copyFromBlob(final URI source) throws StorageException { - this.copyFromBlob(source, null, null, null, null); - } - - /** - * Copies an existing blob's contents, properties, and metadata to a new blob, using the specified access - * conditions, lease ID, request options, and operation context. - * - * @param source - * A URI The URI of a source blob. - * @param sourceAccessCondition - * An {@link AccessCondition} object that represents the access conditions for the source blob. - * @param destinationAccessCondition - * An {@link AccessCondition} object that represents the access conditions for the destination blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - * - */ - @DoesServiceRequest - public final void copyFromBlob(final URI source, final AccessCondition sourceAccessCondition, - final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.copyFrom(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), source.toString(), blob.snapshotID, - sourceAccessCondition, destinationAccessCondition, blobOptions, opContext); - this.setConnection(request); - - BlobRequest.addMetadata(request, blob.metadata, opContext); - - this.signRequest(client, request, 0, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - blob.copyState = BaseResponse.getCopyState(request); - - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Aborts an ongoing blob copy operation. - * - * @param copyId - * A String object that identifying the copy operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void abortCopy(final String copyId) throws StorageException { - this.abortCopy(copyId, null, null, null); - } - - /** - * Aborts an ongoing blob copy operation. - * - * @param copyId - * A String object that identifying the copy operation. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - * - */ - @DoesServiceRequest - public final void abortCopy(final String copyId, final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.abortCopy(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), copyId, accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Creates a snapshot of the blob. - * - * @return A CloudBlob object that represents the snapshot of the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final CloudBlob createSnapshot() throws StorageException { - return this.createSnapshot(null, null, null); - } - - /** - * Creates a snapshot of the blob using the specified request options and operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A CloudBlob object that represents the snapshot of the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final CloudBlob createSnapshot(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public CloudBlob execute(final CloudBlobClient client, final CloudBlob blob, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.snapshot(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - CloudBlob snapshot = null; - final String snapshotTime = BlobResponse.getSnapshotTime(request, opContext); - if (blob instanceof CloudBlockBlob) { - snapshot = new CloudBlockBlob(blob.getUri(), snapshotTime, client); - } - else if (blob instanceof CloudPageBlob) { - snapshot = new CloudPageBlob(blob.getUri(), snapshotTime, client); - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return snapshot; - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Deletes the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void delete() throws StorageException { - this.delete(DeleteSnapshotsOption.NONE, null, null, null); - } - - /** - * Deletes the blob using the specified snapshot and request options, and operation context. - *

- * A blob that has snapshots cannot be deleted unless the snapshots are also deleted. If a blob has snapshots, use - * the {@link DeleteSnapshotsOption#DELETE_SNAPSHOTS_ONLY} or {@link DeleteSnapshotsOption#INCLUDE_SNAPSHOTS} value - * in the deleteSnapshotsOption parameter to specify how the snapshots should be handled when the blob - * is deleted. - * - * @param deleteSnapshotsOption - * A {@link DeleteSnapshotsOption} object that indicates whether to delete only blobs, only snapshots, or - * both. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void delete(final DeleteSnapshotsOption deleteSnapshotsOption, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException { - Utility.assertNotNull("deleteSnapshotsOption", deleteSnapshotsOption); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.delete(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, deleteSnapshotsOption, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Deletes the blob if it exists. - *

- * A blob that has snapshots cannot be deleted unless the snapshots are also deleted. If a blob has snapshots, use - * the {@link DeleteSnapshotsOption#DELETE_SNAPSHOTS_ONLY} or {@link DeleteSnapshotsOption#INCLUDE_SNAPSHOTS} value - * in the deleteSnapshotsOption parameter to specify how the snapshots should be handled when the blob - * is deleted. - * - * @return true if the blob was deleted; otherwise, false. - * - * @throws StorageException - * If a storage service error occurred. - * - */ - @DoesServiceRequest - public final boolean deleteIfExists() throws StorageException { - return this.deleteIfExists(DeleteSnapshotsOption.NONE, null, null, null); - } - - /** - * Deletes the blob if it exists, using the specified snapshot and request options, and operation context. - *

- * A blob that has snapshots cannot be deleted unless the snapshots are also deleted. If a blob has snapshots, use - * the {@link DeleteSnapshotsOption#DELETE_SNAPSHOTS_ONLY} or {@link DeleteSnapshotsOption#INCLUDE_SNAPSHOTS} value - * in the deleteSnapshotsOption parameter to specify how the snapshots should be handled when the blob - * is deleted. - * - * @param deleteSnapshotsOption - * A {@link DeleteSnapshotsOption} object that indicates whether to delete only blobs, only snapshots, or - * both. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return true if the blob was deleted; otherwise, false - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final boolean deleteIfExists(final DeleteSnapshotsOption deleteSnapshotsOption, - final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException { - Utility.assertNotNull("deleteSnapshotsOption", deleteSnapshotsOption); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Boolean execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.delete(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, deleteSnapshotsOption, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_ACCEPTED) { - return true; - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return false; - } - else { - this.setNonExceptionedRetryableFailure(true); - - // return false instead of null to avoid SCA issues - return false; - } - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Downloads the contents of a blob to a stream. - * - * @param outStream - * An OutputStream object that represents the target stream. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void download(final OutputStream outStream) throws StorageException, IOException { - this.download(outStream, null, null, null); - } - - /** - * Downloads the contents of a blob to a stream using the specified request options and operation context. - * - * @param outStream - * An OutputStream object that represents the target stream. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void download(final OutputStream outStream, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.get(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - final InputStream streamRef = ExecutionEngine.getInputStream(request, opContext, this.getResult()); - - final String contentMD5 = request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); - final Boolean validateMD5 = !blobOptions.getDisableContentMD5Validation() - && !Utility.isNullOrEmpty(contentMD5); - - final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); - final long expectedLength = Long.parseLong(contentLength); - - final BlobAttributes retrievedAttributes = BlobResponse.getAttributes(request, blob.getUri(), - blob.snapshotID, opContext); - blob.properties = retrievedAttributes.getProperties(); - blob.metadata = retrievedAttributes.getMetadata(); - blob.copyState = retrievedAttributes.getCopyState(); - ExecutionEngine.getResponseCode(this.getResult(), request, opContext); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, - validateMD5, this.getResult(), opContext); - - if (descriptor.getLength() != expectedLength) { - throw new StorageException( - StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, - "An incorrect number of bytes was read from the connection. The connection may have been closed", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - if (validateMD5 && !contentMD5.equals(descriptor.getMd5())) { - throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( - "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", - contentMD5, descriptor.getMd5()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - return null; - } - }; - - try { - // Executed with no retries so that the first failure will move out - // to the read Stream. - ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, RetryNoRetry.getInstance(), opContext); - opContext.setIntermediateMD5(null); - } - catch (final StorageException ex) { - // Check if users has any retries specified, Or if the exception is retryable - final RetryPolicy dummyPolicy = options.getRetryPolicyFactory().createInstance(opContext); - if ((ex.getHttpStatusCode() == Constants.HeaderConstants.HTTP_UNUSED_306 && !ex.getErrorCode().equals( - StorageErrorCodeStrings.OUT_OF_RANGE_INPUT)) - || ex.getHttpStatusCode() == HttpURLConnection.HTTP_PRECON_FAILED - || !dummyPolicy.shouldRetry(0, impl.getResult().getStatusCode(), (Exception) ex.getCause(), - opContext).isShouldRetry()) { - opContext.setIntermediateMD5(null); - throw ex; - } - - // Continuation, fail gracefully into a read stream. This needs to - // be outside the operation above as it would get retried resulting - // in a nested retry - - // Copy access condition, and update etag. This will potentially replace the if match value, but not on the - // users object. - - AccessCondition etagLockCondition = new AccessCondition(); - etagLockCondition.setIfMatch(this.getProperties().getEtag()); - if (accessCondition != null) { - etagLockCondition.setLeaseID(accessCondition.getLeaseID()); - } - - // 1. Open Read Stream - final BlobInputStream streamRef = this.openInputStream(etagLockCondition, options, opContext); - - // Cache value indicating if we need - final boolean validateMd5 = streamRef.getValidateBlobMd5(); - - streamRef.setValidateBlobMd5(false); - streamRef.mark(Integer.MAX_VALUE); - - try { - // 2. Seek to current position, this will disable read streams - // internal content md5 checks. - if (opContext.getCurrentOperationByteCount() > 0) { - // SCA will say this if a failure as we do not validate the - // return of skip. - // The Blob class repositioning a virtual pointer and will - // always skip the correct - // number of bytes. - streamRef.skip(opContext.getCurrentOperationByteCount()); - } - - // 3. Continue copying - final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, - validateMd5, null, opContext); - - if (validateMd5 && !this.properties.getContentMD5().equals(descriptor.getMd5())) { - throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( - "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", - this.properties.getContentMD5(), descriptor.getMd5()), - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - catch (final IOException secondEx) { - opContext.setIntermediateMD5(null); - if (secondEx.getCause() != null && secondEx.getCause() instanceof StorageException) { - throw (StorageException) secondEx.getCause(); - } - else { - throw secondEx; - } - } - } - } - - /** - * Populates a blob's properties and metadata. - *

- * This method populates the blob's system properties and user-defined metadata. Before reading a blob's properties - * or metadata, call this method or its overload to retrieve the latest values for the blob's properties and - * metadata from the Windows Azure storage service. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void downloadAttributes() throws StorageException { - this.downloadAttributes(null, null, null); - } - - /** - * Populates a blob's properties and metadata using the specified request options and operation context. - *

- * This method populates the blob's system properties and user-defined metadata. Before reading a blob's properties - * or metadata, call this method or its overload to retrieve the latest values for the blob's properties and - * metadata from the Windows Azure storage service. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void downloadAttributes(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.getProperties(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, - opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - // Set attributes - final BlobAttributes retrievedAttributes = BlobResponse.getAttributes(request, blob.getUri(), - blob.snapshotID, opContext); - - if (retrievedAttributes.getProperties().getBlobType() != blob.properties.getBlobType()) { - throw new StorageException( - StorageErrorCodeStrings.INCORRECT_BLOB_TYPE, - String.format( - "Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s", - blob.properties.getBlobType(), retrievedAttributes.getProperties().getBlobType()), - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - blob.properties = retrievedAttributes.getProperties(); - blob.metadata = retrievedAttributes.getMetadata(); - blob.copyState = retrievedAttributes.getCopyState(); - - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Downloads a range of bytes from the blob to the given byte buffer. - * - * @param offset - * The byte offset to use as the starting point for the source. - * @param length - * The number of bytes to read. - * @param buffer - * The byte buffer, as an array of bytes, to which the blob bytes are downloaded. - * @param bufferOffet - * The byte offset to use as the starting point for the target. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void downloadRange(final long offset, final int length, final byte[] buffer, final int bufferOffet) - throws StorageException { - this.downloadRangeInternal(offset, length, buffer, bufferOffet, null, null, null); - } - - /** - * Downloads a range of bytes from the blob to the given byte buffer, using the specified request options and - * operation context. - * - * @param offset - * The byte offset to use as the starting point for the source. - * @param length - * The number of bytes to read. - * @param buffer - * The byte buffer, as an array of bytes, to which the blob bytes are downloaded. - * @param bufferOffet - * The byte offset to use as the starting point for the target. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void downloadRange(final long offset, final int length, final byte[] buffer, final int bufferOffet, - final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext) - throws StorageException { - if (offset < 0 || length <= 0) { - throw new IndexOutOfBoundsException(); - } - - Utility.assertNotNull("buffer", buffer); - - if (length + bufferOffet > buffer.length) { - throw new IndexOutOfBoundsException(); - } - - opContext.initialize(); - this.downloadRangeInternal(offset, length, buffer, bufferOffet, accessCondition, options, opContext); - } - - /** - * Downloads a range of bytes from the blob to the given byte buffer. - * - * @param blobOffset - * the offset of the blob to begin downloading at - * @param length - * the number of bytes to read - * @param buffer - * the byte buffer to write to. - * @param bufferOffset - * the offset in the byte buffer to begin writing. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * An object that specifies any additional options for the request - * @param opContext - * an object used to track the execution of the operation - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - @DoesServiceRequest - protected final void downloadRangeInternal(final long blobOffset, final int length, final byte[] buffer, - final int bufferOffset, final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (blobOffset < 0 || length <= 0) { - throw new IndexOutOfBoundsException(); - } - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - - if (options.getUseTransactionalContentMD5() && length > 4 * Constants.MB) { - throw new IllegalArgumentException( - "Cannot specify x-ms-range-get-content-md5 header on ranges larger than 4 MB. Either use a BlobReadStream via openRead, or disable TransactionalMD5 checking via the BlobRequestOptions."); - } - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.get(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, blobOffset, length, accessCondition, - blobOptions, opContext); - this.setConnection(request); - - if (blobOptions.getUseTransactionalContentMD5()) { - request.setRequestProperty(Constants.HeaderConstants.RANGE_GET_CONTENT_MD5, "true"); - } - - this.signRequest(client, request, -1L, null); - - final InputStream sourceStream = ExecutionEngine.getInputStream(request, opContext, this.getResult()); - - int totalRead = 0; - int nextRead = buffer.length - bufferOffset; - int count = sourceStream.read(buffer, bufferOffset, nextRead); - - while (count > 0) { - totalRead += count; - nextRead = buffer.length - (bufferOffset + totalRead); - - if (nextRead == 0) { - // check for case where more data is returned - if (sourceStream.read(new byte[1], 0, 1) != -1) { - throw new StorageException( - StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, - "An incorrect number of bytes was read from the connection. The connection may have been closed", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - count = sourceStream.read(buffer, bufferOffset + totalRead, nextRead); - } - - ExecutionEngine.getResponseCode(this.getResult(), request, opContext); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_PARTIAL) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - // Do not update blob length and Content-MD5 in downloadRangeInternal API. - final long originalBlobLength = blob.properties.getLength(); - final String originalContentMD5 = blob.properties.getContentMD5(); - final BlobAttributes retrievedAttributes = BlobResponse.getAttributes(request, blob.getUri(), - blob.snapshotID, opContext); - blob.properties = retrievedAttributes.getProperties(); - blob.metadata = retrievedAttributes.getMetadata(); - blob.copyState = retrievedAttributes.getCopyState(); - blob.properties.setContentMD5(originalContentMD5); - blob.properties.setLength(originalBlobLength); - - final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); - final long expectedLength = Long.parseLong(contentLength); - if (totalRead != expectedLength) { - throw new StorageException( - StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, - "An incorrect number of bytes was read from the connection. The connection may have been closed", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - if (blobOptions.getUseTransactionalContentMD5()) { - final String contentMD5 = request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); - - try { - final MessageDigest digest = MessageDigest.getInstance("MD5"); - digest.update(buffer, bufferOffset, length); - final String calculatedMD5 = Base64.encode(digest.digest()); - if (!contentMD5.equals(calculatedMD5)) { - throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( - "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", - contentMD5, calculatedMD5), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - catch (final NoSuchAlgorithmException e) { - // This wont happen, throw fatal. - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Checks to see if the blob exists. - * - * @return true if the blob exists, other wise false. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final boolean exists() throws StorageException { - return this.exists(null, null, null); - } - - /** - * Checks to see if the blob exists, using the specified request options and operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return true if the blob exists, other wise false. - * - * @throws StorageException - * f a storage service error occurred. - */ - @DoesServiceRequest - public final boolean exists(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Boolean execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.getProperties(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, - opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { - final BlobAttributes retrievedAttributes = BlobResponse.getAttributes(request, blob.getUri(), - blob.snapshotID, opContext); - blob.properties = retrievedAttributes.getProperties(); - blob.metadata = retrievedAttributes.getMetadata(); - blob.copyState = retrievedAttributes.getCopyState(); - return Boolean.valueOf(true); - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return Boolean.valueOf(false); - } - else { - this.setNonExceptionedRetryableFailure(true); - - // return false instead of null to avoid SCA issues - return false; - } - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Returns a shared access signature for the blob using the specified group policy identifier and operation context. - * Note this does not contain the leading "?". - * - * @param policy - * A SharedAccessPolicy object that represents the access policy for the shared access - * signature. - * @param groupPolicyIdentifier - * A String that represents the container-level access policy. - * - * @return A String that represents the shared access signature. - * - * @throws IllegalArgumentException - * If the credentials are invalid or the blob is a snapshot. - * @throws InvalidKeyException - * If the credentials are invalid. - * @throws StorageException - * If a storage service error occurred. - */ - public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier) - throws InvalidKeyException, StorageException { - - if (!this.blobServiceClient.getCredentials().canCredentialsSignRequest()) { - throw new IllegalArgumentException( - "Cannot create Shared Access Signature unless the Account Key credentials are used by the BlobServiceClient."); - } - - if (this.isSnapshot()) { - throw new IllegalArgumentException( - "Cannot create Shared Access Signature for snapshots. Perform the operation on the root blob instead."); - } - - final String resourceName = this.getCanonicalName(true); - - final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHash(policy, - groupPolicyIdentifier, resourceName, this.blobServiceClient, null); - - final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignature(policy, - groupPolicyIdentifier, "b", signature); - - return builder.toString(); - } - - /** - * Returns the canonical name of the blob in the format of - * /<account-name>/<container-name>/<blob-name>. - *

- * This format is used by both Shared Access and Copy blob operations. - * - * @param ignoreSnapshotTime - * true if the snapshot time is ignored; otherwise, false. - * - * @return The canonical name in the format of /<account-name>/<container - * -name>/<blob-name>. - */ - String getCanonicalName(final boolean ignoreSnapshotTime) { - String canonicalName; - if (this.blobServiceClient.isUsePathStyleUris()) { - canonicalName = this.getUri().getRawPath(); - } - else { - canonicalName = PathUtility.getCanonicalPathFromCredentials(this.blobServiceClient.getCredentials(), this - .getUri().getRawPath()); - } - - if (!ignoreSnapshotTime && this.snapshotID != null) { - canonicalName = canonicalName.concat("?snapshot="); - canonicalName = canonicalName.concat(this.snapshotID); - } - - return canonicalName; - } - - /** - * Returns the blob's container. - * - * @return A {@link CloudBlobContainer} object that represents the container of the blob. - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @Override - public final CloudBlobContainer getContainer() throws StorageException, URISyntaxException { - if (this.container == null) { - final URI containerURI = PathUtility.getContainerURI(this.getUri(), - this.blobServiceClient.isUsePathStyleUris()); - this.container = new CloudBlobContainer(containerURI, this.blobServiceClient); - } - - return this.container; - } - - /** - * Returns the metadata for the blob. - * - * @return A java.util.HashMap object that represents the metadata for the blob. - */ - public final HashMap getMetadata() { - return this.metadata; - } - - /** - * Returns the name of the blob. - * - * @return A String that represents the name of the blob. - * - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public final String getName() throws URISyntaxException { - if (Utility.isNullOrEmpty(this.name)) { - this.name = PathUtility.getBlobNameFromURI(this.getUri(), this.blobServiceClient.isUsePathStyleUris()); - } - return this.name; - } - - /** - * Returns the blob item's parent. - * - * @return A {@link CloudBlobDirectory} object that represents the parent directory for the blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @Override - public final CloudBlobDirectory getParent() throws URISyntaxException, StorageException { - if (this.parent == null) { - final URI parentURI = PathUtility.getParentAddress(this.getUri(), - this.blobServiceClient.getDirectoryDelimiter(), this.blobServiceClient.isUsePathStyleUris()); - this.parent = new CloudBlobDirectory(parentURI, null, this.blobServiceClient); - } - return this.parent; - } - - /** - * Returns the blob's properties. - * - * @return A {@link BlobProperties} object that represents the properties of the blob. - */ - public final BlobProperties getProperties() { - return this.properties; - } - - /** - * Returns the blob's copy state. - * - * @return A {@link CopyState} object that represents the copy state of the blob. - */ - public CopyState getCopyState() { - return this.copyState; - } - - /** - * Returns the snapshot or shared access signature qualified URI for this blob. - * - * @return A java.net.URI object that represents the snapshot or shared access signature. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public final URI getQualifiedUri() throws URISyntaxException, StorageException { - if (this.isSnapshot()) { - return PathUtility.addToQuery(this.getUri(), String.format("snapshot=%s", this.snapshotID)); - } - else if (this.blobServiceClient.getCredentials() instanceof StorageCredentialsSharedAccessSignature) { - return this.blobServiceClient.getCredentials().transformUri(this.getUri()); - } - else { - return this.getUri(); - } - } - - /** - * Returns the Blob service client associated with the blob. - * - * @return A {@link CloudBlobClient} object that represents the client. - */ - public final CloudBlobClient getServiceClient() { - return this.blobServiceClient; - } - - /** - * Gets the Blob Snapshot ID. - * - * @return the Blob Snapshot ID. - */ - public final String getSnapshotID() { - return this.snapshotID; - } - - /** - * Returns the transformed URI for the resource if the given credentials require transformation. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A java.net.URI object that represents the transformed URI. - * - * @throws IllegalArgumentException - * If the URI is not absolute. - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - protected final URI getTransformedAddress(final OperationContext opContext) throws URISyntaxException, - StorageException { - if (this.blobServiceClient.getCredentials().doCredentialsNeedTransformUri()) { - if (this.getUri().isAbsolute()) { - return this.blobServiceClient.getCredentials().transformUri(this.getUri(), opContext); - } - else { - final StorageException ex = Utility.generateNewUnexpectedStorageException(null); - ex.getExtendedErrorInformation().setErrorMessage("Blob Object relative URIs not supported."); - throw ex; - } - } - else { - return this.getUri(); - } - } - - /** - * Returns the URI for this blob. - * - * @return A java.net.URI object that represents the URI for the blob. - */ - @Override - public final URI getUri() { - return this.uri; - } - - /** - * Indicates whether this blob is a snapshot. - * - * @return true if the blob is a snapshot, otherwise false. - * - * @see DeleteSnapshotsOption - */ - public final boolean isSnapshot() { - return this.snapshotID != null; - } - - /** - * Opens a blob input stream to download the blob. - *

- * Use {@link CloudBlobClient#setStreamMinimumReadSizeInBytes} to configure the read size. - * - * @return An InputStream object that represents the stream to use for reading from the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final BlobInputStream openInputStream() throws StorageException { - return this.openInputStream(null, null, null); - } - - /** - * Opens a blob input stream to download the blob using the specified request options and operation context. - *

- * Use {@link CloudBlobClient#setStreamMinimumReadSizeInBytes} to configure the read size. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An InputStream object that represents the stream to use for reading from the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final BlobInputStream openInputStream(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - assertNoWriteOperationForSnapshot(); - - options.applyDefaults(this.blobServiceClient); - - return new BlobInputStream(this, accessCondition, options, opContext); - } - - /** - * Parse Uri for SAS (Shared access signature) information. - * - * Validate that no other query parameters are passed in. Any SAS information will be recorded as corresponding - * credentials instance. If existingClient is passed in, any SAS information found will not be supported. Otherwise - * a new client is created based on SAS information or as anonymous credentials. - * - * @param completeUri - * The complete Uri. - * @param existingClient - * The client to use. - * @param usePathStyleUris - * If true, path style Uris are used. - * @throws StorageException - * If a storage service error occurred. - * */ - protected void parseURIQueryStringAndVerify(final URI completeUri, final CloudBlobClient existingClient, - final boolean usePathStyleUris) throws StorageException { - Utility.assertNotNull("resourceUri", completeUri); - - if (!completeUri.isAbsolute()) { - final String errorMessage = String.format( - "Address '%s' is not an absolute address. Relative addresses are not permitted in here.", - completeUri.toString()); - throw new IllegalArgumentException(errorMessage); - } - - this.uri = PathUtility.stripURIQueryAndFragment(completeUri); - - final HashMap queryParameters = PathUtility.parseQueryString(completeUri.getQuery()); - - final StorageCredentialsSharedAccessSignature sasCreds = SharedAccessSignatureHelper - .parseQuery(queryParameters); - - final String[] snapshotIDs = queryParameters.get(BlobConstants.SNAPSHOT); - if (snapshotIDs != null && snapshotIDs.length > 0) { - this.snapshotID = snapshotIDs[0]; - } - - if (sasCreds == null) { - return; - } - - final Boolean sameCredentials = existingClient == null ? false : Utility.areCredentialsEqual(sasCreds, - existingClient.getCredentials()); - - if (existingClient == null || !sameCredentials) { - try { - this.blobServiceClient = new CloudBlobClient(new URI(PathUtility.getServiceClientBaseAddress( - this.getUri(), usePathStyleUris)), sasCreds); - } - catch (final URISyntaxException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - if (existingClient != null && !sameCredentials) { - this.blobServiceClient - .setPageBlobStreamWriteSizeInBytes(existingClient.getPageBlobStreamWriteSizeInBytes()); - this.blobServiceClient.setSingleBlobPutThresholdInBytes(existingClient.getSingleBlobPutThresholdInBytes()); - this.blobServiceClient.setStreamMinimumReadSizeInBytes(existingClient.getStreamMinimumReadSizeInBytes()); - this.blobServiceClient.setWriteBlockSizeInBytes(existingClient.getWriteBlockSizeInBytes()); - this.blobServiceClient.setConcurrentRequestCount(existingClient.getConcurrentRequestCount()); - this.blobServiceClient.setDirectoryDelimiter(existingClient.getDirectoryDelimiter()); - this.blobServiceClient.setRetryPolicyFactory(existingClient.getRetryPolicyFactory()); - this.blobServiceClient.setTimeoutInMs(existingClient.getTimeoutInMs()); - } - } - - void updateEtagAndLastModifiedFromResponse(HttpURLConnection request) { - String tempStr = request.getHeaderField(Constants.HeaderConstants.ETAG); - - // ETag - if (!Utility.isNullOrEmpty(tempStr)) { - this.getProperties().setEtag(tempStr); - } - - // Last Modified - if (0 != request.getLastModified()) { - final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US); - lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE); - lastModifiedCalendar.setTime(new Date(request.getLastModified())); - this.getProperties().setLastModified(lastModifiedCalendar.getTime()); - } - - } - - void updateLengthFromResponse(HttpURLConnection request) { - final String xContentLengthHeader = request.getHeaderField(BlobConstants.CONTENT_LENGTH_HEADER); - if (!Utility.isNullOrEmpty(xContentLengthHeader)) { - this.getProperties().setLength(Long.parseLong(xContentLengthHeader)); - } - } - - /** - * Releases the lease on the blob. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The LeaseID is - * required to be set on the AccessCondition. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void releaseLease(final AccessCondition accessCondition) throws StorageException { - this.releaseLease(accessCondition, null, null); - } - - /** - * Releases the lease on the blob using the specified request options and operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob.The LeaseID is - * required to be set on the AccessCondition. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void releaseLease(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - Utility.assertNotNull("accessCondition", accessCondition); - Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.RELEASE, null, null, null, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - blob.properties.setLeaseStatus(LeaseStatus.UNLOCKED); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Renews an existing lease. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The LeaseID is - * required to be set on the AccessCondition. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void renewLease(final AccessCondition accessCondition) throws StorageException { - this.renewLease(accessCondition, null, null); - } - - /** - * Renews an existing lease using the specified request options and operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The LeaseID is - * required to be set on the AccessCondition. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void renewLease(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - Utility.assertNotNull("accessCondition", accessCondition); - Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.RENEW, null, null, null, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Changes the existing lease ID to the proposed lease ID. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is - * required to be set with an access condition. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void changeLease(final String proposedLeaseId, final AccessCondition accessCondition) - throws StorageException { - this.changeLease(proposedLeaseId, accessCondition, null, null); - } - - /** - * Changes the existing lease ID to the proposed lease Id with the specified access conditions, request options, - * and operation context. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is - * required to be set with an access condition. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void changeLease(final String proposedLeaseId, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException { - Utility.assertNotNull("accessCondition", accessCondition); - Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.CHANGE, null, proposedLeaseId, null, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Sets the container for the blob. - * - * @param container - * A {@link CloudBlobContainer} object that represents the container being assigned to the blob. - */ - protected final void setContainer(final CloudBlobContainer container) { - this.container = container; - } - - /** - * Sets the metadata for the blob. - * - * @param metadata - * A java.util.HashMap object that contains the metadata being assigned to the blob. - */ - public final void setMetadata(final HashMap metadata) { - this.metadata = metadata; - } - - /** - * Sets the properties for the blob. - * - * @param properties - * A {@link BlobProperties} object that represents the properties being assigned to the blob. - */ - protected final void setProperties(final BlobProperties properties) { - this.properties = properties; - } - - /** - * Reserved for internal use. - * - * @param copyState - * the copyState to set - */ - public void setCopyState(final CopyState copyState) { - this.copyState = copyState; - } - - /** - * Sets the blob snapshot ID. - * - * @param snapshotID - * A String that represents the snapshot ID being assigned to the blob. - */ - public final void setSnapshotID(final String snapshotID) { - this.snapshotID = snapshotID; - } - - /** - * Attempts to break the lease and ensure that another client cannot acquire a new lease until the current lease - * period has expired. - * - * @return Time, in seconds, remaining in the lease period, or -1 if the lease is already broken. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final long tryBreakLease() throws StorageException { - return this.tryBreakLease(null, null, null); - } - - /** - * Attempts to breaks the lease using the specified request options and operation context, and ensure that another - * client cannot acquire a new lease until the current lease period has expired. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return Time, in seconds, remaining in the lease period, -1 if the lease is already broken. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final long tryBreakLease(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Long execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.BREAK, null, null, null, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - final StorageException potentialConflictException = StorageException.translateException(request, - null, opContext); - - StorageExtendedErrorInformation extendedInfo = potentialConflictException - .getExtendedErrorInformation(); - - if (extendedInfo == null) { - // If we cant validate the error then the error must be surfaced to the user. - throw potentialConflictException; - } - - if (!extendedInfo.getErrorCode().equals(StorageErrorCodeStrings.LEASE_ALREADY_BROKEN)) { - this.setException(potentialConflictException); - this.setNonExceptionedRetryableFailure(true); - } - - return -1L; - } - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return -1L; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - final String leaseTime = BlobResponse.getLeaseTime(request, opContext); - - return Utility.isNullOrEmpty(leaseTime) ? -1L : Long.parseLong(leaseTime); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Uploads the source stream data to the blob. - * - * @param sourceStream - * An InputStream object that represents the source stream to upload. - * - * @param length - * The length of the stream data in bytes, or -1 if unknown. The length must be greater than zero and a - * multiple of 512 for page blobs. - * - * @throws IOException - * If an I/O exception occurred. - * - * @throws StorageException - * If a storage service error occurred. - * - */ - @DoesServiceRequest - public abstract void upload(InputStream sourceStream, long length) throws StorageException, IOException; - - /** - * Uploads the source stream data to the blob using the specified lease ID, request options, and operation context. - * - * @param sourceStream - * An InputStream object that represents the source stream to upload. - * @param length - * The length of the stream data in bytes, or -1 if unknown. The length must be greater than zero and a - * multiple of 512 for page blobs. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public abstract void upload(InputStream sourceStream, long length, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException; - - /** - * Uploads a blob in a single operation. - * - * @param sourceStream - * A InputStream object that represents the source stream to upload. - * @param length - * The length, in bytes, of the stream, or -1 if unknown. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - protected final void uploadFullBlob(final InputStream sourceStream, final long length, - final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext) - throws StorageException, IOException { - assertNoWriteOperationForSnapshot(); - - // Mark sourceStream for current position. - sourceStream.mark(Constants.MAX_MARK_LENGTH); - - if (length < 0 || length > BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES) { - throw new IllegalArgumentException(String.format( - "Invalid stream length; stream must be between 0 and %s MB in length.", - BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES / Constants.MB)); - } - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.put(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), blob.properties, blob.properties.getBlobType(), - 0, accessCondition, blobOptions, opContext); - this.setConnection(request); - - BlobRequest.addMetadata(request, blob.metadata, opContext); - - this.signRequest(client, request, length, null); - - final StreamMd5AndLength descriptor = Utility.writeToOutputStream(sourceStream, - request.getOutputStream(), length, true, false, null, opContext); - - if (length != descriptor.getLength()) { - throw new StorageException( - StorageErrorCodeStrings.INVALID_INPUT, - "An incorrect stream length was specified, resulting in an authentication failure. Please specify correct length, or -1.", - HttpURLConnection.HTTP_FORBIDDEN, null, null); - } - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Uploads the blob's metadata to the storage service. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void uploadMetadata() throws StorageException { - this.uploadMetadata(null, null, null); - } - - /** - * Uploads the blob's metadata to the storage service using the specified lease ID, request options, and operation - * context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void uploadMetadata(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.setMetadata(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), accessCondition, blobOptions, opContext); - this.setConnection(request); - - BlobRequest.addMetadata(request, blob.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Updates the blob's properties to the storage service. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void uploadProperties() throws StorageException { - this.uploadProperties(null, null, null); - } - - /** - * Updates the blob's properties using the specified lease ID, request options, and operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void uploadProperties(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.setProperties(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), blob.properties, null, accessCondition, - blobOptions, opContext); - this.setConnection(request); - - BlobRequest.addMetadata(request, blob.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Asserts that write operation is not done for snapshot. - */ - protected void assertNoWriteOperationForSnapshot() { - if (isSnapshot()) { - throw new IllegalArgumentException("Cannot perform this operation on a blob representing a snapshot."); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobClient.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobClient.java deleted file mode 100644 index 5113afab641d5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobClient.java +++ /dev/null @@ -1,691 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.RequestOptions; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.ResultContinuationType; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.ServiceClient; -import com.microsoft.windowsazure.services.core.storage.StorageCredentials; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsAnonymous; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LazySegmentedIterable; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ListingContext; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.SegmentedStorageOperation; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * Provides a client for accessing the Windows Azure Blob service. - *

- * This class provides a point of access to the Blob service. The service client encapsulates the base URI for the Blob - * service. If the service client will be used for authenticated access, it also encapsulates the credentials for - * accessing the storage account. - */ -public final class CloudBlobClient extends ServiceClient { - /** - * Holds the maximum size of a blob in bytes that may be uploaded as a single blob. - */ - private int singleBlobPutThresholdInBytes = BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES; - - /** - * Holds the maximum block size for writing to a block blob. - */ - private int writeBlockSizeInBytes = BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; - - /** - * Holds the number of bytes a BlobStream will write at once for a page blob. - */ - private int pageBlobStreamWriteSizeInBytes = BlobConstants.DEFAULT_MINIMUM_PAGE_STREAM_WRITE_IN_BYTES; - - /** - * Holds the minimum read size when using a BlobReadStream. - */ - private int streamMinimumReadSizeInBytes = BlobConstants.DEFAULT_MINIMUM_READ_SIZE_IN_BYTES; - - /** - * Holds the number of simultaneous operations a given blob operation may perform. - */ - private int concurrentRequestCount = BlobConstants.DEFAULT_CONCURRENT_REQUEST_COUNT; - - /** - * Holds the default delimiter that may be used to create a virtual directory structure of blobs. - */ - private String directoryDelimiter = BlobConstants.DEFAULT_DELIMITER; - - /** - * Creates an instance of the CloudBlobClient class using the specified Blob service endpoint. - * - * @param baseUri - * A java.net.URI object that represents the Blob service endpoint used to create the - * client. - */ - public CloudBlobClient(final URI baseUri) { - this(baseUri, StorageCredentialsAnonymous.ANONYMOUS); - } - - /** - * Creates an instance of the CloudBlobClient class using the specified Blob service endpoint and - * account credentials. - * - * @param baseUri - * A java.net.URI object that represents the Blob service endpoint used to create the - * client. - * @param credentials - * A {@link StorageCredentials} object that represents the account credentials. - */ - public CloudBlobClient(final URI baseUri, StorageCredentials credentials) { - super(baseUri, credentials); - this.directoryDelimiter = BlobConstants.DEFAULT_DELIMITER; - this.streamMinimumReadSizeInBytes = BlobConstants.DEFAULT_MINIMUM_READ_SIZE_IN_BYTES; - } - - /** - * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlockBlob getBlockBlobReference(final String blobAddressUri) throws URISyntaxException, - StorageException { - return this.getBlockBlobReference(blobAddressUri, null); - } - - /** - * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this container, using the - * specified snapshot ID. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * @param snapshotID - * A String that represents the snapshot ID of the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlockBlob getBlockBlobReference(final String blobAddressUri, final String snapshotID) - throws StorageException, URISyntaxException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI completeUri = PathUtility.appendPathToUri(this.endpoint, blobAddressUri); - - return new CloudBlockBlob(completeUri, snapshotID, this); - } - - /** - * Returns the number of maximum concurrent requests allowed. - * - * @return The number of maximum concurrent requests allowed. - */ - public int getConcurrentRequestCount() { - return this.concurrentRequestCount; - } - - /** - * Returns a reference to a {@link CloudBlobContainer} object that represents the cloud blob container for the - * specified address. - * - * @param containerAddress - * A String that represents the name of the container, or the absolute URI to the container. - * @return A {@link CloudBlobContainer} object that represents a reference to the cloud blob container. - * - * @throws URISyntaxException - * If the resource URI is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - public CloudBlobContainer getContainerReference(final String containerAddress) throws URISyntaxException, - StorageException { - Utility.assertNotNullOrEmpty("containerAddress", containerAddress); - return new CloudBlobContainer(containerAddress, this); - } - - /** - * Returns the value for the default delimiter used for cloud blob directories. The default is '/'. - * - * @return The value for the default delimiter. - */ - public String getDirectoryDelimiter() { - return this.directoryDelimiter; - } - - /** - * Returns a reference to the specified virtual blob directory. - *

- * A blob directory simplifies working with a hierarchical organization of blobs. A blob directory is a blob name - * prefix that can be used to navigate a hierarchy. The prefix may end in a delimiter character, but a delimiter is - * not required; the directory can end in any character. - * - * @param relativeAddress - * A String that represents the name of the virtual blob directory, or the absolute URI to - * the virtual blob directory. - * - * @return A {@link CloudBlobDirectory} object that represents the specified virtual blob directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlobDirectory getDirectoryReference(final String relativeAddress) throws URISyntaxException, - StorageException { - Utility.assertNotNullOrEmpty("relativeAddress", relativeAddress); - - return new CloudBlobDirectory(relativeAddress, this); - } - - /** - * Returns a reference to a {@link CloudPageBlob} object that represents a page blob. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified page blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudPageBlob getPageBlobReference(final String blobAddressUri) throws URISyntaxException, StorageException { - return this.getPageBlobReference(blobAddressUri, null); - } - - /** - * Returns a reference to a {@link CloudPageBlob} object that represents a page blob, using the specified snapshot - * ID. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * @param snapshotID - * A String that represents the snapshot ID of the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified page blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudPageBlob getPageBlobReference(final String blobAddressUri, final String snapshotID) - throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI completeUri = PathUtility.appendPathToUri(this.endpoint, blobAddressUri); - - return new CloudPageBlob(completeUri, snapshotID, this); - } - - /** - * Returns the write page size in use for this Blob service client. - * - * @return The maximum block size, in bytes, for writing to a page blob. - */ - public int getPageBlobStreamWriteSizeInBytes() { - return this.pageBlobStreamWriteSizeInBytes; - } - - /** - * Returns the threshold size used for writing a single blob for this Blob service client. - * - * @return The maximum size, in bytes, of a blob that may be uploaded as a single blob, ranging from 1 to 64 MB - * inclusive. The default value is 32 MBs. - *

- * If a blob size is above the threshold, it will be uploaded as blocks. - */ - public int getSingleBlobPutThresholdInBytes() { - return this.singleBlobPutThresholdInBytes; - } - - /** - * Returns the minimum read size in use for this Blob service client. - * - * @return The minimum read size, in bytes, when using a {@link BlobInputStream} object. - */ - public int getStreamMinimumReadSizeInBytes() { - return this.streamMinimumReadSizeInBytes; - } - - /** - * Returns the write block size in use for this Blob service client. - * - * @return The maximum block size, in bytes, for writing to a block blob while using a {@link BlobOutputStream} - * object. - */ - public int getWriteBlockSizeInBytes() { - return this.writeBlockSizeInBytes; - } - - /** - * Returns an enumerable collection of blob containers for this Blob service client. - * - * @return An enumerable collection of {@link CloudBlobContainer} objects that represent the containers for this - * client. - */ - @DoesServiceRequest - public Iterable listContainers() { - return this.listContainersWithPrefix(null, ContainerListingDetails.NONE, null, null); - } - - /** - * Returns an enumerable collection of blob containers whose names begin with the specified prefix for this Blob - * service client. - * - * @param prefix - * A String that represents the container name prefix. - * - * @return An enumerable collection of {@link CloudBlobContainer} objects that represent the containers for this - * client whose names begin with the specified prefix. - */ - @DoesServiceRequest - public Iterable listContainers(final String prefix) { - return this.listContainersWithPrefix(prefix, ContainerListingDetails.NONE, null, null); - } - - /** - * Returns an enumerable collection of blob containers whose names begin with the specified prefix for this Blob - * service client, using the specified details setting, request options, and operation context. - * - * @param prefix - * A String that represents the container name prefix. - * @param detailsIncluded - * A {@link ContainerListingDetails} value that indicates whether container metadata will be returned. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An enumerable collection of {@link CloudBlobContainer} objects that represents the containers for this - * client. - */ - @DoesServiceRequest - public Iterable listContainers(final String prefix, - final ContainerListingDetails detailsIncluded, final BlobRequestOptions options, - final OperationContext opContext) { - return this.listContainersWithPrefix(prefix, detailsIncluded, options, opContext); - } - - /** - * Returns a result segment containing a collection of containers whose names begin with the specified prefix. - * - * @param prefix - * A String that represents the container name prefix. - * @param detailsIncluded - * A value that indicates whether to return container metadata with the listing. - * @param maxResults - * the maximum results to retrieve. - * @param continuationToken - * A continuation token returned by a previous listing operation. - * @param options - * the request options to use for the operation - * @param taskReference - * a reference to the encapsulating task - * @param opContext - * a tracking object for the operation - * @return a result segment containing a collection of containers whose names begin with the specified prefix. - * @throws IOException - * @throws URISyntaxException - * @throws XMLStreamException - * @throws InvalidKeyException - * @throws StorageException - */ - @DoesServiceRequest - ResultSegment listContainersCore(final String prefix, - final ContainerListingDetails detailsIncluded, final int maxResults, - final ResultContinuation continuationToken, final RequestOptions options, - final StorageOperation> taskReference, - final OperationContext opContext) throws IOException, URISyntaxException, XMLStreamException, - InvalidKeyException, StorageException { - - Utility.assertContinuationType(continuationToken, ResultContinuationType.CONTAINER); - - final ListingContext listingContext = new ListingContext(prefix, maxResults); - listingContext.setMarker(continuationToken != null ? continuationToken.getNextMarker() : null); - - final HttpURLConnection listContainerRequest = ContainerRequest.list(this.getEndpoint(), - options.getTimeoutIntervalInMs(), listingContext, detailsIncluded, opContext); - taskReference.setConnection(listContainerRequest); - - taskReference.signRequest(this, listContainerRequest, -1L, null); - - ExecutionEngine.processRequest(listContainerRequest, opContext, taskReference.getResult()); - - if (taskReference.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - taskReference.setNonExceptionedRetryableFailure(true); - return null; - } - - final ListContainersResponse response = new ListContainersResponse(listContainerRequest.getInputStream()); - response.parseResponse(this); - - ResultContinuation newToken = null; - - if (response.getNextMarker() != null) { - newToken = new ResultContinuation(); - newToken.setNextMarker(response.getNextMarker()); - newToken.setContinuationType(ResultContinuationType.CONTAINER); - } - - final ResultSegment resSegment = new ResultSegment( - response.getContainers(this), maxResults, newToken); - - return resSegment; - } - - /** - * Returns a result segment of an enumerable collection of blob containers for this Blob service client. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link CloudBlobContainer} objects that represent the containers in this container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listContainersSegmented() throws StorageException { - return this.listContainersSegmented(null, ContainerListingDetails.NONE, 0, null, null, null); - } - - /** - * Returns a result segment of an enumerable collection of blob containers whose names begin with the specified - * prefix for this Blob service client. - * - * @param prefix - * A String that represents the prefix of the container name. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link CloudBlobContainer} objects that represent the containers whose names begin with the specified - * prefix. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listContainersSegmented(final String prefix) throws StorageException { - return this.listContainersWithPrefixSegmented(prefix, null, 0, null, null, null); - } - - /** - * Returns a result segment of an enumerable collection of blob containers whose names begin with the specified - * prefix for this container, using the specified listing details options, request options, and operation context. - * - * @param prefix - * A String that represents the prefix of the container name. - * @param detailsIncluded - * A {@link ContainerListingDetails} value that indicates whether container metadata will be returned. - * @param maxResults - * The maximum number of results to retrieve. - * @param continuationToken - * A {@link ResultContinuation} object that represents a continuation token returned by a previous - * listing operation. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link CloudBlobContainer} objects that represent the containers in this container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listContainersSegmented(final String prefix, - final ContainerListingDetails detailsIncluded, final int maxResults, - final ResultContinuation continuationToken, final BlobRequestOptions options, - final OperationContext opContext) throws StorageException { - - return this.listContainersWithPrefixSegmented(prefix, detailsIncluded, maxResults, continuationToken, options, - opContext); - } - - /** - * Returns an enumerable collection of blob containers whose names begin with the specified prefix, using the - * specified details setting, request options, and operation context. - * - * @param prefix - * A String that represents the prefix of the container name. - * @param detailsIncluded - * A {@link ContainerListingDetails} value that indicates whether container metadata will be returned. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An enumerable collection of {@link CloudBlobContainer} objects that represent the containers whose names - * begin with the specified prefix. - */ - @DoesServiceRequest - protected Iterable listContainersWithPrefix(final String prefix, - final ContainerListingDetails detailsIncluded, BlobRequestOptions options, OperationContext opContext) { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this); - - final SegmentedStorageOperation> impl = new SegmentedStorageOperation>( - options, null) { - @Override - public ResultSegment execute(final CloudBlobClient client, final Void dontCare, - final OperationContext opContext) throws Exception { - - final ResultSegment result = CloudBlobClient.this.listContainersCore(prefix, - detailsIncluded, -1, this.getToken(), this.getRequestOptions(), this, opContext); - - // Note, setting the token on the SegmentedStorageOperation is - // key, this is how the iterator - // will share the token across executions - this.setToken(result.getContinuationToken()); - return result; - } - }; - - return new LazySegmentedIterable(impl, this, null, - options.getRetryPolicyFactory(), opContext); - } - - /** - * Returns a result segment of an enumerable collection of blob containers whose names begin with the specified - * prefix for this container, using the specified listing details options, request options, and operation context. - * - * @param prefix - * A String that represents the prefix of the container name. - * @param detailsIncluded - * A {@link ContainerListingDetails} value that indicates whether container metadata will be returned. - * @param maxResults - * The maximum number of results to retrieve. - * @param continuationToken - * A {@link ResultContinuation} object that represents a continuation token returned by a previous - * listing operation. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link CloudBlobContainer} objects that represent the containers in this container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - protected ResultSegment listContainersWithPrefixSegmented(final String prefix, - final ContainerListingDetails detailsIncluded, final int maxResults, - final ResultContinuation continuationToken, BlobRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this); - - Utility.assertContinuationType(continuationToken, ResultContinuationType.CONTAINER); - - final StorageOperation> impl = new StorageOperation>( - options) { - @Override - public ResultSegment execute(final CloudBlobClient client, final Void dontCare, - final OperationContext opContext) throws Exception { - return CloudBlobClient.this.listContainersCore(prefix, detailsIncluded, maxResults, continuationToken, - this.getRequestOptions(), this, opContext); - } - }; - - return ExecutionEngine.executeWithRetry(this, null, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Sets the maximum number of concurrent requests allowed for the Blob service client. - * - * @param concurrentRequestCount - * The value being assigned as the maximum number of concurrent requests allowed for the Blob service - * client. - */ - public void setConcurrentRequestCount(final int concurrentRequestCount) { - this.concurrentRequestCount = concurrentRequestCount; - } - - /** - * Sets the value for the default delimiter used for cloud blob directories. - * - * @param directoryDelimiter - * A String that represents the value for the default directory delimiter. - */ - public void setDirectoryDelimiter(final String directoryDelimiter) { - this.directoryDelimiter = directoryDelimiter; - } - - /** - * Sets the write page size in use for this Blob Service client. - * - * @param pageBlobStreamWriteSizeInBytes - * The maximum block size, in bytes, for writing to a page blob. This value must be a multiple of 512 and - * less than or equal to 4 MB. - */ - public void setPageBlobStreamWriteSizeInBytes(final int pageBlobStreamWriteSizeInBytes) { - if (pageBlobStreamWriteSizeInBytes > BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES - || pageBlobStreamWriteSizeInBytes < BlobConstants.PAGE_SIZE - || pageBlobStreamWriteSizeInBytes % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("PageBlobStreamWriteSizeInBytes"); - } - - this.pageBlobStreamWriteSizeInBytes = pageBlobStreamWriteSizeInBytes; - } - - /** - * Sets the threshold size used for writing a single blob to use with this Blob service client. - * - * @param singleBlobPutThresholdInBytes - * The maximum size, in bytes, of a blob that may be uploaded as a single blob, ranging from 1 MB to 64 - * MB inclusive. If a blob size is above the threshold, it will be uploaded as blocks. - * - * @throws IllegalArgumentException - * If minimumReadSize is less than 1 MB or greater than 64 MB. - */ - public void setSingleBlobPutThresholdInBytes(final int singleBlobPutThresholdInBytes) { - if (singleBlobPutThresholdInBytes > BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES - || singleBlobPutThresholdInBytes < 1 * Constants.MB) { - throw new IllegalArgumentException("SingleBlobUploadThresholdInBytes"); - } - - this.singleBlobPutThresholdInBytes = singleBlobPutThresholdInBytes; - } - - /** - * Sets the minimum read block size to use with this Blob service client. - * - * @param minimumReadSize - * The maximum block size, in bytes, for reading from a block blob while using a {@link BlobInputStream} - * object, ranging from 512 bytes to 64 MB, inclusive. - */ - public void setStreamMinimumReadSizeInBytes(final int minimumReadSize) { - if (minimumReadSize > 64 * Constants.MB || minimumReadSize < BlobConstants.PAGE_SIZE) { - throw new IllegalArgumentException("MinimumReadSize"); - } - - this.streamMinimumReadSizeInBytes = minimumReadSize; - } - - /** - * Sets the write block size to use with this Blob service client. - * - * @param writeBlockSizeInBytes - * The maximum block size, in bytes, for writing to a block blob while using a {@link BlobOutputStream} - * object, ranging from 1 MB to 4 MB, inclusive. - * - * @throws IllegalArgumentException - * If writeBlockSizeInBytes is less than 1 MB or greater than 4 MB. - */ - public void setWriteBlockSizeInBytes(final int writeBlockSizeInBytes) { - if (writeBlockSizeInBytes > BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES - || writeBlockSizeInBytes < 1 * Constants.MB) { - throw new IllegalArgumentException("WriteBlockSizeInBytes"); - } - - this.writeBlockSizeInBytes = writeBlockSizeInBytes; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobContainer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobContainer.java deleted file mode 100644 index 10e2a450a514e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobContainer.java +++ /dev/null @@ -1,2090 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.StringWriter; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.Calendar; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashMap; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.blob.core.storage.SharedAccessSignatureHelper; -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.ResultContinuationType; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.StorageExtendedErrorInformation; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LazySegmentedIterable; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LeaseAction; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.SegmentedStorageOperation; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * Represents a container in the Windows Azure Blob service. - *

- * Containers hold directories, which are encapsulated as {@link CloudBlobDirectory} objects, and directories hold block - * blobs and page blobs. Directories can also contain sub-directories. - */ -public final class CloudBlobContainer { - - /** - * Converts the ACL string to a BlobContainerPermissions object. - * - * @param aclString - * the string to convert. - * @return The resulting BlobContainerPermissions object. - */ - static BlobContainerPermissions getContainerAcl(final String aclString) { - BlobContainerPublicAccessType accessType = BlobContainerPublicAccessType.OFF; - - if (!Utility.isNullOrEmpty(aclString)) { - final String lowerAclString = aclString.toLowerCase(); - if ("container".equals(lowerAclString)) { - accessType = BlobContainerPublicAccessType.CONTAINER; - } - else if ("blob".equals(lowerAclString)) { - accessType = BlobContainerPublicAccessType.BLOB; - } - else { - throw new IllegalArgumentException(String.format( - "Invalid acl public access type returned '%s'. Expected blob or container.", aclString)); - } - } - - final BlobContainerPermissions retVal = new BlobContainerPermissions(); - retVal.setPublicAccess(accessType); - - return retVal; - } - - /** - * Represents the container metadata. - */ - protected HashMap metadata; - - /** - * Holds the container properties. - */ - BlobContainerProperties properties; - - /** - * Holds the name of the container. - */ - String name; - - /** - * Holds the URI of the container. - */ - URI uri; - - /** - * Holds a reference to the associated service client. - */ - private CloudBlobClient blobServiceClient; - - /** - * Initializes a new instance of the CloudBlobContainer class. - * - * @param client - * the reference to the associated service client. - */ - private CloudBlobContainer(final CloudBlobClient client) { - this.metadata = new HashMap(); - this.properties = new BlobContainerProperties(); - this.blobServiceClient = client; - } - - /** - * Creates an instance of the CloudBlobContainer class using the specified address and client. - * - * @param containerAddress - * A String that represents either the absolute URI to the container, or the container name. - * @param client - * A {@link CloudBlobClient} object that represents the associated service client, and that specifies the - * endpoint for the Blob service. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlobContainer(final String containerAddress, final CloudBlobClient client) throws URISyntaxException, - StorageException { - this(client); - - final URI resURI = PathUtility.appendPathToUri(client.getEndpoint(), containerAddress); - - this.uri = resURI; - this.name = PathUtility.getContainerNameFromUri(resURI, client.isUsePathStyleUris()); - - this.parseQueryAndVerify(this.uri, client, client.isUsePathStyleUris()); - } - - /** - * Creates an instance of the CloudBlobContainer class using the specified URI and client. - * - * @param uri - * A java.net.URI object that represents the URI of the container. - * @param client - * A {@link CloudBlobClient} object that represents the associated service client, and that specifies the - * endpoint for the Blob service. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlobContainer(final URI uri, final CloudBlobClient client) throws URISyntaxException, StorageException { - this(client); - - this.uri = uri; - this.name = PathUtility.getContainerNameFromUri(uri, client.isUsePathStyleUris()); - - this.parseQueryAndVerify(this.uri, client, client.isUsePathStyleUris()); - } - - /** - * Creates the container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void create() throws StorageException { - this.create(null, null); - } - - /** - * Creates the container using the specified options and operation context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void create(BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = ContainerRequest.create(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - ContainerRequest.addMetadata(request, container.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - // Set attributes - final BlobContainerAttributes attributes = ContainerResponse.getAttributes(request, - client.isUsePathStyleUris()); - container.properties = attributes.getProperties(); - container.name = attributes.getName(); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Creates the container if it does not exist. - * - * @return true if the container did not already exist and was created; otherwise, false. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public boolean createIfNotExist() throws StorageException { - return this.createIfNotExist(null, null); - } - - /** - * Creates the container if it does not exist, using the specified request options and operation context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return true if the container did not already exist and was created; otherwise, false. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public boolean createIfNotExist(BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Boolean execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = ContainerRequest.create(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - ContainerRequest.addMetadata(request, container.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - // Validate response code here - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CREATED) { - // Set attributes - final BlobContainerAttributes attributes = ContainerResponse.getAttributes(request, - client.isUsePathStyleUris()); - container.properties = attributes.getProperties(); - container.name = attributes.getName(); - return true; - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - final StorageException potentialConflictException = StorageException.translateException(request, - null, opContext); - - StorageExtendedErrorInformation extendedInfo = potentialConflictException - .getExtendedErrorInformation(); - if (extendedInfo == null) { - // If we cant validate the error then the error must be surfaced to the user. - throw potentialConflictException; - } - - if (!extendedInfo.getErrorCode().equals(StorageErrorCodeStrings.CONTAINER_ALREADY_EXISTS)) { - this.setException(potentialConflictException); - this.setNonExceptionedRetryableFailure(true); - - // return false instead of null to avoid SCA issues - return false; - } - - return false; - } - else { - throw StorageException.translateException(request, null, opContext); - } - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Deletes the container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void delete() throws StorageException { - this.delete(null, null); - } - - /** - * Deletes the container using the specified request options and operation context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void delete(BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = ContainerRequest.delete(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - - } - - /** - * Deletes the container if it exists. - * - * @return true if the container did not already exist and was created; otherwise, false. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public boolean deleteIfExists() throws StorageException { - return this.deleteIfExists(null, null); - } - - /** - * Deletes the container if it exists using the specified request options and operation context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return true if the container did not already exist and was created; otherwise, false. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public boolean deleteIfExists(BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Boolean execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = ContainerRequest.delete(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_ACCEPTED) { - container.updatePropertiesFromResponse(request); - return true; - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return false; - } - else { - this.setNonExceptionedRetryableFailure(true); - // return false instead of null to avoid SCA issues - return false; - } - - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Downloads the container's attributes, which consist of metadata and properties. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void downloadAttributes() throws StorageException { - this.downloadAttributes(null, null); - } - - /** - * Downloads the container's attributes, which consist of metadata and properties, using the specified request - * options and operation context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void downloadAttributes(BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = ContainerRequest.getProperties(container.uri, this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - // Set attributes - final BlobContainerAttributes attributes = ContainerResponse.getAttributes(request, - client.isUsePathStyleUris()); - container.metadata = attributes.getMetadata(); - container.properties = attributes.getProperties(); - container.name = attributes.getName(); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Downloads the permission settings for the container. - * - * @return A {@link BlobContainerPermissions} object that represents the container's permissions. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public BlobContainerPermissions downloadPermissions() throws StorageException { - return this.downloadPermissions(null, null); - } - - /** - * Downloads the permissions settings for the container using the specified request options and operation context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link BlobContainerPermissions} object that represents the container's permissions. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public BlobContainerPermissions downloadPermissions(BlobRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public BlobContainerPermissions execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = ContainerRequest.getAcl(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - } - - container.updatePropertiesFromResponse(request); - final String aclString = ContainerResponse.getAcl(request); - final BlobContainerPermissions containerAcl = getContainerAcl(aclString); - - final BlobAccessPolicyResponse response = new BlobAccessPolicyResponse(request.getInputStream()); - - for (final String key : response.getAccessIdentifiers().keySet()) { - containerAcl.getSharedAccessPolicies().put(key, response.getAccessIdentifiers().get(key)); - } - - return containerAcl; - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Returns a value that indicates whether the container exists. - * - * @return true if the container exists, otherwise false. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public boolean exists() throws StorageException { - return this.exists(null, null); - } - - /** - * Returns a value that indicates whether the container exists, using the specified request options and operation - * context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return true if the container exists, otherwise false. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public boolean exists(BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Boolean execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = ContainerRequest.getProperties(container.uri, this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { - container.updatePropertiesFromResponse(request); - return Boolean.valueOf(true); - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return Boolean.valueOf(false); - } - else { - this.setNonExceptionedRetryableFailure(true); - // return false instead of null to avoid SCA issues - return false; - } - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Returns a shared access signature for the container. Note this does not contain the leading "?". - * - * @param policy - * The access policy for the shared access signature. - * @param groupPolicyIdentifier - * A container-level access policy. - * @return a shared access signature for the container. - * @throws InvalidKeyException - * @throws StorageException - * @throws IllegalArgumentException - */ - public String generateSharedAccessSignature(final SharedAccessBlobPolicy policy, final String groupPolicyIdentifier) - throws InvalidKeyException, StorageException { - - if (!this.blobServiceClient.getCredentials().canCredentialsSignRequest()) { - final String errorMessage = "Cannot create Shared Access Signature unless the Account Key credentials are used by the BlobServiceClient."; - throw new IllegalArgumentException(errorMessage); - } - - final String resourceName = this.getSharedAccessCanonicalName(); - - final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHash(policy, - groupPolicyIdentifier, resourceName, this.blobServiceClient, null); - - final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignature(policy, - groupPolicyIdentifier, "c", signature); - - return builder.toString(); - } - - /** - * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this container. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlockBlob getBlockBlobReference(final String blobAddressUri) throws URISyntaxException, - StorageException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI address = PathUtility.appendPathToUri(this.uri, blobAddressUri); - - return new CloudBlockBlob(address, this.blobServiceClient, this); - } - - /** - * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this container, using the - * specified snapshot ID. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * @param snapshotID - * A String that represents the snapshot ID of the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlockBlob getBlockBlobReference(final String blobAddressUri, final String snapshotID) - throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI address = PathUtility.appendPathToUri(this.uri, blobAddressUri); - - final CloudBlockBlob retBlob = new CloudBlockBlob(address, snapshotID, this.blobServiceClient); - retBlob.setContainer(this); - return retBlob; - } - - /** - * Returns a reference to a {@link CloudBlobDirectory} object that represents a virtual blob directory within this - * container. - * - * @param relativeAddress - * A String that represents the name of the virtual blob directory, or the absolute URI to - * the virtual blob directory. - * - * @return A {@link CloudBlobDirectory} that represents a virtual blob directory within this container. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlobDirectory getDirectoryReference(final String relativeAddress) throws URISyntaxException, - StorageException { - Utility.assertNotNullOrEmpty("relativeAddress", relativeAddress); - final URI address = PathUtility.appendPathToUri(this.uri, relativeAddress); - - return new CloudBlobDirectory(address, null, this.blobServiceClient); - } - - /** - * Returns the metadata for the container. - * - * @return A java.util.HashMap object that represents the metadata for the container. - */ - public HashMap getMetadata() { - return this.metadata; - } - - /** - * Returns the name of the container. - * - * @return A String that represents the name of the container. - */ - public String getName() { - return this.name; - } - - /** - * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in this container. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * - * @return A {@link CloudPageBlob} object that represents a reference to the specified page blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudPageBlob getPageBlobReference(final String blobAddressUri) throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI address = PathUtility.appendPathToUri(this.uri, blobAddressUri); - - return new CloudPageBlob(address, this.blobServiceClient, this); - } - - /** - * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in the directory, using the - * specified snapshot ID. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * @param snapshotID - * A String that represents the snapshot ID of the blob. - * - * @return A {@link CloudPageBlob} object that represents a reference to the specified page blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudPageBlob getPageBlobReference(final String blobAddressUri, final String snapshotID) - throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI address = PathUtility.appendPathToUri(this.uri, blobAddressUri); - - final CloudPageBlob retBlob = new CloudPageBlob(address, snapshotID, this.blobServiceClient); - retBlob.setContainer(this); - return retBlob; - } - - /** - * Returns the properties for the container. - * - * @return A {@link BlobContainerProperties} object that represents the properties for the container. - */ - public BlobContainerProperties getProperties() { - return this.properties; - } - - /** - * Returns the Blob service client associated with this container. - * - * @return A {@link CloudBlobClient} object that represents the service client associated with this container. - */ - public CloudBlobClient getServiceClient() { - return this.blobServiceClient; - } - - /** - * Returns the canonical name for shared access. - * - * @return the canonical name for shared access. - */ - private String getSharedAccessCanonicalName() { - if (this.blobServiceClient.isUsePathStyleUris()) { - return this.getUri().getPath(); - } - else { - return PathUtility.getCanonicalPathFromCredentials(this.blobServiceClient.getCredentials(), this.getUri() - .getPath()); - } - } - - /** - * Returns the URI after applying the authentication transformation. - * - * @return A java.net.URI object that represents the URI after applying the authentication - * transformation. - * - * @throws IllegalArgumentException - * If an unexpected value is passed. - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - protected URI getTransformedAddress() throws URISyntaxException, StorageException { - if (this.blobServiceClient.getCredentials().doCredentialsNeedTransformUri()) { - if (this.uri.isAbsolute()) { - return this.blobServiceClient.getCredentials().transformUri(this.uri); - } - else { - final StorageException ex = Utility.generateNewUnexpectedStorageException(null); - ex.getExtendedErrorInformation().setErrorMessage("Blob Object relative URIs not supported."); - throw ex; - } - } - else { - return this.uri; - } - } - - /** - * Returns the URI for this container. - * - * @return The absolute URI to the container. - */ - public URI getUri() { - return this.uri; - } - - /** - * Returns an enumerable collection of blob items for the container. - * - * @return An enumerable collection of {@link ListBlobItem} objects that represents the items in this container. - */ - @DoesServiceRequest - public Iterable listBlobs() { - return this.listBlobs(null, false, EnumSet.noneOf(BlobListingDetails.class), null, null); - } - - /** - * Returns an enumerable collection of blob items for the container whose names begin with the specified prefix. - * - * @param prefix - * A String that represents the blob name prefix. This value must be preceded either by the - * name of the container or by the absolute path to the container. - * - * @return An enumerable collection of {@link ListBlobItem} objects that represents the items whose names begin with - * the specified prefix in this container. - */ - @DoesServiceRequest - public Iterable listBlobs(final String prefix) { - return this.listBlobs(prefix, false, EnumSet.noneOf(BlobListingDetails.class), null, null); - } - - /** - * Returns an enumerable collection of blob items whose names begin with the specified prefix, using the specified - * flat or hierarchical option, listing details options, request options, and operation context. - * - * @param prefix - * A String that represents the blob name prefix. This value must be preceded either by the - * name of the container or by the absolute path to the container. - * @param useFlatBlobListing - * true to indicate that the returned list will be flat; false to indicate that - * the returned list will be hierarchical. - * @param listingDetails - * A java.util.EnumSet object that contains {@link BlobListingDetails} values that indicate - * whether snapshots, metadata, and/or uncommitted blocks are returned. Committed blocks are always - * returned. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An enumerable collection of {@link ListBlobItem} objects that represent the block items whose names begin - * with the specified prefix in this directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @DoesServiceRequest - public Iterable listBlobs(final String prefix, final boolean useFlatBlobListing, - final EnumSet listingDetails, BlobRequestOptions options, OperationContext opContext) { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - if (!useFlatBlobListing && listingDetails != null && listingDetails.contains(BlobListingDetails.SNAPSHOTS)) { - throw new IllegalArgumentException( - "Listing snapshots is only supported in flat mode (no delimiter). Consider setting useFlatBlobListing to true."); - } - - final SegmentedStorageOperation> impl = new SegmentedStorageOperation>( - options, null) { - - @Override - public ResultSegment execute(final CloudBlobClient client, - final CloudBlobContainer container, final OperationContext opContext) throws Exception { - - final ResultSegment result = CloudBlobContainer.this.listBlobsCore(prefix, - useFlatBlobListing, listingDetails, -1, this.getToken(), - (BlobRequestOptions) this.getRequestOptions(), this, opContext); - - // Note, setting the token on the SegmentedStorageOperation is - // key, this is how the iterator - // will share the token across executions - if (result != null) { - this.setToken(result.getContinuationToken()); - } - return result; - } - }; - - return new LazySegmentedIterable(impl, - this.blobServiceClient, this, options.getRetryPolicyFactory(), opContext); - } - - /** - * Returns a result segment containing a collection of blob items whose names begin with the specified prefix. - * - * @param prefix - * The blob name prefix. This value must be preceded either by the name of the container or by the - * absolute path to the container. - * @param useFlatBlobListing - * a value indicating whether the blob listing operation will list all blobs in a container in a flat - * listing, or whether it will list blobs hierarchically, by virtual directory. - * @param listingDetails - * a EnumSet BlobListingDetails that indicates what items a listing operation will return. - * @param maxResults - * the maximum results to retrieve. - * @param continuationToken - * A continuation token returned by a previous listing operation. - * @param options - * An object that specifies any additional options for the request - * @param taskReference - * a reference to the encapsulating task - * @param opContext - * a tracking object for the operation - * @return a result segment containing a collection of blob items whose names begin with the specified - * @throws IllegalArgumentException - * @throws URISyntaxException - * @throws IOException - * @throws StorageException - * @throws InvalidKeyException - * @throws XMLStreamException - */ - @DoesServiceRequest - ResultSegment listBlobsCore(final String prefix, final boolean useFlatBlobListing, - EnumSet listingDetails, final int maxResults, - final ResultContinuation continuationToken, final BlobRequestOptions options, - final StorageOperation> taskReference, - final OperationContext opContext) throws URISyntaxException, IOException, StorageException, - InvalidKeyException, XMLStreamException { - Utility.assertContinuationType(continuationToken, ResultContinuationType.BLOB); - Utility.assertNotNull("options", options); - - if (listingDetails == null) { - listingDetails = EnumSet.noneOf(BlobListingDetails.class); - } - - if (!useFlatBlobListing && listingDetails.contains(BlobListingDetails.SNAPSHOTS)) { - throw new IllegalArgumentException( - "Listing snapshots is only supported in flat mode (no delimiter). Consider setting useFlatBlobListing to true."); - } - - final String delimiter = useFlatBlobListing ? null : this.blobServiceClient.getDirectoryDelimiter(); - - final BlobListingContext listingContext = new BlobListingContext(prefix, maxResults, delimiter, listingDetails); - listingContext.setMarker(continuationToken != null ? continuationToken.getNextMarker() : null); - - final HttpURLConnection listBlobsRequest = BlobRequest.list(this.getTransformedAddress(), - options.getTimeoutIntervalInMs(), listingContext, options, opContext); - taskReference.setConnection(listBlobsRequest); - - taskReference.signRequest(this.blobServiceClient, listBlobsRequest, -1L, null); - - ExecutionEngine.processRequest(listBlobsRequest, opContext, taskReference.getResult()); - - if (taskReference.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - taskReference.setNonExceptionedRetryableFailure(true); - return null; - } - - final ListBlobsResponse response = new ListBlobsResponse(listBlobsRequest.getInputStream()); - response.parseResponse(this.blobServiceClient, this); - - ResultContinuation newToken = null; - - if (response.getNextMarker() != null) { - newToken = new ResultContinuation(); - newToken.setNextMarker(response.getNextMarker()); - newToken.setContinuationType(ResultContinuationType.BLOB); - } - - final ResultSegment resSegment = new ResultSegment(response.getBlobs( - this.blobServiceClient, this), maxResults, newToken); - - return resSegment; - } - - /** - * Returns a result segment of an enumerable collection of blob items in the container. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link ListBlobItem} objects that represent the blob items in the container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listBlobsSegmented() throws StorageException { - return this.listBlobsSegmented(null, false, EnumSet.noneOf(BlobListingDetails.class), -1, null, null, null); - } - - /** - * Returns a result segment containing a collection of blob items whose names begin with the specified prefix. - * - * @param prefix - * A String that represents the prefix of the blob name. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link ListBlobItem} objects that represent the blob items whose names begin with the specified prefix in - * the container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listBlobsSegmented(final String prefix) throws StorageException { - return this.listBlobsSegmented(prefix, false, EnumSet.noneOf(BlobListingDetails.class), -1, null, null, null); - } - - /** - * Returns a result segment containing a collection of blob items whose names begin with the specified prefix, using - * the specified flat or hierarchical option, listing details options, request options, and operation context. - * - * @param prefix - * A String that represents the prefix of the blob name. - * @param useFlatBlobListing - * true to indicate that the returned list will be flat; false to indicate that - * the returned list will be hierarchical. - * @param listingDetails - * A java.util.EnumSet object that contains {@link BlobListingDetails} values that indicate - * whether snapshots, metadata, and/or uncommitted blocks are returned. Committed blocks are always - * returned. - * @param maxResults - * The maximum number of results to retrieve. - * @param continuationToken - * A {@link ResultContinuation} object that represents a continuation token returned by a previous - * listing operation. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link ListBlobItem} objects that represent the block items whose names begin with the specified prefix - * in the container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listBlobsSegmented(final String prefix, final boolean useFlatBlobListing, - final EnumSet listingDetails, final int maxResults, - final ResultContinuation continuationToken, BlobRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - Utility.assertContinuationType(continuationToken, ResultContinuationType.BLOB); - - if (!useFlatBlobListing && listingDetails != null && listingDetails.contains(BlobListingDetails.SNAPSHOTS)) { - throw new IllegalArgumentException( - "Listing snapshots is only supported in flat mode (no delimiter). Consider setting useFlatBlobListing to true."); - } - - final StorageOperation> impl = new StorageOperation>( - options) { - - @Override - public ResultSegment execute(final CloudBlobClient client, final CloudBlobContainer parent, - final OperationContext opContext) throws Exception { - - return CloudBlobContainer.this.listBlobsCore(prefix, useFlatBlobListing, listingDetails, maxResults, - continuationToken, (BlobRequestOptions) this.getRequestOptions(), this, opContext); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Returns an enumerable collection of containers for the service client associated with this container. - * - * @return An enumerable collection of {@link CloudBlobContainer} objects that represent the containers for the - * service client associated with this container. - */ - @DoesServiceRequest - public Iterable listContainers() { - return this.blobServiceClient.listContainers(); - } - - /** - * Returns an enumerable collection of containers whose names begin with the specified prefix for the service client - * associated with this container. - * - * @param prefix - * A String that represents the container name prefix. - * - * @return An enumerable collection of {@link CloudBlobContainer} objects that represent the containers whose names - * begin with the specified prefix for the service client associated with this container. - */ - @DoesServiceRequest - public Iterable listContainers(final String prefix) { - return this.blobServiceClient.listContainers(prefix); - } - - /** - * Returns an enumerable collection of containers whose names begin with the specified prefix for the service client - * associated with this container, using the specified details setting, request options, and operation context. - * - * @param prefix - * A String that represents the container name prefix. - * @param detailsIncluded - * A {@link ContainerListingDetails} value that indicates whether container metadata will be returned. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An enumerable collection of {@link CloudBlobContainer} objects that represents the containers for the - * service client associated with this container. - */ - @DoesServiceRequest - public Iterable listContainers(final String prefix, - final ContainerListingDetails detailsIncluded, final BlobRequestOptions options, - final OperationContext opContext) { - return this.blobServiceClient.listContainers(prefix, detailsIncluded, options, opContext); - } - - /** - * Returns a result segment of an enumerable collection of containers for the service client associated with this - * container. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link CloudBlobContainer} objects that represent the containers for the service client associated with - * this container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listContainersSegmented() throws StorageException { - return this.blobServiceClient.listContainersSegmented(); - } - - /** - * Returns a result segment of an enumerable collection of containers whose names begin with the specified prefix - * for the service client associated with this container. - * - * @param prefix - * A String that represents the blob name prefix. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link CloudBlobContainer} objects that represent the containers whose names begin with the specified - * prefix for the service client associated with this container. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ResultSegment listContainersSegmented(final String prefix) throws StorageException { - return this.blobServiceClient.listContainersSegmented(prefix); - } - - /** - * Returns a result segment containing a collection of containers whose names begin with the specified prefix for - * the service client associated with this container, using the specified listing details options, request options, - * and operation context. - * - * @param prefix - * A String that represents the prefix of the container name. - * @param detailsIncluded - * A {@link ContainerListingDetails} object that indicates whether metadata is included. - * @param maxResults - * The maximum number of results to retrieve. - * @param continuationToken - * A {@link ResultContinuation} object that represents a continuation token returned by a previous - * listing operation. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link CloudBlobContainer} objects that represent the containers whose names begin with the specified - * prefix for the service client associated with this container. - * - * @throws StorageException - * If a storage service error occurred. - * - */ - @DoesServiceRequest - public ResultSegment listContainersSegmented(final String prefix, - final ContainerListingDetails detailsIncluded, final int maxResults, - final ResultContinuation continuationToken, final BlobRequestOptions options, - final OperationContext opContext) throws StorageException { - return this.blobServiceClient.listContainersSegmented(prefix, detailsIncluded, maxResults, continuationToken, - options, opContext); - } - - /** - * Parse Uri for SAS (Shared access signature) information. - * - * Validate that no other query parameters are passed in. Any SAS information will be recorded as corresponding - * credentials instance. If existingClient is passed in, any SAS information found will not be supported. Otherwise - * a new client is created based on SAS information or as anonymous credentials. - * - * @param completeUri - * The complete Uri. - * @param existingClient - * The client to use. - * @param usePathStyleUris - * If true, path style Uris are used. - * @throws URISyntaxException - * @throws StorageException - */ - private void parseQueryAndVerify(final URI completeUri, final CloudBlobClient existingClient, - final boolean usePathStyleUris) throws URISyntaxException, StorageException { - Utility.assertNotNull("completeUri", completeUri); - - if (!completeUri.isAbsolute()) { - final String errorMessage = String.format( - "Address '%s' is not an absolute address. Relative addresses are not permitted in here.", - completeUri.toString()); - throw new IllegalArgumentException(errorMessage); - } - - this.uri = PathUtility.stripURIQueryAndFragment(completeUri); - - final HashMap queryParameters = PathUtility.parseQueryString(completeUri.getQuery()); - final StorageCredentialsSharedAccessSignature sasCreds = SharedAccessSignatureHelper - .parseQuery(queryParameters); - - if (sasCreds == null) { - return; - } - - final Boolean sameCredentials = existingClient == null ? false : Utility.areCredentialsEqual(sasCreds, - existingClient.getCredentials()); - - if (existingClient == null || !sameCredentials) { - this.blobServiceClient = new CloudBlobClient(new URI(PathUtility.getServiceClientBaseAddress(this.getUri(), - usePathStyleUris)), sasCreds); - } - - if (existingClient != null && !sameCredentials) { - this.blobServiceClient - .setPageBlobStreamWriteSizeInBytes(existingClient.getPageBlobStreamWriteSizeInBytes()); - this.blobServiceClient.setSingleBlobPutThresholdInBytes(existingClient.getSingleBlobPutThresholdInBytes()); - this.blobServiceClient.setStreamMinimumReadSizeInBytes(existingClient.getStreamMinimumReadSizeInBytes()); - this.blobServiceClient.setWriteBlockSizeInBytes(existingClient.getWriteBlockSizeInBytes()); - this.blobServiceClient.setConcurrentRequestCount(existingClient.getConcurrentRequestCount()); - this.blobServiceClient.setDirectoryDelimiter(existingClient.getDirectoryDelimiter()); - this.blobServiceClient.setRetryPolicyFactory(existingClient.getRetryPolicyFactory()); - this.blobServiceClient.setTimeoutInMs(existingClient.getTimeoutInMs()); - } - } - - void updatePropertiesFromResponse(HttpURLConnection request) { - String tempStr = request.getHeaderField(Constants.HeaderConstants.ETAG); - - // ETag - if (!Utility.isNullOrEmpty(tempStr)) { - this.getProperties().setEtag(tempStr); - } - - // Last Modified - if (0 != request.getLastModified()) { - final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US); - lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE); - lastModifiedCalendar.setTime(new Date(request.getLastModified())); - this.getProperties().setLastModified(lastModifiedCalendar.getTime()); - } - } - - /** - * Sets the metadata for the container. - * - * @param metadata - * A java.util.HashMap object that represents the metadata being assigned to the container. - */ - public void setMetadata(final HashMap metadata) { - this.metadata = metadata; - } - - /** - * Sets the name of the container. - * - * @param name - * A String that represents the name being assigned to the container. - */ - protected void setName(final String name) { - this.name = name; - } - - /** - * Sets the properties for the container. - * - * @param properties - * A {@link BlobContainerProperties} object that represents the properties being assigned to the - * container. - */ - protected void setProperties(final BlobContainerProperties properties) { - this.properties = properties; - } - - /** - * Sets the URI of the container. - * - * @param uri - * A java.net.URI object that represents the URI being assigned to the container. - */ - protected void setUri(final URI uri) { - this.uri = uri; - } - - /** - * Uploads the container's metadata. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadMetadata() throws StorageException { - this.uploadMetadata(null, null); - } - - /** - * Uploads the container's metadata using the specified request options and operation context. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadMetadata(BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = ContainerRequest.setMetadata(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - ContainerRequest.addMetadata(request, container.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - } - - container.updatePropertiesFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - - } - - /** - * Uploads the container's permissions. - * - * @param permissions - * A {@link BlobContainerPermissions} object that represents the permissions to upload. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPermissions(final BlobContainerPermissions permissions) throws StorageException { - this.uploadPermissions(permissions, null, null); - } - - /** - * Uploads the container's permissions using the specified request options and operation context. - * - * @param permissions - * A {@link BlobContainerPermissions} object that represents the permissions to upload. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPermissions(final BlobContainerPermissions permissions, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = ContainerRequest.setAcl(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), permissions.getPublicAccess(), opContext); - this.setConnection(request); - - final StringWriter outBuffer = new StringWriter(); - - ContainerRequest.writeSharedAccessIdentifiersToStream(permissions.getSharedAccessPolicies(), outBuffer); - - final byte[] aclBytes = outBuffer.toString().getBytes("UTF8"); - - this.signRequest(client, request, aclBytes.length, null); - - final OutputStream outStreamRef = request.getOutputStream(); - outStreamRef.write(aclBytes); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - } - - container.updatePropertiesFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Acquires a new lease on the container with the specified lease time and proposed lease ID. - * - * @param leaseTimeInSeconds - * Specifies the span of time for which to acquire the lease, in seconds. - * If null, an infinite lease will be acquired. If not null, the value must be greater than - * zero. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @return A String that represents the lease ID. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId) - throws StorageException { - return this.acquireLease(leaseTimeInSeconds, proposedLeaseId, null, null, null); - } - - /** - * Acquires a new lease on the container with the specified lease time, proposed lease ID, request - * options, and operation context. - * - * @param leaseTimeInSeconds - * Specifies the span of time for which to acquire the lease, in seconds. - * If null, an infinite lease will be acquired. If not null, the value must be greater than - * zero. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the container. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A String that represents the lease ID. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final String acquireLease(final Integer leaseTimeInSeconds, final String proposedLeaseId, - final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public String execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = ContainerRequest.lease(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), LeaseAction.ACQUIRE, leaseTimeInSeconds, proposedLeaseId, null, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - container.updatePropertiesFromResponse(request); - - return BlobResponse.getLeaseID(request, opContext); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Renews an existing lease with the specified access conditions. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the container. The lease - * ID is required to be set with an access condition. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void renewLease(final AccessCondition accessCondition) throws StorageException { - this.renewLease(accessCondition, null, null); - } - - /** - * Renews an existing lease with the specified access conditions, request options, and operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is - * required to be set with an access condition. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void renewLease(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - Utility.assertNotNull("accessCondition", accessCondition); - Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = ContainerRequest.lease(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), LeaseAction.RENEW, null, null, null, accessCondition, blobOptions, - opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - container.updatePropertiesFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Releases the lease on the container. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is - * required to be set with an access condition. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void releaseLease(final AccessCondition accessCondition) throws StorageException { - this.releaseLease(accessCondition, null, null); - } - - /** - * Releases the lease on the container using the specified access conditions, request options, and operation - * context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is - * required to be set with an access condition. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void releaseLease(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - Utility.assertNotNull("accessCondition", accessCondition); - Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = ContainerRequest.lease(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), LeaseAction.RELEASE, null, null, null, accessCondition, blobOptions, - opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - container.updatePropertiesFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Breaks the lease and ensures that another client cannot acquire a new lease until the current lease - * period has expired. - * - * @param breakPeriodInSeconds - * Specifies the time to wait, in seconds, until the current lease is broken. - * If null, the break period is the remainder of the current lease, or zero for infinite leases. - * - * @return The time, in seconds, remaining in the lease period. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final long breakLease(final Integer breakPeriodInSeconds) throws StorageException { - return this.breakLease(breakPeriodInSeconds, null, null, null); - } - - /** - * Breaks the existing lease, using the specified request options and operation context, and ensures that - * another client cannot acquire a new lease until the current lease period has expired. - * - * @param breakPeriodInSeconds - * Specifies the time to wait, in seconds, until the current lease is broken. - * If null, the break period is the remainder of the current lease, or zero for infinite leases. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return The time, in seconds, remaining in the lease period. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final long breakLease(final Integer breakPeriodInSeconds, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Long execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = ContainerRequest.lease(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), LeaseAction.BREAK, null, null, breakPeriodInSeconds, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return -1L; - } - - container.updatePropertiesFromResponse(request); - final String leaseTime = BlobResponse.getLeaseTime(request, opContext); - return Utility.isNullOrEmpty(leaseTime) ? -1L : Long.parseLong(leaseTime); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Changes the existing lease ID to the proposed lease ID. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is - * required to be set with an access condition. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void changeLease(final String proposedLeaseId, final AccessCondition accessCondition) - throws StorageException { - this.changeLease(proposedLeaseId, accessCondition, null, null); - } - - /** - * Changes the existing lease ID to the proposed lease Id with the specified access conditions, request options, - * and operation context. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. The lease ID is - * required to be set with an access condition. - * - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client - * ({@link CloudBlobClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. The context - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public final void changeLease(final String proposedLeaseId, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException { - Utility.assertNotNull("accessCondition", accessCondition); - Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudBlobClient client, final CloudBlobContainer container, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = ContainerRequest.lease(container.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), LeaseAction.CHANGE, null, proposedLeaseId, null, accessCondition, - blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - container.updatePropertiesFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobDirectory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobDirectory.java deleted file mode 100644 index 6f5d16588cbc0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlobDirectory.java +++ /dev/null @@ -1,466 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.EnumSet; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Represents a virtual directory of blobs, designated by a delimiter character. - *

- * Containers, which are encapsulated as {@link CloudBlobContainer} objects, hold directories, and directories hold - * block blobs and page blobs. Directories can also contain sub-directories. - */ -public final class CloudBlobDirectory implements ListBlobItem { - - /** - * Holds the Blobs container Reference. - */ - private CloudBlobContainer container; - - /** - * Represents the blob's directory. - */ - protected CloudBlobDirectory parent; - - /** - * Represents the blob client. - */ - protected CloudBlobClient blobServiceClient; - - /** - * Holds the URI of the directory. - */ - private final URI uri; - - /** - * Holds the prefix for the directory. - */ - private String prefix; - - /** - * Creates an instance of the CloudBlobDirectory class using the specified address and client. - * - * @param relativeAddress - * A String that represents the blob directory's relative address. - * @param client - * A {@link CloudBlobClient} object that represents the associated service client. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - protected CloudBlobDirectory(String relativeAddress, final CloudBlobClient client) throws URISyntaxException, - StorageException { - Utility.assertNotNullOrEmpty("relativeAddress", relativeAddress); - Utility.assertNotNull("client", client); - - this.blobServiceClient = client; - - if (this.blobServiceClient.getDirectoryDelimiter() != null - && !relativeAddress.endsWith(this.blobServiceClient.getDirectoryDelimiter())) { - relativeAddress = relativeAddress.concat(this.blobServiceClient.getDirectoryDelimiter()); - } - - this.uri = PathUtility.appendPathToUri(this.blobServiceClient.getEndpoint(), relativeAddress); - } - - /** - * Creates an instance of the CloudBlobDirectory class using the specified address, directory parent, - * and client. - * - * @param uri - * A String that represents the blob directory's address. - * @param parent - * A CloudBlobDirectory object that represents the parent directory, if applicable. - * @param client - * A {@link CloudBlobClient} object that represents the associated service client. - */ - protected CloudBlobDirectory(final URI uri, final CloudBlobDirectory parent, final CloudBlobClient client) { - Utility.assertNotNull("uri", uri); - Utility.assertNotNull("client", client); - - this.blobServiceClient = client; - this.uri = uri; - this.parent = parent; - } - - /** - * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this directory. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlockBlob getBlockBlobReference(final String blobAddressUri) throws URISyntaxException, - StorageException { - return this.getBlockBlobReference(blobAddressUri, null); - } - - /** - * Returns a reference to a {@link CloudBlockBlob} object that represents a block blob in this directory, using the - * specified snapshot ID. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * @param snapshotID - * A String that represents the snapshot ID of the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified block blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlockBlob getBlockBlobReference(final String blobAddressUri, final String snapshotID) - throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI address = PathUtility.appendPathToUri(this.uri, blobAddressUri, - this.blobServiceClient.getDirectoryDelimiter()); - - final CloudBlockBlob retBlob = new CloudBlockBlob(address, snapshotID, this.blobServiceClient); - retBlob.setContainer(this.container); - return retBlob; - } - - /** - * Returns the container for this directory. - * - * @return A {@link CloudBlobContainer} that represents the container for this directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @Override - public CloudBlobContainer getContainer() throws StorageException, URISyntaxException { - if (this.container == null) { - final URI containerURI = PathUtility.getContainerURI(this.uri, this.blobServiceClient.isUsePathStyleUris()); - this.container = new CloudBlobContainer(containerURI, this.blobServiceClient); - } - - return this.container; - } - - /** - * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in the directory. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified page blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudPageBlob getPageBlobReference(final String blobAddressUri) throws URISyntaxException, StorageException { - return this.getPageBlobReference(blobAddressUri, null); - } - - /** - * Returns a reference to a {@link CloudPageBlob} object that represents a page blob in the directory, using the - * specified snapshot ID. - * - * @param blobAddressUri - * A String that represents the name of the blob, or the absolute URI to the blob. - * @param snapshotID - * A String that represents the snapshot ID of the blob. - * - * @return A {@link CloudBlockBlob} object that represents a reference to the specified page blob. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudPageBlob getPageBlobReference(final String blobAddressUri, final String snapshotID) - throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("blobAddressUri", blobAddressUri); - - final URI address = PathUtility.appendPathToUri(this.uri, blobAddressUri, - this.blobServiceClient.getDirectoryDelimiter()); - - final CloudPageBlob retBlob = new CloudPageBlob(address, snapshotID, this.blobServiceClient); - retBlob.setContainer(this.container); - - return retBlob; - } - - /** - * Returns the parent directory of this directory. - * - * @return A {@link CloudBlobDirectory} object that represents the parent of this directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @Override - public CloudBlobDirectory getParent() throws URISyntaxException, StorageException { - if (this.parent == null) { - final URI parentURI = PathUtility.getParentAddress(this.uri, - this.blobServiceClient.getDirectoryDelimiter(), this.blobServiceClient.isUsePathStyleUris()); - this.parent = new CloudBlobDirectory(parentURI, null, this.blobServiceClient); - } - return this.parent; - } - - /** - * Returns the prefix for this directory. - * - * @return A String that represents the prefix for this directory. - * - * @throws StorageException - * If a storage service error occurred. - */ - protected String getPrefix() throws StorageException { - if (this.prefix == null) { - try { - final String containerUri = this.getContainer().getUri().toString().concat("/"); - this.prefix = Utility.safeRelativize(new URI(containerUri), this.uri); - } - catch (final URISyntaxException e) { - final StorageException wrappedUnexpectedException = Utility.generateNewUnexpectedStorageException(e); - throw wrappedUnexpectedException; - } - } - - return this.prefix; - } - - /** - * Returns the Blob service client associated with this directory. - * - * @return An {@link CloudBlobClient} object that represents the service client associated with the directory. - */ - public CloudBlobClient getServiceClient() { - return this.blobServiceClient; - } - - /** - * Returns a reference to a virtual blob directory beneath this directory. - * - * @param relativeAddress - * A String that represents the name of the virtual blob directory, or the absolute URI to - * the virtual blob directory. - * - * @return A CloudBlobDirectory object that represents a virtual blob directory beneath this directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudBlobDirectory getSubDirectoryReference(final String relativeAddress) throws StorageException, - URISyntaxException { - Utility.assertNotNullOrEmpty("relativeAddress", relativeAddress); - - final URI address = PathUtility.appendPathToUri(this.uri, relativeAddress, - this.blobServiceClient.getDirectoryDelimiter()); - - return new CloudBlobDirectory(address, this, this.blobServiceClient); - } - - /** - * Returns the URI for this directory. - * - * @return A java.net.URI object that represents the URI for this directory. - */ - @Override - public URI getUri() { - return this.uri; - } - - /** - * Returns an enumerable collection of blob items for the directory. - * - * @return An enumerable collection of {@link ListBlobItem} objects that represent the block items in this - * container. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @DoesServiceRequest - public Iterable listBlobs() throws StorageException, URISyntaxException { - return this.getContainer().listBlobs(this.getPrefix()); - } - - /** - * Returns an enumerable collection of blob items whose names begin with the specified prefix for the directory. - * - * @param prefix - * A String that represents the blob name prefix. - * - * @return An enumerable collection of {@link ListBlobItem} objects that represent the block items whose names begin - * with the specified prefix in this directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @DoesServiceRequest - public Iterable listBlobs(String prefix) throws URISyntaxException, StorageException { - prefix = prefix == null ? Constants.EMPTY_STRING : prefix; - return this.getContainer().listBlobs(this.getPrefix().concat(prefix)); - } - - /** - * Returns an enumerable collection of blob items whose names begin with the specified prefix, using the specified - * flat or hierarchical option, listing details options, request options, and operation context. - * - * @param prefix - * A String that represents the prefix of the blob name. - * @param useFlatBlobListing - * true to indicate that the returned list will be flat; false to indicate that - * the returned list will be hierarchical. - * @param listingDetails - * A java.util.EnumSet object that contains {@link BlobListingDetails} values that indicate - * whether snapshots, metadata, and/or uncommitted blocks are returned. Committed blocks are always - * returned. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An enumerable collection of {@link ListBlobItem} objects that represent the block items whose names begin - * with the specified prefix in this directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @DoesServiceRequest - public Iterable listBlobs(String prefix, final boolean useFlatBlobListing, - final EnumSet listingDetails, final BlobRequestOptions options, - final OperationContext opContext) throws URISyntaxException, StorageException { - prefix = prefix == null ? Constants.EMPTY_STRING : prefix; - return this.getContainer().listBlobs(this.getPrefix().concat(prefix), useFlatBlobListing, listingDetails, - options, opContext); - } - - /** - * Returns a result segment of an enumerable collection of blob items in the directory. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link ListBlobItem} objects that represent the blob items in the directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @DoesServiceRequest - public ResultSegment listBlobsSegmented() throws StorageException, URISyntaxException { - return this.getContainer().listBlobsSegmented(this.getPrefix()); - } - - /** - * Returns a result segment containing a collection of blob items whose names begin with the specified prefix. - * - * @param prefix - * A String that represents the prefix of the blob name. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link ListBlobItem} objects that represent the blob items whose names begin with the specified prefix in - * the directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @DoesServiceRequest - public ResultSegment listBlobsSegmented(String prefix) throws StorageException, URISyntaxException { - prefix = prefix == null ? Constants.EMPTY_STRING : prefix; - return this.getContainer().listBlobsSegmented(this.getPrefix().concat(prefix)); - } - - /** - * Returns a result segment containing a collection of blob items whose names begin with the specified prefix, using - * the specified flat or hierarchical option, listing details options, request options, and operation context. - * - * @param prefix - * A String that represents the prefix of the blob name. - * @param useFlatBlobListing - * true to indicate that the returned list will be flat; false to indicate that - * the returned list will be hierarchical. - * @param listingDetails - * A java.util.EnumSet object that contains {@link BlobListingDetails} values that indicate - * whether snapshots, metadata, and/or uncommitted blocks are returned. Committed blocks are always - * returned. - * @param maxResults - * The maximum number of results to retrieve. - * @param continuationToken - * A {@link ResultContinuation} object that represents a continuation token returned by a previous - * listing operation. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link ResultSegment} object that contains a segment of the enumerable collection of - * {@link ListBlobItem} objects that represent the block items whose names begin with the specified prefix - * in the directory. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - @DoesServiceRequest - public ResultSegment listBlobsSegmented(String prefix, final boolean useFlatBlobListing, - final EnumSet listingDetails, final int maxResults, - final ResultContinuation continuationToken, final BlobRequestOptions options, - final OperationContext opContext) throws StorageException, URISyntaxException { - prefix = prefix == null ? Constants.EMPTY_STRING : prefix; - return this.getContainer().listBlobsSegmented(this.getPrefix().concat(prefix), useFlatBlobListing, - listingDetails, maxResults, continuationToken, options, opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlockBlob.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlockBlob.java deleted file mode 100644 index d6724ed776ae1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlockBlob.java +++ /dev/null @@ -1,649 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.util.ArrayList; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.StreamMd5AndLength; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * Represents a blob that is uploaded as a set of blocks. - */ -public final class CloudBlockBlob extends CloudBlob { - - /** - * Creates an instance of the CloudBlockBlob class using the specified relative URI and storage service - * client. - * - * @param uri - * A java.net.URI object that represents the relative URI to the blob, beginning with the - * container name. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudBlockBlob(final URI uri) throws StorageException { - super(BlobType.BLOCK_BLOB); - - Utility.assertNotNull("blobAbsoluteUri", uri); - this.uri = uri; - this.parseURIQueryStringAndVerify(uri, null, Utility.determinePathStyleFromUri(uri, null));; - } - - /** - * Creates an instance of the CloudBlockBlob class by copying values from another cloud block blob. - * - * @param otherBlob - * A CloudBlockBlob object that represents the block blob to copy. - * - * @throws StorageException - * If a storage service error occurs. - */ - public CloudBlockBlob(final CloudBlockBlob otherBlob) throws StorageException { - super(otherBlob); - } - - /** - * Creates an instance of the CloudBlockBlob class using the specified relative URI and storage service - * client. - * - * @param uri - * A java.net.URI object that represents the relative URI to the blob, beginning with the - * container name. - * @param client - * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudBlockBlob(final URI uri, final CloudBlobClient client) throws StorageException { - super(BlobType.BLOCK_BLOB, uri, client); - } - - /** - * Creates an instance of the CloudBlockBlob class using the specified relative URI, storage service - * client and container. - * - * @param uri - * A java.net.URI object that represents the relative URI to the blob. - * @param client - * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. - * @param container - * A {@link CloudBlobContainer} object that represents the container to use for the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudBlockBlob(final URI uri, final CloudBlobClient client, final CloudBlobContainer container) - throws StorageException { - super(BlobType.BLOCK_BLOB, uri, client, container); - } - - /** - * Creates an instance of the CloudBlockBlob class using the specified relative URI, snapshot ID, and - * storage service client. - * - * @param uri - * A java.net.URI object that represents the relative URI to the blob. - * @param snapshotID - * A String that represents the snapshot version, if applicable. - * @param client - * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudBlockBlob(final URI uri, final String snapshotID, final CloudBlobClient client) throws StorageException { - super(BlobType.BLOCK_BLOB, uri, snapshotID, client); - } - - /** - * Commits a block list to the storage service. - * - * @param blockList - * An enumerable collection of BlockEntry objects that represents the list block items being - * committed. The size field is ignored. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void commitBlockList(final Iterable blockList) throws StorageException { - this.commitBlockList(blockList, null, null, null); - } - - /** - * Commits a block list to the storage service using the specified lease ID, request options, and operation context. - * - * @param blockList - * An enumerable collection of BlockEntry objects that represents the list block items being - * committed. The size field is ignored. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void commitBlockList(final Iterable blockList, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException { - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.putBlockList(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), blob.properties, accessCondition, blobOptions, opContext); - this.setConnection(request); - - BlobRequest.addMetadata(request, blob.metadata, opContext); - - // Potential optimization, we can write this stream outside of - // the StorageOperation, so it wont need to be rewritten for each retry. Because it would - // need to be a final member this would require refactoring into an internal method which - // receives the block list bytestream as a final param. - - final byte[] blockListBytes = BlobRequest.writeBlockListToStream(blockList, opContext); - - final ByteArrayInputStream blockListInputStream = new ByteArrayInputStream(blockListBytes); - - final StreamMd5AndLength descriptor = Utility.analyzeStream(blockListInputStream, -1L, -1L, - true /* rewindSourceStream */, true /* calculateMD5 */); - - request.setRequestProperty(Constants.HeaderConstants.CONTENT_MD5, descriptor.getMd5()); - - this.signRequest(client, request, descriptor.getLength(), null); - - Utility.writeToOutputStream(blockListInputStream, request.getOutputStream(), descriptor.getLength(), - false, false, null, opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Downloads the committed block list from the block blob. - *

- * The committed block list includes the list of blocks that have been successfully committed to the block blob. The - * list of committed blocks is returned in the same order that they were committed to the blob. No block may appear - * more than once in the committed block list. - * - * @return An ArrayList object of BlockEntry objects that represent the committed list - * block items downloaded from the block blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ArrayList downloadBlockList() throws StorageException { - return this.downloadBlockList(BlockListingFilter.COMMITTED, null, null, null); - } - - /** - * Downloads the block list from the block blob using the specified block listing filter, request options, and - * operation context. - * - * @param blockListingFilter - * A {@link BlockListingFilter} value that specifies whether to download committed blocks, uncommitted - * blocks, or all blocks. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An ArrayList object of BlockEntry objects that represent the list block items - * downloaded from the block blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ArrayList downloadBlockList(final BlockListingFilter blockListingFilter, - final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException { - Utility.assertNotNull("blockListingFilter", blockListingFilter); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - final StorageOperation> impl = new StorageOperation>( - options) { - - @Override - public ArrayList execute(final CloudBlobClient client, final CloudBlob blob, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.getBlockList(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, blockListingFilter, accessCondition, - blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - blob.updateLengthFromResponse(request); - - final GetBlockListResponse response = new GetBlockListResponse(request.getInputStream()); - return response.getBlocks(); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Creates and opens an output stream to write data to the block blob. - * - * @return A {@link BlobOutputStream} object used to write data to the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - public BlobOutputStream openOutputStream() throws StorageException { - return this.openOutputStream(null, null, null); - } - - /** - * Creates and opens an output stream to write data to the block blob using the specified request options and - * operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link BlobOutputStream} object used to write data to the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - public BlobOutputStream openOutputStream(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - assertNoWriteOperationForSnapshot(); - - options.applyDefaults(this.blobServiceClient); - - return new BlobOutputStream(this, accessCondition, options, opContext); - } - - /** - * Uploads the source stream data to the block blob. - * - * @param sourceStream - * An InputStream object that represents the input stream to write to the block blob. - * @param length - * The length, in bytes, of the stream data, or -1 if unknown. - * - * @throws IOException - * If an I/O error occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - @DoesServiceRequest - public void upload(final InputStream sourceStream, final long length) throws StorageException, IOException { - this.upload(sourceStream, length, null, null, null); - } - - /** - * Uploads the source stream data to the blob, using the specified lease ID, request options, and operation context. - * - * @param sourceStream - * An InputStream object that represents the input stream to write to the block blob. - * @param length - * The length, in bytes, of the stream data, or -1 if unknown. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IOException - * If an I/O error occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - @DoesServiceRequest - public void upload(final InputStream sourceStream, final long length, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException { - if (length < -1) { - throw new IllegalArgumentException( - "Invalid stream length, specify -1 for unkown length stream, or a positive number of bytes"); - } - - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.blobServiceClient); - - StreamMd5AndLength descriptor = new StreamMd5AndLength(); - descriptor.setLength(length); - - if (sourceStream.markSupported()) { - // Mark sourceStream for current position. - sourceStream.mark(Constants.MAX_MARK_LENGTH); - } - - // If the stream is rewindable and the length is unknown or we need to - // set md5, then analyze the stream. - // Note this read will abort at - // serviceClient.getSingleBlobPutThresholdInBytes() bytes and return - // -1 as length in which case we will revert to using a stream as it is - // over the single put threshold. - if (sourceStream.markSupported() && (length < 0 || options.getStoreBlobContentMD5())) { - // If the stream is of unknown length or we need to calculate - // the MD5, then we we need to read the stream contents first - - descriptor = Utility.analyzeStream(sourceStream, length, - this.blobServiceClient.getSingleBlobPutThresholdInBytes(), true /* rewindSourceStream */, - options.getStoreBlobContentMD5()); - - if (descriptor.getMd5() != null && options.getStoreBlobContentMD5()) { - this.properties.setContentMD5(descriptor.getMd5()); - } - } - - // If the stream is rewindable, and the length is known and less than - // threshold the upload in a single put, otherwise use a stream. - if (sourceStream.markSupported() && descriptor.getLength() != -1 - && descriptor.getLength() < this.blobServiceClient.getSingleBlobPutThresholdInBytes()) { - this.uploadFullBlob(sourceStream, descriptor.getLength(), accessCondition, options, opContext); - } - else { - final BlobOutputStream writeStream = this.openOutputStream(accessCondition, options, opContext); - writeStream.write(sourceStream, length); - writeStream.close(); - } - } - - /** - * Uploads a block to the block blob, using the specified block ID and lease ID. - * - * @param blockId - * A String that represents the Base-64 encoded block ID. Note for a given blob the length - * of all Block IDs must be identical. - * @param sourceStream - * An InputStream object that represents the input stream to write to the block blob. - * @param length - * The length, in bytes, of the stream data, or -1 if unknown. - * @throws IOException - * If an I/O error occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadBlock(final String blockId, final InputStream sourceStream, final long length) - throws StorageException, IOException { - this.uploadBlock(blockId, sourceStream, length, null, null, null); - } - - /** - * Uploads a block to the block blob, using the specified block ID, lease ID, request options, and operation - * context. - * - * @param blockId - * A String that represents the Base-64 encoded block ID. Note for a given blob the length - * of all Block IDs must be identical. - * - * @param sourceStream - * An InputStream object that represents the input stream to write to the block blob. - * @param length - * The length, in bytes, of the stream data, or -1 if unknown. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IOException - * If an I/O error occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadBlock(final String blockId, final InputStream sourceStream, final long length, - final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException, IOException { - if (length < -1) { - throw new IllegalArgumentException( - "Invalid stream length, specify -1 for unkown length stream, or a positive number of bytes"); - } - - if (length > 4 * Constants.MB) { - throw new IllegalArgumentException( - "Invalid stream length, length must be less than or equal to 4 MB in size."); - } - - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - - // Assert block length - if (Utility.isNullOrEmpty(blockId) || !Base64.validateIsBase64String(blockId)) { - throw new IllegalArgumentException("Invalid blockID, BlockID must be a valid Base64 String."); - } - - if (sourceStream.markSupported()) { - // Mark sourceStream for current position. - sourceStream.mark(Constants.MAX_MARK_LENGTH); - } - - InputStream bufferedStreamReference = sourceStream; - StreamMd5AndLength descriptor = new StreamMd5AndLength(); - descriptor.setLength(length); - - if (!sourceStream.markSupported()) { - // needs buffering - final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - descriptor = Utility.writeToOutputStream(sourceStream, byteStream, length, false /* rewindSourceStream */, - options.getUseTransactionalContentMD5(), null, opContext); - - bufferedStreamReference = new ByteArrayInputStream(byteStream.toByteArray()); - } - else if (length < 0 || options.getUseTransactionalContentMD5()) { - // If the stream is of unknown length or we need to calculate the - // MD5, then we we need to read the stream contents first - - descriptor = Utility.analyzeStream(sourceStream, length, -1L, true /* rewindSourceStream */, - options.getUseTransactionalContentMD5()); - } - - if (descriptor.getLength() > 4 * Constants.MB) { - throw new IllegalArgumentException( - "Invalid stream length, length must be less than or equal to 4 MB in size."); - } - - this.uploadBlockInternal(blockId, descriptor.getMd5(), bufferedStreamReference, descriptor.getLength(), - accessCondition, options, opContext); - } - - /** - * Uploads a block of the blob to the server. - * - * @param blockId - * the Base64 Encoded Block ID - * @param md5 - * the MD5 to use if it will be set. - * @param sourceStream - * the InputStream to read from - * @param length - * the OutputStream to write the blob to. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * An object that specifies any additional options for the request - * @param opContext - * an object used to track the execution of the operation - * @throws StorageException - * If a storage service error occurred. - * @throws IOException - */ - @DoesServiceRequest - private void uploadBlockInternal(final String blockId, final String md5, final InputStream sourceStream, - final long length, final AccessCondition accessCondition, final BlobRequestOptions options, - final OperationContext opContext) throws StorageException, IOException { - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.putBlock(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), blockId, accessCondition, blobOptions, opContext); - this.setConnection(request); - - if (blobOptions.getUseTransactionalContentMD5()) { - request.setRequestProperty(Constants.HeaderConstants.CONTENT_MD5, md5); - } - - this.signRequest(client, request, length, null); - - Utility.writeToOutputStream(sourceStream, request.getOutputStream(), length, - true /* rewindSourceStream */, false /* calculateMD5 */, null, opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudPageBlob.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudPageBlob.java deleted file mode 100644 index 38611d54063ee..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudPageBlob.java +++ /dev/null @@ -1,699 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * Represents a Windows Azure page blob. - */ -public final class CloudPageBlob extends CloudBlob { - /** - * Creates an instance of the CloudPageBlob class using the specified relative URI and storage service - * client. - * - * @param uri - * A java.net.URI object that represents the relative URI to the blob, beginning with the - * container name. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudPageBlob(final URI uri) throws StorageException { - super(BlobType.PAGE_BLOB); - - Utility.assertNotNull("blobAbsoluteUri", uri); - this.uri = uri; - this.parseURIQueryStringAndVerify(uri, null, Utility.determinePathStyleFromUri(uri, null));; - } - - /** - * Creates an instance of the CloudPageBlob class by copying values from another page blob. - * - * @param otherBlob - * A CloudPageBlob object that represents the page blob to copy. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudPageBlob(final CloudPageBlob otherBlob) throws StorageException { - super(otherBlob); - } - - /** - * Creates an instance of the CloudPageBlob class using the specified URI and cloud blob client. - * - * @param uri - * A java.net.URI object that represents the absolute URI to the blob, beginning with the - * container name. - * @param client - * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudPageBlob(final URI uri, final CloudBlobClient client) throws StorageException { - super(BlobType.PAGE_BLOB, uri, client); - } - - /** - * Creates an instance of the CloudPageBlob class using the specified URI, cloud blob client, and cloud - * blob container. - * - * @param uri - * A java.net.URI object that represents the relative URI to the blob, beginning with the - * container name. - * @param client - * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. - * @param container - * A {@link CloudBlobContainer} object that represents the container to use for the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudPageBlob(final URI uri, final CloudBlobClient client, final CloudBlobContainer container) - throws StorageException { - super(BlobType.PAGE_BLOB, uri, client, container); - } - - /** - * Creates an instance of the CloudPageBlob class using the specified URI, snapshot ID, and cloud blob - * client. - * - * @param uri - * A java.net.URI object that represents the absolute URI to the blob, beginning with the - * container name. - * @param snapshotID - * A String that represents the snapshot version, if applicable. - * @param client - * A {@link CloudBlobContainer} object that represents the container to use for the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - public CloudPageBlob(final URI uri, final String snapshotID, final CloudBlobClient client) throws StorageException { - super(BlobType.PAGE_BLOB, uri, snapshotID, client); - } - - /** - * Clears pages from a page blob. - *

- * Calling clearPages releases the storage space used by the specified pages. Pages that have been - * cleared are no longer tracked as part of the page blob, and no longer incur a charge against the storage account. - * - * @param offset - * The offset, in bytes, at which to begin clearing pages. This value must be a multiple of 512. - * @param length - * The length, in bytes, of the data range to be cleared. This value must be a multiple of 512. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void clearPages(final long offset, final long length) throws StorageException, IOException { - this.clearPages(offset, length, null, null, null); - } - - /** - * Clears pages from a page blob using the specified lease ID, request options, and operation context. - *

- * Calling clearPages releases the storage space used by the specified pages. Pages that have been - * cleared are no longer tracked as part of the page blob, and no longer incur a charge against the storage account. - * - * @param offset - * The offset, in bytes, at which to begin clearing pages. This value must be a multiple of 512. - * @param length - * The length, in bytes, of the data range to be cleared. This value must be a multiple of 512. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void clearPages(final long offset, final long length, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException { - if (offset % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("Page start offset must be multiple of 512!"); - } - - if (length % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("Page data must be multiple of 512!"); - } - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - final PageProperties pageProps = new PageProperties(); - pageProps.setPageOperation(PageOperationType.CLEAR); - pageProps.getRange().setStartOffset(offset); - pageProps.getRange().setEndOffset(offset + length - 1); - - this.putPagesInternal(pageProps, null, length, null, accessCondition, options, opContext); - } - - /** - * Creates a page blob. - * - * @param length - * The size, in bytes, of the page blob. - * - * @throws IllegalArgumentException - * If the length is not a multiple of 512. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void create(final long length) throws StorageException { - this.create(length, null, null, null); - } - - /** - * Creates a page blob using the specified request options and operation context. - * - * @param length - * The size, in bytes, of the page blob. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IllegalArgumentException - * If the length is not a multiple of 512. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void create(final long length, final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - assertNoWriteOperationForSnapshot(); - - if (length % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("Page blob length must be multiple of 512."); - } - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.put(blob.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), blob.properties, BlobType.PAGE_BLOB, length, - accessCondition, blobOptions, opContext); - this.setConnection(request); - - BlobRequest.addMetadata(request, blob.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Returns a collection of page ranges and their starting and ending byte offsets. - *

- * The start and end byte offsets for each page range are inclusive. - * - * @return An ArrayList object that represents the set of page ranges and their starting and ending - * byte offsets. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ArrayList downloadPageRanges() throws StorageException { - return this.downloadPageRanges(null, null, null); - } - - /** - * Returns a collection of page ranges and their starting and ending byte offsets using the specified request - * options and operation context. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An ArrayList object that represents the set of page ranges and their starting and ending - * byte offsets. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public ArrayList downloadPageRanges(final AccessCondition accessCondition, BlobRequestOptions options, - OperationContext opContext) throws StorageException { - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - - final StorageOperation> impl = new StorageOperation>( - options) { - - @Override - public ArrayList execute(final CloudBlobClient client, final CloudBlob blob, - final OperationContext opContext) throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.getPageRanges(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - blob.updateLengthFromResponse(request); - - final GetPageRangesResponse response = new GetPageRangesResponse(request.getInputStream()); - return response.getPageRanges(); - } - }; - - return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Opens an input stream object to write data to the page blob. - * - * @param length - * The length, in bytes, of the stream to create. This value must be a multiple of 512. - * - * @return A {@link BlobOutputStream} object used to write data to the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public BlobOutputStream openOutputStream(final long length) throws StorageException { - return this.openOutputStream(length, null, null, null); - } - - /** - * Opens an input stream object to write data to the page blob, using the specified lease ID, request options and - * operation context. - * - * @param length - * The length, in bytes, of the stream to create. This value must be a multiple of 512. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link BlobOutputStream} object used to write data to the blob. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public BlobOutputStream openOutputStream(final long length, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - assertNoWriteOperationForSnapshot(); - - options.applyDefaults(this.blobServiceClient); - - if (options.getStoreBlobContentMD5()) { - throw new IllegalArgumentException("Blob Level MD5 is not supported for PageBlob"); - } - - return new BlobOutputStream(this, length, accessCondition, options, opContext); - } - - /** - * Used for both uploadPages and clearPages. - * - * @param pageProperties - * The page properties. - * @param data - * The data to write. - * @param length - * The number of bytes to write. - * @param md5 - * the MD5 hash for the data. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - private void putPagesInternal(final PageProperties pageProperties, final byte[] data, final long length, - final String md5, final AccessCondition accessCondition, final BlobRequestOptions options, - final OperationContext opContext) throws StorageException { - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) - throws Exception { - final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); - - final HttpURLConnection request = BlobRequest.putPage(blob.getTransformedAddress(opContext), - blobOptions.getTimeoutIntervalInMs(), pageProperties, accessCondition, blobOptions, opContext); - this.setConnection(request); - - if (pageProperties.getPageOperation() == PageOperationType.UPDATE) { - if (blobOptions.getUseTransactionalContentMD5()) { - request.setRequestProperty(Constants.HeaderConstants.CONTENT_MD5, md5); - } - - this.signRequest(client, request, length, null); - - request.getOutputStream().write(data); - } - else { - this.signRequest(client, request, 0L, null); - } - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - blob.updateEtagAndLastModifiedFromResponse(request); - return null; - } - }; - - ExecutionEngine - .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Uploads the source stream data to the page blob. - * - * @param sourceStream - * An IntputStream object to read from. - * @param length - * The length, in bytes, of the stream data, must be non zero and a multiple of 512. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - @DoesServiceRequest - public void upload(final InputStream sourceStream, final long length) throws StorageException, IOException { - this.upload(sourceStream, length, null, null, null); - } - - /** - * Uploads the source stream data to the page blob using the specified lease ID, request options, and operation - * context. - * - * @param sourceStream - * An IntputStream object to read from. - * @param length - * The length, in bytes, of the stream data. This must be great than zero and a multiple of 512. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - @DoesServiceRequest - public void upload(final InputStream sourceStream, final long length, final AccessCondition accessCondition, - BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException { - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - if (length <= 0 || length % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("Page data must be multiple of 512!"); - } - - if (options.getStoreBlobContentMD5()) { - throw new IllegalArgumentException("Blob Level MD5 is not supported for PageBlob"); - } - - if (sourceStream.markSupported()) { - // Mark sourceStream for current position. - sourceStream.mark(Constants.MAX_MARK_LENGTH); - } - - if (length <= 4 * Constants.MB) { - this.create(length, accessCondition, options, opContext); - this.uploadPages(sourceStream, 0, length, accessCondition, options, opContext); - } - else { - final OutputStream streamRef = this.openOutputStream(length, accessCondition, options, opContext); - Utility.writeToOutputStream(sourceStream, streamRef, length, false, false, null, opContext); - streamRef.close(); - } - } - - /** - * Uploads a range of contiguous pages, up to 4 MB in size, at the specified offset in the page blob. - * - * @param sourceStream - * An InputStream object that represents the input stream to write to the page blob. - * @param offset - * The offset, in number of bytes, at which to begin writing the data. This value must be a multiple of - * 512. - * @param length - * The length, in bytes, of the data to write. This value must be a multiple of 512. - * - * @throws IllegalArgumentException - * If the offset or length are not multiples of 512, or if the length is greater than 4 MB. - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPages(final InputStream sourceStream, final long offset, final long length) - throws StorageException, IOException { - this.uploadPages(sourceStream, offset, length, null, null, null); - } - - /** - * Uploads a range of contiguous pages, up to 4 MB in size, at the specified offset in the page blob, using the - * specified lease ID, request options, and operation context. - * - * @param sourceStream - * An InputStream object that represents the input stream to write to the page blob. - * @param offset - * The offset, in number of bytes, at which to begin writing the data. This value must be a multiple of - * 512. - * @param length - * The length, in bytes, of the data to write. This value must be a multiple of 512. - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param options - * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws IllegalArgumentException - * If the offset or length are not multiples of 512, or if the length is greater than 4 MB. - * @throws IOException - * If an I/O exception occurred. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPages(final InputStream sourceStream, final long offset, final long length, - final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) - throws StorageException, IOException { - - if (offset % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("Page start offset must be multiple of 512!"); - } - - if (length % BlobConstants.PAGE_SIZE != 0) { - throw new IllegalArgumentException("Page data must be multiple of 512!"); - } - - if (length > 4 * Constants.MB) { - throw new IllegalArgumentException("Max write size is 4MB. Please specify a smaller range."); - } - - assertNoWriteOperationForSnapshot(); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new BlobRequestOptions(); - } - - options.applyDefaults(this.blobServiceClient); - - final PageProperties pageProps = new PageProperties(); - pageProps.setPageOperation(PageOperationType.UPDATE); - pageProps.getRange().setStartOffset(offset); - pageProps.getRange().setEndOffset(offset + length - 1); - final byte[] data = new byte[(int) length]; - String md5 = null; - - int count = 0; - long total = 0; - while (total < length) { - count = sourceStream.read(data, 0, (int) Math.min(length - total, Integer.MAX_VALUE)); - total += count; - } - - if (options.getUseTransactionalContentMD5()) { - try { - final MessageDigest digest = MessageDigest.getInstance("MD5"); - digest.update(data, 0, data.length); - md5 = Base64.encode(digest.digest()); - } - catch (final NoSuchAlgorithmException e) { - // This wont happen, throw fatal. - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - this.putPagesInternal(pageProps, data, length, md5, accessCondition, options, opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerListingDetails.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerListingDetails.java deleted file mode 100644 index 366ef2f8215a0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerListingDetails.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Specifies which details to include when listing the containers in this storage account. - */ -public enum ContainerListingDetails { - /** - * Specifies including all available details. - */ - ALL(1), - - /** - * Specifies including container metadata. - */ - METADATA(1), - - /** - * Specifies including no additional details. - */ - NONE(0); - - /** - * Returns the value of this enum. - */ - public int value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - ContainerListingDetails(final int val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerRequest.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerRequest.java deleted file mode 100644 index 4dfad857b93c1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerRequest.java +++ /dev/null @@ -1,471 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.IOException; -import java.io.StringWriter; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.HashMap; -import java.util.Map.Entry; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.Credentials; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseRequest; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LeaseAction; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ListingContext; - -/** - * RESERVED FOR INTERNAL USE. A class used to generate requests for contianer objects. - */ -final class ContainerRequest { - /** - * Adds user-defined metadata to the request as one or more name-value pairs. - * - * @param request - * The web request. - * @param metadata - * The user-defined metadata. - * */ - public static void addMetadata(final HttpURLConnection request, final HashMap metadata, - final OperationContext opContext) { - BaseRequest.addMetadata(request, metadata, opContext); - } - - /** - * Adds user-defined metadata to the request as a single name-value pair. - * - * @param request - * The web request. - * @param name - * The metadata name. - * @param value - * The metadata value. - * */ - public static void addMetadata(final HttpURLConnection request, final String name, final String value, - final OperationContext opContext) { - BaseRequest.addMetadata(request, name, value, opContext); - } - - /** - * Constructs a web request to create a new container. Sign with 0 length. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * @throws IllegalArgumentException - */ - public static HttpURLConnection create(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder containerBuilder = getContainerUriQueryBuilder(); - return BaseRequest.create(uri, timeout, containerBuilder, opContext); - } - - /** - * Creates the web request. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @param query - * The query builder to use. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * @throws IllegalArgumentException - */ - private static HttpURLConnection createURLConnection(final URI uri, final int timeout, final UriQueryBuilder query, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - return BaseRequest.createURLConnection(uri, timeout, query, opContext); - } - - /** - * Constructs a web request to delete the container and all of blobs within it. Sign with no length specified. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * @throws IllegalArgumentException - */ - public static HttpURLConnection delete(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder containerBuilder = getContainerUriQueryBuilder(); - return BaseRequest.delete(uri, timeout, containerBuilder, opContext); - } - - /** - * Constructs a web request to return the ACL for this container. Sign with no length specified. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - */ - public static HttpURLConnection getAcl(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder builder = getContainerUriQueryBuilder(); - builder.add("comp", "acl"); - - final HttpURLConnection request = createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("GET"); - - return request; - } - - /** - * Gets the container Uri query builder. - * - * A UriQueryBuilder for the container. - * - * @throws StorageException - */ - protected static UriQueryBuilder getContainerUriQueryBuilder() throws StorageException { - final UriQueryBuilder uriBuilder = new UriQueryBuilder(); - try { - uriBuilder.add("restype", "container"); - } - catch (final IllegalArgumentException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - return uriBuilder; - } - - /** - * Constructs a web request to retrieve the container's metadata. Sign with no length specified. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - */ - public static HttpURLConnection getMetadata(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder containerBuilder = getContainerUriQueryBuilder(); - return BaseRequest.getMetadata(uri, timeout, containerBuilder, opContext); - } - - /** - * Constructs a web request to return the user-defined metadata for this container. Sign with no length specified. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * */ - public static HttpURLConnection getProperties(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder containerBuilder = getContainerUriQueryBuilder(); - return BaseRequest.getProperties(uri, timeout, containerBuilder, opContext); - } - - /** - * Constructs a request to return a listing of all containers in this storage account. Sign with no length - * specified. - * - * @param uri - * The absolute URI for the account. - * @param timeout - * The absolute URI for the account. - * @param listingContext - * A set of parameters for the listing operation. - * @param detailsIncluded - * Additional details to return with the listing. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection configured for the operation. - * @throws IOException - * @throws URISyntaxException - * @throws StorageException - * @throws IllegalArgumentException - */ - public static HttpURLConnection list(final URI uri, final int timeout, final ListingContext listingContext, - final ContainerListingDetails detailsIncluded, final OperationContext opContext) throws URISyntaxException, - IOException, StorageException { - - final UriQueryBuilder builder = getContainerUriQueryBuilder(); - builder.add("comp", "list"); - - if (listingContext != null) { - if (!Utility.isNullOrEmpty(listingContext.getPrefix())) { - builder.add("prefix", listingContext.getPrefix()); - } - - if (!Utility.isNullOrEmpty(listingContext.getMarker())) { - builder.add("marker", listingContext.getMarker()); - } - - if (listingContext.getMaxResults() != null && listingContext.getMaxResults() > 0) { - builder.add("maxresults", listingContext.getMaxResults().toString()); - } - } - - if (detailsIncluded == ContainerListingDetails.ALL || detailsIncluded == ContainerListingDetails.METADATA) { - builder.add("include", "metadata"); - } - - final HttpURLConnection request = createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("GET"); - - return request; - } - - /** - * Sets the ACL for the container. , Sign with length of aclBytes. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @param publicAccess - * The type of public access to allow for the container. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * */ - public static HttpURLConnection setAcl(final URI uri, final int timeout, - final BlobContainerPublicAccessType publicAccess, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - final UriQueryBuilder builder = getContainerUriQueryBuilder(); - builder.add("comp", "acl"); - - final HttpURLConnection request = createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("PUT"); - request.setDoOutput(true); - - if (publicAccess != BlobContainerPublicAccessType.OFF) { - request.setRequestProperty(BlobConstants.BLOB_PUBLIC_ACCESS_HEADER, publicAccess.toString().toLowerCase()); - } - - return request; - } - - /** - * Constructs a web request to set user-defined metadata for the container, Sign with 0 Length. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * */ - public static HttpURLConnection setMetadata(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder containerBuilder = getContainerUriQueryBuilder(); - return BaseRequest.setMetadata(uri, timeout, containerBuilder, opContext); - } - - /** - * Constructs a HttpURLConnection to Acquire,Release,Break, or Renew a blob lease. Sign with 0 length. - * - * @param uri - * The absolute URI to the blob - * @param timeout - * The server timeout interval - * @param action - * the LeaseAction to perform - * - * @param visibilityTimeoutInSeconds - * Specifies the the span of time for which to acquire the lease, in seconds. - * If null, an infinite lease will be acquired. If not null, this must be greater than zero. - * - * @param proposedLeaseId - * A String that represents the proposed lease ID for the new lease, - * or null if no lease ID is proposed. - * - * @param breakPeriodInSeconds - * Specifies the amount of time to allow the lease to remain, in seconds. - * If null, the break period is the remainder of the current lease, or zero for infinite leases. - * - * @param accessCondition - * An {@link AccessCondition} object that represents the access conditions for the blob. - * @param blobOptions - * the options to use for the request. - * @param opContext - * a tracking object for the request - * @return a HttpURLConnection to use to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if the resource URI is invalid - * @throws StorageException - * an exception representing any error which occurred during the operation. - * @throws IllegalArgumentException - */ - public static HttpURLConnection lease(final URI uri, final int timeout, final LeaseAction action, - final Integer leaseTimeInSeconds, final String proposedLeaseId, final Integer breakPeriodInSeconds, - final AccessCondition accessCondition, final BlobRequestOptions blobOptions, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - - final UriQueryBuilder builder = getContainerUriQueryBuilder(); - builder.add("comp", "lease"); - - final HttpURLConnection request = createURLConnection(uri, timeout, builder, opContext); - - request.setDoOutput(true); - request.setRequestMethod("PUT"); - request.setFixedLengthStreamingMode(0); - request.setRequestProperty("x-ms-lease-action", action.toString()); - - if (leaseTimeInSeconds != null) { - request.setRequestProperty("x-ms-lease-duration", leaseTimeInSeconds.toString()); - } - else { - request.setRequestProperty("x-ms-lease-duration", "-1"); - } - - if (proposedLeaseId != null) { - request.setRequestProperty("x-ms-proposed-lease-id", proposedLeaseId); - } - - if (accessCondition != null) { - accessCondition.applyConditionToRequest(request); - } - return request; - } - - /** - * Signs the request for Shared Key authentication. - * - * @param request - * The web request. - * @param credentials - * The account credentials. - * @throws StorageException - * */ - public static void signRequest(final HttpURLConnection request, final Credentials credentials, - final Long contentLength, final OperationContext opContext) throws InvalidKeyException, StorageException { - BaseRequest.signRequestForBlobAndQueue(request, credentials, contentLength, opContext); - } - - /** - * Signs the request for Shared Key Lite authentication. - * - * @param request - * The web request. - * @param credentials - * The account credentials. - * @throws StorageException - * @throws InvalidKeyException - * */ - public static void signRequestForSharedKeyLite(final HttpURLConnection request, final Credentials credentials, - final Long contentLength, final OperationContext opContext) throws InvalidKeyException, StorageException { - BaseRequest.signRequestForBlobAndQueueSharedKeyLite(request, credentials, contentLength, opContext); - } - - /** - * Writes a collection of shared access policies to the specified stream in XML format. - * - * @param sharedAccessPolicies - * A collection of shared access policies - * @param outWriter - * an sink to write the output to. - * @throws XMLStreamException - */ - public static void writeSharedAccessIdentifiersToStream( - final HashMap sharedAccessPolicies, final StringWriter outWriter) - throws XMLStreamException { - Utility.assertNotNull("sharedAccessPolicies", sharedAccessPolicies); - Utility.assertNotNull("outWriter", outWriter); - - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outWriter); - - if (sharedAccessPolicies.keySet().size() > Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS) { - final String errorMessage = String - .format("Too many %d shared access policy identifiers provided. Server does not support setting more than %d on a single container.", - sharedAccessPolicies.keySet().size(), Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS); - - throw new IllegalArgumentException(errorMessage); - } - - // default is UTF8 - xmlw.writeStartDocument(); - xmlw.writeStartElement(Constants.SIGNED_IDENTIFIERS_ELEMENT); - - for (final Entry entry : sharedAccessPolicies.entrySet()) { - final SharedAccessBlobPolicy policy = entry.getValue(); - xmlw.writeStartElement(Constants.SIGNED_IDENTIFIER_ELEMENT); - - // Set the identifier - xmlw.writeStartElement(Constants.ID); - xmlw.writeCharacters(entry.getKey()); - xmlw.writeEndElement(); - - xmlw.writeStartElement(Constants.ACCESS_POLICY); - - // Set the Start Time - xmlw.writeStartElement(Constants.START); - xmlw.writeCharacters(Utility.getUTCTimeOrEmpty(policy.getSharedAccessStartTime())); - // end Start - xmlw.writeEndElement(); - - // Set the Expiry Time - xmlw.writeStartElement(Constants.EXPIRY); - xmlw.writeCharacters(Utility.getUTCTimeOrEmpty(policy.getSharedAccessExpiryTime())); - // end Expiry - xmlw.writeEndElement(); - - // Set the Permissions - xmlw.writeStartElement(Constants.PERMISSION); - xmlw.writeCharacters(SharedAccessBlobPolicy.permissionsToString(policy.getPermissions())); - // end Permission - xmlw.writeEndElement(); - - // end AccessPolicy - xmlw.writeEndElement(); - // end SignedIdentifier - xmlw.writeEndElement(); - } - - // end SignedIdentifiers - xmlw.writeEndElement(); - // end doc - xmlw.writeEndDocument(); - } - - /** - * Private Default Ctor - */ - private ContainerRequest() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerResponse.java deleted file mode 100644 index 1dbaec6bb4ee2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ContainerResponse.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Date; - -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseResponse; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse the response from container operations - */ -final class ContainerResponse extends BaseResponse { - - /** - * Gets the ACL for the container from the response. - * - * @param request - * the request object for this operation - * @return the ACL value indicating the public access level for the container - */ - public static String getAcl(final HttpURLConnection request) { - return request.getHeaderField(BlobConstants.BLOB_PUBLIC_ACCESS_HEADER); - } - - /** - * Gets the BlobContainerAttributes from the given request. - * - * @param request - * the request to get attributes from. - * @param usePathStyleUris - * a value indicating if the account is using pathSytleUris. - * @return the BlobContainerAttributes from the given request. - * @throws StorageException - */ - public static BlobContainerAttributes getAttributes(final HttpURLConnection request, final boolean usePathStyleUris) - throws StorageException { - final BlobContainerAttributes containerAttributes = new BlobContainerAttributes(); - URI tempURI; - try { - tempURI = PathUtility.stripURIQueryAndFragment(request.getURL().toURI()); - } - catch (final URISyntaxException e) { - final StorageException wrappedUnexpectedException = Utility.generateNewUnexpectedStorageException(e); - throw wrappedUnexpectedException; - } - - containerAttributes.setUri(tempURI); - containerAttributes.setName(PathUtility.getContainerNameFromUri(tempURI, usePathStyleUris)); - - final BlobContainerProperties containerProperties = containerAttributes.getProperties(); - containerProperties.setEtag(BaseResponse.getEtag(request)); - containerProperties.setLastModified(new Date(request.getLastModified())); - containerAttributes.setMetadata(getMetadata(request)); - - containerProperties.setLeaseStatus(BaseResponse.getLeaseStatus(request)); - containerProperties.setLeaseState(BaseResponse.getLeaseState(request)); - containerProperties.setLeaseDuration(BaseResponse.getLeaseDuration(request)); - - return containerAttributes; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyState.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyState.java deleted file mode 100644 index 10c25597d0821..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyState.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.URI; -import java.util.Date; - -/** - * Represents the attributes of a copy operation. - * - */ -public final class CopyState { - /** - * Holds the name of the container. - */ - private String copyId; - - /** - * Holds the time the copy operation completed, whether completion was due to a successful copy, an abort, or a - * failure. - */ - private Date completionTime; - - /** - * Holds the status of the copy operation. - */ - private CopyStatus status; - - /** - * Holds the source URI of a copy operation. - */ - private URI source; - - /** - * Holds the number of bytes copied in the operation so far. - */ - private Long bytesCopied; - - /** - * Holds the total number of bytes in the source of the copy. - */ - private Long totalBytes; - - /** - * Holds the description of the current status. - */ - private String statusDescription; - - /** - * Initializes a new instance of the CopyState class. - */ - public CopyState() { - } - - /** - * Gets the copy ID of the container. - * - * @return A string containing the copy ID of the container. - */ - public String getCopyId() { - return this.copyId; - } - - /** - * Gets the time that the copy operation completed. - * - * @return The time that the copy operation completed. - */ - public Date getCompletionTime() { - return this.completionTime; - } - - /** - * Gets the status of the copy operation. - * - * @return A CopyStatus object representing the status of the copy operation. - */ - public CopyStatus getStatus() { - return this.status; - } - - /** - * Gets the source URI of the copy operation. - * - * @return The source URI of the copy operation in a string. - */ - public URI getSource() { - return this.source; - } - - /** - * Gets the number of bytes copied in the operation so far. - * - * @return The number of bytes copied so far. - */ - public Long getBytesCopied() { - return this.bytesCopied; - } - - public Long getTotalBytes() { - return this.totalBytes; - } - - /** - * Gets the status description of the copy operation. - * - * @return A string containing the status description. - */ - public String getStatusDescription() { - return this.statusDescription; - } - - /** - * Sets the copy ID of the container. - * - * @param copyId - * The copy ID of the container to set. - * - */ - public void setCopyId(final String copyId) { - this.copyId = copyId; - } - - /** - * Sets the time that the copy operation completed. - * - * @param completionTime - * The completion time to set. - */ - public void setCompletionTime(final Date completionTime) { - this.completionTime = completionTime; - } - - /** - * Sets the status of the copy operation. - * - * @param status - * The copy operation status to set, as a CopyStatus object. - */ - public void setStatus(final CopyStatus status) { - this.status = status; - } - - /** - * Sets the source URI of the copy operation. - * - * @param source - * The source URI to set. - */ - public void setSource(final URI source) { - this.source = source; - } - - /** - * Sets the number of bytes copied so far. - * - * @param bytesCopied - * The number of bytes copied to set. - */ - public void setBytesCopied(final Long bytesCopied) { - this.bytesCopied = bytesCopied; - } - - /** - * Sets the total number of bytes in the source to copy. - * - * @param totalBytes - * The number of bytes to set. - */ - public void setTotalBytes(final Long totalBytes) { - this.totalBytes = totalBytes; - } - - /** - * Sets the current status of the copy operation. - * - * @param statusDescription - * The current status to set. - */ - public void setStatusDescription(final String statusDescription) { - this.statusDescription = statusDescription; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyStatus.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyStatus.java deleted file mode 100644 index 3358e040115de..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CopyStatus.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.Locale; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Represents the status of a copy blob operation. - */ -public enum CopyStatus { - /** - * The copy status is not specified. - */ - UNSPECIFIED, - - /** - * The copy status is invalid. - */ - INVALID, - - /** - * The copy operation is pending. - */ - PENDING, - - /** - * The copy operation succeeded. - */ - SUCCESS, - - /** - * The copy operation has been aborted. - */ - ABORTED, - - /** - * The copy operation encountered an error. - */ - FAILED; - - /** - * Parses a copy status from the given string. - * - * @param typeString - * A String that represents the string to parse. - * - * @return A CopyStatus value that represents the copy status. - */ - public static CopyStatus parse(final String typeString) { - if (Utility.isNullOrEmpty(typeString)) { - return UNSPECIFIED; - } - else if ("invalid".equals(typeString.toLowerCase(Locale.US))) { - return INVALID; - } - else if ("pending".equals(typeString.toLowerCase(Locale.US))) { - return PENDING; - } - else if ("success".equals(typeString.toLowerCase(Locale.US))) { - return SUCCESS; - } - else if ("aborted".equals(typeString.toLowerCase(Locale.US))) { - return ABORTED; - } - else if ("failed".equals(typeString.toLowerCase(Locale.US))) { - return FAILED; - } - else { - return UNSPECIFIED; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/DeleteSnapshotsOption.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/DeleteSnapshotsOption.java deleted file mode 100644 index ce7a5b5750c6f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/DeleteSnapshotsOption.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Specifies options when calling delete operations. - */ -public enum DeleteSnapshotsOption { - /** - * Specifies deleting only the blob's snapshots. - */ - DELETE_SNAPSHOTS_ONLY, - - /** - * Specifies deleting the blob and its snapshots. - */ - INCLUDE_SNAPSHOTS, - - /** - * Specifies deleting the blob but not its snapshots. - */ - NONE -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/GetBlockListResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/GetBlockListResponse.java deleted file mode 100644 index 4b2f8f2eeec91..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/GetBlockListResponse.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.InputStream; -import java.util.ArrayList; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse a get block list response stream. - */ -final class GetBlockListResponse { - /** - * Holds the ArrayList of CloudBlobs from the response. - */ - private final ArrayList blocks = new ArrayList(); - - /** - * Stores the value indicating if the response has been fully parsed. - */ - private boolean isParsed; - - /** - * Stores the InputStream to read from. - */ - private final InputStream streamRef; - - /** - * Constructs the response from the inputstream. - * - * @param stream - * the inputstream for the response the server returned. - */ - public GetBlockListResponse(final InputStream stream) { - this.streamRef = stream; - } - - /** - * Returns an ArrayList of BlockEntrys for the given block blob. - * - * @return an ArrayList of BlockEntrys for the given block blob. - * @throws XMLStreamException - * @throws StorageException - */ - public ArrayList getBlocks() throws XMLStreamException, StorageException { - if (!this.isParsed) { - this.parseResponse(); - } - - return this.blocks; - } - - /** - * Parses the XML stream. - * - * @throws XMLStreamException - * @throws StorageException - */ - public void parseResponse() throws XMLStreamException, StorageException { - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(this.streamRef); - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // 1. get BlockList Header - eventType = xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.BLOCK_LIST_ELEMENT); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - if (name.equals(BlobConstants.COMMITTED_BLOCKS_ELEMENT)) { - // Move to block element - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.START_ELEMENT - && BlobConstants.BLOCK_ELEMENT.equals(xmlr.getName().toString())) { - this.blocks.addAll(BlobDeserializationHelper.readBlobBlocks(xmlr, BlockSearchMode.COMMITTED)); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.COMMITTED_BLOCKS_ELEMENT); - } - } - else if (name.equals(BlobConstants.UNCOMMITTED_BLOCKS_ELEMENT)) { - // Move to block element - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.START_ELEMENT - && BlobConstants.BLOCK_ELEMENT.equals(xmlr.getName().toString())) { - this.blocks.addAll(BlobDeserializationHelper.readBlobBlocks(xmlr, BlockSearchMode.UNCOMMITTED)); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.UNCOMMITTED_BLOCKS_ELEMENT); - } - } - else if (name.equals(BlobConstants.BLOCK_LIST_ELEMENT) && eventType == XMLStreamConstants.END_ELEMENT) { - break; - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - } - - this.isParsed = true; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/GetPageRangesResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/GetPageRangesResponse.java deleted file mode 100644 index 63ce73d7c0ae6..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/GetPageRangesResponse.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.InputStream; -import java.util.ArrayList; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse a get page ranges response stream. - */ -final class GetPageRangesResponse { - /** - * Holds the ArrayList of Page Ranges from the response. - */ - private ArrayList pageRanges = new ArrayList(); - - /** - * Stores the value indicating if the response has been fully parsed. - */ - private boolean isParsed; - - /** - * Stores the InputStream to read from. - */ - private final InputStream streamRef; - - /** - * Constructs the response from the inputstream. - * - * @param stream - * the inputstream for the response the server returned. - */ - public GetPageRangesResponse(final InputStream stream) { - this.streamRef = stream; - } - - /** - * Returns an ArrayList of Page Ranges for the given page blob. - * - * @return an ArrayList of Page Ranges for the given page blob. - * @throws XMLStreamException - * @throws StorageException - */ - public ArrayList getPageRanges() throws XMLStreamException, StorageException { - if (!this.isParsed) { - this.parseResponse(); - } - - return this.pageRanges; - } - - /** - * Parses the XML stream. - * - * @throws XMLStreamException - * @throws StorageException - */ - public void parseResponse() throws XMLStreamException, StorageException { - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(this.streamRef); - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // 1. get BlockList Header - eventType = xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.PAGE_LIST_ELEMENT); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (name.equals(BlobConstants.PAGE_RANGE_ELEMENT)) { - this.pageRanges = BlobDeserializationHelper.readPageRanges(xmlr); - } - else if (name.equals(BlobConstants.PAGE_LIST_ELEMENT) && eventType == XMLStreamConstants.END_ELEMENT) { - break; - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - } - - this.isParsed = true; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListBlobItem.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListBlobItem.java deleted file mode 100644 index 790aa46034635..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListBlobItem.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.URI; -import java.net.URISyntaxException; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Represents an item that may be returned by a blob listing operation. - */ -public interface ListBlobItem { - - /** - * Returns the container for the blob item. - * - * @return A {@link CloudBlobContainer} object that represents the blob item's container. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - CloudBlobContainer getContainer() throws URISyntaxException, StorageException; - - /** - * Returns the parent for the blob item. - * - * @return A {@link CloudBlobDirectory} object that represents the blob item's parent. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - CloudBlobDirectory getParent() throws URISyntaxException, StorageException; - - /** - * Returns the URI for the blob item. - * - * @return A java.net.URI object that represents the blob item's URI. - */ - URI getUri(); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListBlobsResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListBlobsResponse.java deleted file mode 100644 index fad732e4e49b0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListBlobsResponse.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.InputStream; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse a list blobs response stream. - */ -final class ListBlobsResponse { - - /** - * Holds the ArrayList of CloudBlobs from the response. - */ - private ArrayList blobs = new ArrayList(); - - /** - * Stores the value indicating if the response has been fully parsed. - */ - private boolean isParsed; - - /** - * Stores the marker. - */ - private String marker; - - /** - * Stores the max results. - */ - private int maxResults; - - /** - * Stores the next marker. - */ - private String nextMarker; - - /** - * Stores the container prefix. - */ - private String prefix; - - /** - * Stores the InputStream to read from. - */ - private final InputStream streamRef; - - /** - * Stores the blob delimiter. - */ - private String delimiter; - - public ListBlobsResponse(final InputStream stream) { - this.streamRef = stream; - } - - public ArrayList getBlobs(final CloudBlobClient serviceClient, final CloudBlobContainer container) - throws XMLStreamException, StorageException { - if (!this.isParsed) { - this.parseResponse(serviceClient, container); - } - - return this.blobs; - } - - public String getDelimiter() { - return this.delimiter; - } - - public String getMarker() { - return this.marker; - } - - public int getMaxResults() { - return this.maxResults; - } - - public String getNextMarker() { - return this.nextMarker; - } - - public String getPrefix() { - return this.prefix; - } - - public void parseResponse(final CloudBlobClient serviceClient, final CloudBlobContainer container) - throws XMLStreamException, StorageException { - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(this.streamRef); - String tempParseString = null; - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // 1. get enumerationResults Header - eventType = xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, "EnumerationResults"); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.MAX_RESULTS_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, Constants.MAX_RESULTS_ELEMENT); - this.maxResults = Integer.parseInt(tempParseString); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.MARKER_ELEMENT)) { - this.marker = Utility.readElementFromXMLReader(xmlr, Constants.MARKER_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.NEXT_MARKER_ELEMENT)) { - this.nextMarker = Utility.readElementFromXMLReader(xmlr, Constants.NEXT_MARKER_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.PREFIX_ELEMENT)) { - this.prefix = Utility.readElementFromXMLReader(xmlr, Constants.PREFIX_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.DELIMITER_ELEMENT)) { - this.delimiter = Utility.readElementFromXMLReader(xmlr, Constants.DELIMITER_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(BlobConstants.BLOBS_ELEMENT)) { - try { - this.blobs = BlobDeserializationHelper.readBlobItems(xmlr, serviceClient, container); - } - catch (final URISyntaxException e) { - throw new XMLStreamException(e); - } - catch (final ParseException e) { - throw new XMLStreamException(e); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.BLOBS_ELEMENT); - } - else if (eventType == XMLStreamConstants.END_ELEMENT && "EnumerationResults".equals(name)) { - break; - } - } - } - - this.isParsed = true; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListContainersResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListContainersResponse.java deleted file mode 100644 index 2aa51ccfc7e25..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/ListContainersResponse.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.InputStream; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class for parsing a list containers response stream. - */ -final class ListContainersResponse { - - /** - * Holds the list of containers. - */ - private ArrayList containers = new ArrayList(); - - /** - * Stores the value indicating if the response has been fully parsed. - */ - private boolean isParsed; - - /** - * Stores the marker. - */ - private String marker; - - /** - * Stores the max results. - */ - private int maxResults; - - /** - * Stores the next marker. - */ - private String nextMarker; - - /** - * Stores the container prefix. - */ - private String prefix; - - /** - * Stores the InputStream to read from. - */ - private final InputStream streamRef; - - public ListContainersResponse(final InputStream stream) { - this.streamRef = stream; - } - - /** - * Returns an ArrayList of CloudBlobContainer - * - * @param serviceClient - * a reference to the client object associated with this object. - * @return an ArrayList of CloudBlobContainer - * @throws XMLStreamException - * @throws StorageException - */ - public ArrayList getContainers(final CloudBlobClient serviceClient) throws XMLStreamException, - StorageException { - if (!this.isParsed) { - this.parseResponse(serviceClient); - } - - return this.containers; - } - - public String getMarker() { - return this.marker; - } - - public int getMaxResults() { - return this.maxResults; - } - - public String getNextMarker() { - return this.nextMarker; - } - - public String getPrefix() { - return this.prefix; - } - - /** - * Parses the XML stream. - * - * @param serviceClient - * a reference to the client object associated with this object. - * @throws XMLStreamException - * @throws StorageException - */ - public void parseResponse(final CloudBlobClient serviceClient) throws XMLStreamException, StorageException { - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(this.streamRef); - String tempParseString = null; - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // 1. get enumerationResults Header - eventType = xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, "EnumerationResults"); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.MAX_RESULTS_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, Constants.MAX_RESULTS_ELEMENT); - this.maxResults = Integer.parseInt(tempParseString); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.MARKER_ELEMENT)) { - this.marker = Utility.readElementFromXMLReader(xmlr, Constants.MARKER_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.NEXT_MARKER_ELEMENT)) { - this.nextMarker = Utility.readElementFromXMLReader(xmlr, Constants.NEXT_MARKER_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.PREFIX_ELEMENT)) { - this.prefix = Utility.readElementFromXMLReader(xmlr, Constants.PREFIX_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(BlobConstants.CONTAINERS_ELEMENT)) { - try { - this.containers = BlobDeserializationHelper.readContainers(xmlr, serviceClient); - } - catch (final URISyntaxException e) { - throw new XMLStreamException(e); - } - catch (final ParseException e) { - throw new XMLStreamException(e); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.CONTAINERS_ELEMENT); - // eventType = xmlr.next(); - } - else if (eventType == XMLStreamConstants.END_ELEMENT && "EnumerationResults".equals(name)) { - break; - } - } - } - - this.isParsed = true; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageOperationType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageOperationType.java deleted file mode 100644 index e9d49b5739489..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageOperationType.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * RESERVED FOR INTERNAL USE. Describes actions that may be used for writing to a page blob or clearing a set of pages. - */ -enum PageOperationType { - /** - * Update the page with new data. - */ - UPDATE, - - /** - * Clear the page. - */ - CLEAR -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageProperties.java deleted file mode 100644 index 1e76174d74747..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageProperties.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * RESERVED FOR INTERNAL USE. Represents properties for writing to a page blob. - */ -final class PageProperties { - - /** - * Gets or sets the type of write operation. - */ - private PageOperationType pageOperation = PageOperationType.UPDATE; - - /** - * Gets or sets the range of bytes to write to. - */ - private PageRange range = new PageRange(-1, -1); - - /** - * Initializes a new instance of the PageProperties class. - */ - public PageProperties() { - // Empty Default Ctor - } - - /** - * @return the pageOperation - */ - public PageOperationType getPageOperation() { - return this.pageOperation; - } - - /** - * @return the range - */ - public PageRange getRange() { - return this.range; - } - - /** - * @param pageOperation - * the pageOperation to set - */ - public void setPageOperation(final PageOperationType pageOperation) { - this.pageOperation = pageOperation; - } - - /** - * @param range - * the range to set - */ - public void setRange(final PageRange range) { - this.range = range; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageRange.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageRange.java deleted file mode 100644 index 92b03228ebc0c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/PageRange.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -/** - * Represents a range of pages in a page blob. - */ -public final class PageRange { - /** - * Represents the ending offset of the page range. - */ - private long endOffset; - - /** - * Represents the starting offset of the page range. - */ - private long startOffset; - - /** - * Creates an instance of the PageRange class. - * - * @param start - * The starting offset. - * @param end - * The ending offset. - */ - public PageRange(final long start, final long end) { - this.setStartOffset(start); - this.setEndOffset(end); - } - - /** - * @return the endOffset - */ - public long getEndOffset() { - return this.endOffset; - } - - /** - * @return the startOffset - */ - public long getStartOffset() { - return this.startOffset; - } - - /** - * @param endOffset - * the endOffset to set - */ - public void setEndOffset(final long endOffset) { - this.endOffset = endOffset; - } - - /** - * @param startOffset - * the startOffset to set - */ - public void setStartOffset(final long startOffset) { - this.startOffset = startOffset; - } - - /** - * Returns the content of the page range as a string. - * - * @return A String that represents the contents of the page range. - */ - @Override - public String toString() { - return String.format("bytes=%d-%d", this.getStartOffset(), this.getEndOffset()); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/SharedAccessBlobPermissions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/SharedAccessBlobPermissions.java deleted file mode 100644 index 003153c6338ab..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/SharedAccessBlobPermissions.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.EnumSet; - -/** - * Specifies the set of possible permissions for a shared access policy. - */ -public enum SharedAccessBlobPermissions { - /** - * Specifies Read access granted. - */ - READ((byte) 0x1), - - /** - * Specifies Write access granted. - */ - WRITE((byte) 0x2), - - /** - * Specifies Delete access granted for blobs. - */ - DELETE((byte) 0x4), - - /** - * Specifies List access granted. - */ - LIST((byte) 0x8); - - /** - * Returns the enum set representing the shared access permissions for the specified byte value. - * - * @param value - * The byte value to convert to the corresponding enum set. - * @return A java.util.EnumSet object that contains the SharedAccessBlobPermissions values - * corresponding to the specified byte value. - */ - protected static EnumSet fromByte(final byte value) { - final EnumSet retSet = EnumSet.noneOf(SharedAccessBlobPermissions.class); - - if (value == READ.value) { - retSet.add(READ); - } - - if (value == WRITE.value) { - retSet.add(WRITE); - } - if (value == DELETE.value) { - retSet.add(DELETE); - } - if (value == LIST.value) { - retSet.add(LIST); - } - - return retSet; - } - - /** - * Returns the value of this enum. - */ - private byte value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - SharedAccessBlobPermissions(final byte val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/SharedAccessBlobPolicy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/SharedAccessBlobPolicy.java deleted file mode 100644 index c4ebe80b713c4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/SharedAccessBlobPolicy.java +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.util.Date; -import java.util.EnumSet; - -import com.microsoft.windowsazure.services.core.storage.Constants; - -/** - * Represents a shared access policy, which specifies the start time, expiry time, and permissions for a shared access - * signature. - */ -public final class SharedAccessBlobPolicy { - - /** - * Assigns shared access permissions using the specified permissions string. - * - * @param value - * A String that represents the shared access permissions. The string must contain one or - * more of the following values. Note they must be lowercase, and the order that they are specified must - * be in the order of "rwdl". - *

    - *
  • d: Delete access.
  • - *
  • l: List access.
  • - *
  • r: Read access.
  • - *
  • w: Write access.
  • - *
- * - * @return A java.util.EnumSet object that contains {@link SharedAccessBlobPermissions} values that - * represents the set of shared access permissions. - */ - public static EnumSet permissionsFromString(final String value) { - final char[] chars = value.toCharArray(); - final EnumSet retSet = EnumSet.noneOf(SharedAccessBlobPermissions.class); - - for (final char c : chars) { - switch (c) { - case 'r': - retSet.add(SharedAccessBlobPermissions.READ); - break; - case 'w': - retSet.add(SharedAccessBlobPermissions.WRITE); - break; - case 'd': - retSet.add(SharedAccessBlobPermissions.DELETE); - break; - case 'l': - retSet.add(SharedAccessBlobPermissions.LIST); - break; - default: - throw new IllegalArgumentException("value"); - } - } - - return retSet; - } - - /** - * Converts the permissions specified for the shared access policy to a string. - * - * @param permissions - * A {@link SharedAccessBlobPermissions} object that represents the shared access permissions. - * - * @return A String that represents the shared access permissions in the "rwdl" format, which is - * described at {@link SharedAccessBlobPolicy#permissionsFromString}. - */ - public static String permissionsToString(final EnumSet permissions) { - if (permissions == null) { - return Constants.EMPTY_STRING; - } - - // The service supports a fixed order => rwdl - final StringBuilder builder = new StringBuilder(); - - if (permissions.contains(SharedAccessBlobPermissions.READ)) { - builder.append("r"); - } - - if (permissions.contains(SharedAccessBlobPermissions.WRITE)) { - builder.append("w"); - } - - if (permissions.contains(SharedAccessBlobPermissions.DELETE)) { - builder.append("d"); - } - - if (permissions.contains(SharedAccessBlobPermissions.LIST)) { - builder.append("l"); - } - - return builder.toString(); - } - - /** - * The permissions for a shared access signature associated with this shared access policy. - */ - private EnumSet permissions; - - /** - * The expiry time for a shared access signature associated with this shared access policy. - */ - private Date sharedAccessExpiryTime; - - /** - * The start time for a shared access signature associated with this shared access policy. - */ - private Date sharedAccessStartTime; - - /** - * Creates an instance of the SharedAccessBlobPolicy class. - * */ - public SharedAccessBlobPolicy() { - // Empty Default Ctor - } - - /** - * Gets the permissions for a shared access signature associated with this shared access policy. - * - * @return A java.util.EnumSet object that contains {@link SharedAccessBlobPermissions} values that - * represents the set of shared access permissions. - */ - public EnumSet getPermissions() { - return this.permissions; - } - - /** - * Gets the expiry time for a shared access signature associated with this shared access policy. - * - * @return A Date object that contains the shared access signature expiry time. - */ - public Date getSharedAccessExpiryTime() { - return this.sharedAccessExpiryTime; - } - - /** - * Gets the start time for a shared access signature associated with this shared access policy. - * - * @return A Date object that contains the shared access signature start time. - */ - public Date getSharedAccessStartTime() { - return this.sharedAccessStartTime; - } - - /** - * Sets the permissions for a shared access signature associated with this shared access policy. - * - * @param permissions - * The permissions, represented by a java.util.EnumSet object that contains - * {@link SharedAccessBlobPermissions} values, to set for the shared access signature. - */ - public void setPermissions(final EnumSet permissions) { - this.permissions = permissions; - } - - /** - * Sets the expiry time for a shared access signature associated with this shared access policy. - * - * @param sharedAccessExpiryTime - * The expiry time to set for the shared access signature. - */ - public void setSharedAccessExpiryTime(final Date sharedAccessExpiryTime) { - this.sharedAccessExpiryTime = sharedAccessExpiryTime; - } - - /** - * Sets the start time for a shared access signature associated with this shared access policy. - * - * @param sharedAccessStartTime - * The start time to set for the shared access signature. - */ - public void setSharedAccessStartTime(final Date sharedAccessStartTime) { - this.sharedAccessStartTime = sharedAccessStartTime; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/package.html deleted file mode 100644 index cbf5ee75f3777..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the integrated blob service client classes and implementation. - - diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/core/storage/SharedAccessSignatureHelper.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/core/storage/SharedAccessSignatureHelper.java deleted file mode 100644 index f798b48382329..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/core/storage/SharedAccessSignatureHelper.java +++ /dev/null @@ -1,493 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.core.storage; - -import java.security.InvalidKeyException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map.Entry; - -import com.microsoft.windowsazure.services.blob.client.SharedAccessBlobPolicy; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ServiceClient; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.queue.client.SharedAccessQueuePolicy; -import com.microsoft.windowsazure.services.table.client.SharedAccessTablePolicy; - -/** - * RESERVED FOR INTERNAL USE. Contains helper methods for implementing shared access signatures. - */ -public class SharedAccessSignatureHelper { - /** - * Get the complete query builder for creating the Shared Access Signature query. - * - * @param policy - * The shared access policy to hash. - * @param groupPolicyIdentifier - * An optional identifier for the policy. - * @param resourceType - * Either "b" for blobs or "c" for containers. - * @param signature - * The signature to use. - * @return The finished query builder - * @throws IllegalArgumentException - * @throws StorageException - */ - public static UriQueryBuilder generateSharedAccessSignature(final SharedAccessBlobPolicy policy, - final String groupPolicyIdentifier, final String resourceType, final String signature) - throws StorageException { - Utility.assertNotNullOrEmpty("resourceType", resourceType); - Utility.assertNotNull("signature", signature); - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add(Constants.QueryConstants.SIGNED_VERSION, Constants.HeaderConstants.TARGET_STORAGE_VERSION); - - if (policy != null) { - String permissions = SharedAccessBlobPolicy.permissionsToString(policy.getPermissions()); - - if (Utility.isNullOrEmpty(permissions)) { - permissions = null; - } - - final String startString = Utility.getUTCTimeOrEmpty(policy.getSharedAccessStartTime()); - if (!Utility.isNullOrEmpty(startString)) { - builder.add(Constants.QueryConstants.SIGNED_START, startString); - } - - final String stopString = Utility.getUTCTimeOrEmpty(policy.getSharedAccessExpiryTime()); - if (!Utility.isNullOrEmpty(stopString)) { - builder.add(Constants.QueryConstants.SIGNED_EXPIRY, stopString); - } - - if (!Utility.isNullOrEmpty(permissions)) { - builder.add(Constants.QueryConstants.SIGNED_PERMISSIONS, permissions); - } - } - - builder.add(Constants.QueryConstants.SIGNED_RESOURCE, resourceType); - - if (!Utility.isNullOrEmpty(groupPolicyIdentifier)) { - builder.add(Constants.QueryConstants.SIGNED_IDENTIFIER, groupPolicyIdentifier); - } - - if (!Utility.isNullOrEmpty(signature)) { - builder.add(Constants.QueryConstants.SIGNATURE, signature); - } - - return builder; - } - - /** - * Get the complete query builder for creating the Shared Access Signature query. - * - * @param policy - * The shared access policy to hash. - * @param groupPolicyIdentifier - * An optional identifier for the policy. - * @param signature - * The signature to use. - * @return The finished query builder - * @throws IllegalArgumentException - * @throws StorageException - */ - public static UriQueryBuilder generateSharedAccessSignature(final SharedAccessQueuePolicy policy, - final String groupPolicyIdentifier, final String signature) throws StorageException { - Utility.assertNotNull("signature", signature); - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add(Constants.QueryConstants.SIGNED_VERSION, Constants.HeaderConstants.TARGET_STORAGE_VERSION); - - if (policy != null) { - String permissions = SharedAccessQueuePolicy.permissionsToString(policy.getPermissions()); - - if (Utility.isNullOrEmpty(permissions)) { - permissions = null; - } - - final String startString = Utility.getUTCTimeOrEmpty(policy.getSharedAccessStartTime()); - if (!Utility.isNullOrEmpty(startString)) { - builder.add(Constants.QueryConstants.SIGNED_START, startString); - } - - final String stopString = Utility.getUTCTimeOrEmpty(policy.getSharedAccessExpiryTime()); - if (!Utility.isNullOrEmpty(stopString)) { - builder.add(Constants.QueryConstants.SIGNED_EXPIRY, stopString); - } - - if (!Utility.isNullOrEmpty(permissions)) { - builder.add(Constants.QueryConstants.SIGNED_PERMISSIONS, permissions); - } - } - - if (!Utility.isNullOrEmpty(groupPolicyIdentifier)) { - builder.add(Constants.QueryConstants.SIGNED_IDENTIFIER, groupPolicyIdentifier); - } - - if (!Utility.isNullOrEmpty(signature)) { - builder.add(Constants.QueryConstants.SIGNATURE, signature); - } - - return builder; - } - - /** - * Get the complete query builder for creating the Shared Access Signature query. - * - * @param signature - * The signature to use. - * @return The finished query builder - * @throws IllegalArgumentException - * @throws StorageException - */ - public static UriQueryBuilder generateSharedAccessSignature(final String permissions, final Date startTime, - final Date expiryTime, final String startPatitionKey, final String startRowKey, - final String endPatitionKey, final String endRowKey, final String accessPolicyIdentifier, - final String resourceType, final String tableName, final String signature, final String accountKeyName) - throws StorageException { - Utility.assertNotNull("signature", signature); - - final UriQueryBuilder builder = new UriQueryBuilder(); - - builder.add(Constants.QueryConstants.SIGNED_VERSION, Constants.HeaderConstants.TARGET_STORAGE_VERSION); - - if (!Utility.isNullOrEmpty(permissions)) { - builder.add(Constants.QueryConstants.SIGNED_PERMISSIONS, permissions); - } - - final String startString = Utility.getUTCTimeOrEmpty(startTime); - if (!Utility.isNullOrEmpty(startString)) { - builder.add(Constants.QueryConstants.SIGNED_START, startString); - } - - final String stopString = Utility.getUTCTimeOrEmpty(expiryTime); - if (!Utility.isNullOrEmpty(stopString)) { - builder.add(Constants.QueryConstants.SIGNED_EXPIRY, stopString); - } - - if (!Utility.isNullOrEmpty(startPatitionKey)) { - builder.add(Constants.QueryConstants.START_PARTITION_KEY, startPatitionKey); - } - - if (!Utility.isNullOrEmpty(startRowKey)) { - builder.add(Constants.QueryConstants.START_ROW_KEY, startRowKey); - } - - if (!Utility.isNullOrEmpty(endPatitionKey)) { - builder.add(Constants.QueryConstants.END_PARTITION_KEY, endPatitionKey); - } - - if (!Utility.isNullOrEmpty(endRowKey)) { - builder.add(Constants.QueryConstants.END_ROW_KEY, endRowKey); - } - - if (!Utility.isNullOrEmpty(accessPolicyIdentifier)) { - builder.add(Constants.QueryConstants.SIGNED_IDENTIFIER, accessPolicyIdentifier); - } - - if (!Utility.isNullOrEmpty(resourceType)) { - builder.add(Constants.QueryConstants.SIGNED_RESOURCE, resourceType); - } - - if (!Utility.isNullOrEmpty(tableName)) { - builder.add(Constants.QueryConstants.SAS_TABLE_NAME, tableName); - } - - if (!Utility.isNullOrEmpty(signature)) { - builder.add(Constants.QueryConstants.SIGNATURE, signature); - } - - if (!Utility.isNullOrEmpty(accountKeyName)) { - builder.add(Constants.QueryConstants.SIGNED_KEY, accountKeyName); - } - - return builder; - } - - /** - * Get the complete query builder for creating the Shared Access Signature query. - */ - public static UriQueryBuilder generateSharedAccessSignature(final SharedAccessTablePolicy policy, - final String startPartitionKey, final String startRowKey, final String endPartitionKey, - final String endRowKey, final String accessPolicyIdentifier, final String tableName, - final String signature, final String accountKeyName) throws StorageException { - - String permissionString = null; - Date startTime = null; - Date expiryTime = null; - - if (policy != null) { - permissionString = SharedAccessTablePolicy.permissionsToString(policy.getPermissions()); - startTime = policy.getSharedAccessStartTime(); - expiryTime = policy.getSharedAccessExpiryTime(); - } - - return generateSharedAccessSignature(permissionString, startTime, expiryTime, startPartitionKey, startRowKey, - endPartitionKey, endRowKey, accessPolicyIdentifier, null, tableName, signature, accountKeyName); - } - - /** - * Get the signature hash embedded inside the Shared Access Signature for blob service. - * - * @param policy - * The shared access policy to hash. - * @param accessPolicyIdentifier - * An optional identifier for the policy. - * @param resourceName - * the resource name. - * @param client - * the ServiceClient associated with the object. - * @param opContext - * an object used to track the execution of the operation - * @return the signature hash embedded inside the Shared Access Signature. - * @throws InvalidKeyException - * @throws StorageException - */ - public static String generateSharedAccessSignatureHash(final SharedAccessBlobPolicy policy, - final String accessPolicyIdentifier, final String resourceName, final ServiceClient client, - final OperationContext opContext) throws InvalidKeyException, StorageException { - String permissionString = null; - Date startTime = null; - Date expiryTime = null; - - if (policy != null) { - permissionString = SharedAccessBlobPolicy.permissionsToString(policy.getPermissions()); - startTime = policy.getSharedAccessStartTime(); - expiryTime = policy.getSharedAccessExpiryTime(); - } - - return generateSharedAccessSignatureHash(permissionString, startTime, expiryTime, resourceName, - accessPolicyIdentifier, false, null, null, null, null, client, opContext); - - } - - /** - * Get the signature hash embedded inside the Shared Access Signature for queue service. - * - * @param policy - * The shared access policy to hash. - * @param accessPolicyIdentifier - * An optional identifier for the policy. - * @param resourceName - * the resource name. - * @param client - * the ServiceClient associated with the object. - * @param opContext - * an object used to track the execution of the operation - * @return the signature hash embedded inside the Shared Access Signature. - * @throws InvalidKeyException - * @throws StorageException - */ - - public static String generateSharedAccessSignatureHash(final SharedAccessQueuePolicy policy, - final String accessPolicyIdentifier, final String resourceName, final ServiceClient client, - final OperationContext opContext) throws InvalidKeyException, StorageException { - - String permissionString = null; - Date startTime = null; - Date expiryTime = null; - - if (policy != null) { - permissionString = SharedAccessQueuePolicy.permissionsToString(policy.getPermissions()); - startTime = policy.getSharedAccessStartTime(); - expiryTime = policy.getSharedAccessExpiryTime(); - } - - return generateSharedAccessSignatureHash(permissionString, startTime, expiryTime, resourceName, - accessPolicyIdentifier, false, null, null, null, null, client, opContext); - } - - /** - * Get the signature hash embedded inside the Shared Access Signature for all storage service. - * - * @return the signature hash embedded inside the Shared Access Signature. - * @throws InvalidKeyException - * @throws StorageException - */ - public static String generateSharedAccessSignatureHash(final String permissions, final Date startTime, - final Date expiryTime, final String resourceName, final String accessPolicyIdentifier, - final boolean useTableSas, final String startPatitionKey, final String startRowKey, - final String endPatitionKey, final String endRowKey, final ServiceClient client, - final OperationContext opContext) throws InvalidKeyException, StorageException { - Utility.assertNotNullOrEmpty("resourceName", resourceName); - Utility.assertNotNull("client", client); - - String stringToSign = String.format("%s\n%s\n%s\n%s\n%s\n%s", permissions == null ? Constants.EMPTY_STRING - : permissions, Utility.getUTCTimeOrEmpty(startTime), Utility.getUTCTimeOrEmpty(expiryTime), - resourceName, accessPolicyIdentifier == null ? Constants.EMPTY_STRING : accessPolicyIdentifier, - Constants.HeaderConstants.TARGET_STORAGE_VERSION); - - if (useTableSas) { - stringToSign = String.format("%s\n%s\n%s\n%s\n%s", stringToSign, - startPatitionKey == null ? Constants.EMPTY_STRING : startPatitionKey, - startRowKey == null ? Constants.EMPTY_STRING : startRowKey, - endPatitionKey == null ? Constants.EMPTY_STRING : endPatitionKey, - endRowKey == null ? Constants.EMPTY_STRING : endRowKey); - } - - stringToSign = Utility.safeDecode(stringToSign); - final String signature = client.getCredentials().computeHmac256(stringToSign, opContext); - - // add logging - return signature; - } - - /** - * Get the signature hash embedded inside the Shared Access Signature for blob service. - * - * @param policy - * The shared access policy to hash. - * @param accessPolicyIdentifier - * An optional identifier for the policy. - * @param resourceName - * the resource name. - * @param client - * the ServiceClient associated with the object. - * @param opContext - * an object used to track the execution of the operation - * @return the signature hash embedded inside the Shared Access Signature. - * @throws InvalidKeyException - * @throws StorageException - */ - public static String generateSharedAccessSignatureHash(final SharedAccessTablePolicy policy, - final String accessPolicyIdentifier, final String resourceName, final String startPartitionKey, - final String startRowKey, final String endPartitionKey, final String endRowKey, final ServiceClient client, - final OperationContext opContext) throws InvalidKeyException, StorageException { - String permissionString = null; - Date startTime = null; - Date expiryTime = null; - - if (policy != null) { - permissionString = SharedAccessTablePolicy.permissionsToString(policy.getPermissions()); - startTime = policy.getSharedAccessStartTime(); - expiryTime = policy.getSharedAccessExpiryTime(); - } - - return generateSharedAccessSignatureHash(permissionString, startTime, expiryTime, resourceName, - accessPolicyIdentifier, true, startPartitionKey, startRowKey, endPartitionKey, endRowKey, client, - opContext); - - } - - /** - * Parses the query parameters and populates a StorageCredentialsSharedAccessSignature object if one is present. - * - * @param queryParams - * the parameters to parse - * @return the StorageCredentialsSharedAccessSignature if one is present, otherwise null - * @throws IllegalArgumentException - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - public static StorageCredentialsSharedAccessSignature parseQuery(final HashMap queryParams) - throws StorageException { - String signature = null; - String signedStart = null; - String signedExpiry = null; - String signedResource = null; - String sigendPermissions = null; - String signedIdentifier = null; - String signedVersion = null; - - boolean sasParameterFound = false; - - StorageCredentialsSharedAccessSignature credentials = null; - - for (final Entry entry : queryParams.entrySet()) { - final String lowerKey = entry.getKey().toLowerCase(Utility.LOCALE_US); - - if (lowerKey.equals(Constants.QueryConstants.SIGNED_START)) { - signedStart = entry.getValue()[0]; - sasParameterFound = true; - } - else if (lowerKey.equals(Constants.QueryConstants.SIGNED_EXPIRY)) { - signedExpiry = entry.getValue()[0]; - sasParameterFound = true; - } - else if (lowerKey.equals(Constants.QueryConstants.SIGNED_PERMISSIONS)) { - sigendPermissions = entry.getValue()[0]; - sasParameterFound = true; - } - else if (lowerKey.equals(Constants.QueryConstants.SIGNED_RESOURCE)) { - signedResource = entry.getValue()[0]; - sasParameterFound = true; - } - else if (lowerKey.equals(Constants.QueryConstants.SIGNED_IDENTIFIER)) { - signedIdentifier = entry.getValue()[0]; - sasParameterFound = true; - } - else if (lowerKey.equals(Constants.QueryConstants.SIGNATURE)) { - signature = entry.getValue()[0]; - sasParameterFound = true; - } - else if (lowerKey.equals(Constants.QueryConstants.SIGNED_VERSION)) { - signedVersion = entry.getValue()[0]; - sasParameterFound = true; - } - } - - if (sasParameterFound) { - if (signature == null) { - final String errorMessage = "Missing mandatory parameters for valid Shared Access Signature"; - throw new IllegalArgumentException(errorMessage); - } - - final UriQueryBuilder builder = new UriQueryBuilder(); - - if (!Utility.isNullOrEmpty(signedStart)) { - builder.add(Constants.QueryConstants.SIGNED_START, signedStart); - } - - if (!Utility.isNullOrEmpty(signedExpiry)) { - builder.add(Constants.QueryConstants.SIGNED_EXPIRY, signedExpiry); - } - - if (!Utility.isNullOrEmpty(sigendPermissions)) { - builder.add(Constants.QueryConstants.SIGNED_PERMISSIONS, sigendPermissions); - } - - if (!Utility.isNullOrEmpty(signedResource)) { - builder.add(Constants.QueryConstants.SIGNED_RESOURCE, signedResource); - } - - if (!Utility.isNullOrEmpty(signedIdentifier)) { - builder.add(Constants.QueryConstants.SIGNED_IDENTIFIER, signedIdentifier); - } - - if (!Utility.isNullOrEmpty(signedVersion)) { - builder.add(Constants.QueryConstants.SIGNED_VERSION, signedVersion); - } - - if (!Utility.isNullOrEmpty(signature)) { - builder.add(Constants.QueryConstants.SIGNATURE, signature); - } - - final String token = builder.toString(); - credentials = new StorageCredentialsSharedAccessSignature(token); - } - - return credentials; - } - - /** - * Private Default Ctor. - */ - private SharedAccessSignatureHelper() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobExceptionProcessor.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobExceptionProcessor.java deleted file mode 100644 index 3b0689cff0083..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobExceptionProcessor.java +++ /dev/null @@ -1,929 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.implementation; - -import java.io.InputStream; -import java.util.HashMap; - -import javax.inject.Inject; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.blob.models.AcquireLeaseOptions; -import com.microsoft.windowsazure.services.blob.models.AcquireLeaseResult; -import com.microsoft.windowsazure.services.blob.models.BlobServiceOptions; -import com.microsoft.windowsazure.services.blob.models.BlockList; -import com.microsoft.windowsazure.services.blob.models.BreakLeaseResult; -import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.ContainerACL; -import com.microsoft.windowsazure.services.blob.models.CopyBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CopyBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobPagesOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobPagesResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotResult; -import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; -import com.microsoft.windowsazure.services.blob.models.DeleteBlobOptions; -import com.microsoft.windowsazure.services.blob.models.DeleteContainerOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobMetadataOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobResult; -import com.microsoft.windowsazure.services.blob.models.GetContainerACLResult; -import com.microsoft.windowsazure.services.blob.models.GetContainerPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobRegionsOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobRegionsResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobsOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobsResult; -import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; -import com.microsoft.windowsazure.services.blob.models.ListContainersResult; -import com.microsoft.windowsazure.services.blob.models.PageRange; -import com.microsoft.windowsazure.services.blob.models.ServiceProperties; -import com.microsoft.windowsazure.services.blob.models.SetBlobMetadataOptions; -import com.microsoft.windowsazure.services.blob.models.SetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.SetContainerMetadataOptions; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.UniformInterfaceException; - -public class BlobExceptionProcessor implements BlobContract { - private static Log log = LogFactory.getLog(BlobExceptionProcessor.class); - private final BlobContract service; - - @Inject - public BlobExceptionProcessor(BlobRestProxy service) { - this.service = service; - } - - public BlobExceptionProcessor(BlobContract service) { - this.service = service; - } - - @Override - public BlobContract withFilter(ServiceFilter filter) { - return new BlobExceptionProcessor(service.withFilter(filter)); - } - - private ServiceException processCatch(ServiceException e) { - log.warn(e.getMessage(), e.getCause()); - return ServiceExceptionFactory.process("blob", e); - } - - @Override - public GetServicePropertiesResult getServiceProperties() throws ServiceException { - try { - return service.getServiceProperties(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetServicePropertiesResult getServiceProperties(BlobServiceOptions options) throws ServiceException { - try { - return service.getServiceProperties(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties, BlobServiceOptions options) - throws ServiceException { - try { - service.setServiceProperties(serviceProperties, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException { - try { - service.setServiceProperties(serviceProperties); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListContainersResult listContainers() throws ServiceException { - try { - return service.listContainers(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListContainersResult listContainers(ListContainersOptions options) throws ServiceException { - try { - return service.listContainers(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void createContainer(String container) throws ServiceException { - try { - service.createContainer(container); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void createContainer(String container, CreateContainerOptions options) throws ServiceException { - try { - service.createContainer(container, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteContainer(String container) throws ServiceException { - try { - service.deleteContainer(container); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteContainer(String container, DeleteContainerOptions options) throws ServiceException { - try { - service.deleteContainer(container, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetContainerPropertiesResult getContainerProperties(String container) throws ServiceException { - try { - return service.getContainerProperties(container); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetContainerPropertiesResult getContainerProperties(String container, BlobServiceOptions options) - throws ServiceException { - try { - return service.getContainerProperties(container, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetContainerPropertiesResult getContainerMetadata(String container) throws ServiceException { - try { - return service.getContainerMetadata(container); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetContainerPropertiesResult getContainerMetadata(String container, BlobServiceOptions options) - throws ServiceException { - try { - return service.getContainerMetadata(container, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetContainerACLResult getContainerACL(String container) throws ServiceException { - try { - return service.getContainerACL(container); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetContainerACLResult getContainerACL(String container, BlobServiceOptions options) throws ServiceException { - try { - return service.getContainerACL(container, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setContainerACL(String container, ContainerACL acl) throws ServiceException { - try { - service.setContainerACL(container, acl); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setContainerACL(String container, ContainerACL acl, BlobServiceOptions options) throws ServiceException { - try { - service.setContainerACL(container, acl, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setContainerMetadata(String container, HashMap metadata) throws ServiceException { - try { - service.setContainerMetadata(container, metadata); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setContainerMetadata(String container, HashMap metadata, - SetContainerMetadataOptions options) throws ServiceException { - try { - service.setContainerMetadata(container, metadata, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListBlobsResult listBlobs(String container) throws ServiceException { - try { - return service.listBlobs(container); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListBlobsResult listBlobs(String container, ListBlobsOptions options) throws ServiceException { - try { - return service.listBlobs(container, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobResult createPageBlob(String container, String blob, long length) throws ServiceException { - try { - return service.createPageBlob(container, blob, length); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobResult createPageBlob(String container, String blob, long length, CreateBlobOptions options) - throws ServiceException { - try { - return service.createPageBlob(container, blob, length, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobResult createBlockBlob(String container, String blob, InputStream contentStream) - throws ServiceException { - try { - return service.createBlockBlob(container, blob, contentStream); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobResult createBlockBlob(String container, String blob, InputStream contentStream, - CreateBlobOptions options) throws ServiceException { - try { - return service.createBlockBlob(container, blob, contentStream, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobPagesResult clearBlobPages(String container, String blob, PageRange range) throws ServiceException { - try { - return service.clearBlobPages(container, blob, range); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobPagesResult clearBlobPages(String container, String blob, PageRange range, - CreateBlobPagesOptions options) throws ServiceException { - try { - return service.clearBlobPages(container, blob, range, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobPagesResult createBlobPages(String container, String blob, PageRange range, long length, - InputStream contentStream) throws ServiceException { - try { - return service.createBlobPages(container, blob, range, length, contentStream); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobPagesResult createBlobPages(String container, String blob, PageRange range, long length, - InputStream contentStream, CreateBlobPagesOptions options) throws ServiceException { - try { - return service.createBlobPages(container, blob, range, length, contentStream, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void createBlobBlock(String container, String blob, String blockId, InputStream contentStream) - throws ServiceException { - try { - service.createBlobBlock(container, blob, blockId, contentStream); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void createBlobBlock(String container, String blob, String blockId, InputStream contentStream, - CreateBlobBlockOptions options) throws ServiceException { - try { - service.createBlobBlock(container, blob, blockId, contentStream, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void commitBlobBlocks(String container, String blob, BlockList blockList) throws ServiceException { - try { - service.commitBlobBlocks(container, blob, blockList); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void commitBlobBlocks(String container, String blob, BlockList blockList, CommitBlobBlocksOptions options) - throws ServiceException { - try { - service.commitBlobBlocks(container, blob, blockList, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListBlobBlocksResult listBlobBlocks(String container, String blob) throws ServiceException { - try { - return service.listBlobBlocks(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListBlobBlocksResult listBlobBlocks(String container, String blob, ListBlobBlocksOptions options) - throws ServiceException { - try { - return service.listBlobBlocks(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetBlobPropertiesResult getBlobProperties(String container, String blob) throws ServiceException { - try { - return service.getBlobProperties(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetBlobPropertiesResult getBlobProperties(String container, String blob, GetBlobPropertiesOptions options) - throws ServiceException { - try { - return service.getBlobProperties(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetBlobMetadataResult getBlobMetadata(String container, String blob) throws ServiceException { - try { - return service.getBlobMetadata(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetBlobMetadataResult getBlobMetadata(String container, String blob, GetBlobMetadataOptions options) - throws ServiceException { - try { - return service.getBlobMetadata(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListBlobRegionsResult listBlobRegions(String container, String blob) throws ServiceException { - try { - return service.listBlobRegions(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListBlobRegionsResult listBlobRegions(String container, String blob, ListBlobRegionsOptions options) - throws ServiceException { - try { - return service.listBlobRegions(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public SetBlobPropertiesResult setBlobProperties(String container, String blob, SetBlobPropertiesOptions options) - throws ServiceException { - try { - return service.setBlobProperties(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public SetBlobMetadataResult setBlobMetadata(String container, String blob, HashMap metadata) - throws ServiceException { - try { - return service.setBlobMetadata(container, blob, metadata); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public SetBlobMetadataResult setBlobMetadata(String container, String blob, HashMap metadata, - SetBlobMetadataOptions options) throws ServiceException { - try { - return service.setBlobMetadata(container, blob, metadata, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetBlobResult getBlob(String container, String blob) throws ServiceException { - try { - return service.getBlob(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetBlobResult getBlob(String container, String blob, GetBlobOptions options) throws ServiceException { - try { - return service.getBlob(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteBlob(String container, String blob) throws ServiceException { - try { - service.deleteBlob(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteBlob(String container, String blob, DeleteBlobOptions options) throws ServiceException { - try { - service.deleteBlob(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobSnapshotResult createBlobSnapshot(String container, String blob) throws ServiceException { - try { - return service.createBlobSnapshot(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateBlobSnapshotResult createBlobSnapshot(String container, String blob, CreateBlobSnapshotOptions options) - throws ServiceException { - try { - return service.createBlobSnapshot(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CopyBlobResult copyBlob(String destinationContainer, String destinationBlob, String sourceContainer, - String sourceBlob) throws ServiceException { - try { - return service.copyBlob(destinationContainer, destinationBlob, sourceContainer, sourceBlob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CopyBlobResult copyBlob(String destinationContainer, String destinationBlob, String sourceContainer, - String sourceBlob, CopyBlobOptions options) throws ServiceException { - try { - return service.copyBlob(destinationContainer, destinationBlob, sourceContainer, sourceBlob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public AcquireLeaseResult acquireLease(String container, String blob) throws ServiceException { - try { - return service.acquireLease(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public AcquireLeaseResult acquireLease(String container, String blob, AcquireLeaseOptions options) - throws ServiceException { - try { - return service.acquireLease(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public AcquireLeaseResult renewLease(String container, String blob, String leaseId) throws ServiceException { - try { - return service.renewLease(container, blob, leaseId); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public AcquireLeaseResult renewLease(String container, String blob, String leaseId, BlobServiceOptions options) - throws ServiceException { - try { - return service.renewLease(container, blob, leaseId, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void releaseLease(String container, String blob, String leaseId) throws ServiceException { - try { - service.releaseLease(container, blob, leaseId); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void releaseLease(String container, String blob, String leaseId, BlobServiceOptions options) - throws ServiceException { - try { - service.releaseLease(container, blob, leaseId, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - @Deprecated - public void breakLease(String container, String blob, String leaseId) throws ServiceException { - breakLease(container, blob); - } - - @Override - @Deprecated - public void breakLease(String container, String blob, String leaseId, BlobServiceOptions options) throws ServiceException { - breakLease(container, blob, options); - } - - @Override - public BreakLeaseResult breakLease(String container, String blob) throws ServiceException { - try { - return service.breakLease(container, blob); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public BreakLeaseResult breakLease(String container, String blob, BlobServiceOptions options) - throws ServiceException { - try { - return service.breakLease(container, blob, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobOperationRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobOperationRestProxy.java deleted file mode 100644 index 4a9daa0e4b2b1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobOperationRestProxy.java +++ /dev/null @@ -1,1044 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.blob.implementation; - -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.blob.models.AccessCondition; -import com.microsoft.windowsazure.services.blob.models.AcquireLeaseOptions; -import com.microsoft.windowsazure.services.blob.models.AcquireLeaseResult; -import com.microsoft.windowsazure.services.blob.models.BlobProperties; -import com.microsoft.windowsazure.services.blob.models.BlobServiceOptions; -import com.microsoft.windowsazure.services.blob.models.BlockList; -import com.microsoft.windowsazure.services.blob.models.BreakLeaseResult; -import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.ContainerACL; -import com.microsoft.windowsazure.services.blob.models.ContainerACL.PublicAccessType; -import com.microsoft.windowsazure.services.blob.models.CopyBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CopyBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobPagesOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobPagesResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotResult; -import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; -import com.microsoft.windowsazure.services.blob.models.DeleteBlobOptions; -import com.microsoft.windowsazure.services.blob.models.DeleteContainerOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobMetadataOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobResult; -import com.microsoft.windowsazure.services.blob.models.GetContainerACLResult; -import com.microsoft.windowsazure.services.blob.models.GetContainerPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobRegionsOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobRegionsResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobsOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobsResult; -import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; -import com.microsoft.windowsazure.services.blob.models.ListContainersResult; -import com.microsoft.windowsazure.services.blob.models.PageRange; -import com.microsoft.windowsazure.services.blob.models.ServiceProperties; -import com.microsoft.windowsazure.services.blob.models.SetBlobMetadataOptions; -import com.microsoft.windowsazure.services.blob.models.SetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.SetContainerMetadataOptions; -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.CommaStringBuilder; -import com.microsoft.windowsazure.services.core.utils.pipeline.ClientFilterAdapter; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; -import com.sun.jersey.core.util.Base64; - -public abstract class BlobOperationRestProxy implements BlobContract { - - private static final String API_VERSION = "2011-08-18"; - private final Client channel; - private final String accountName; - private final String url; - private final RFC1123DateConverter dateMapper; - private final ServiceFilter[] filters; - - protected BlobOperationRestProxy(Client channel, String accountName, String url) { - this(channel, new ServiceFilter[0], accountName, url, new RFC1123DateConverter()); - } - - protected BlobOperationRestProxy(Client channel, ServiceFilter[] filters, String accountName, String url, - RFC1123DateConverter dateMapper) { - this.channel = channel; - this.accountName = accountName; - this.url = url; - this.filters = filters; - this.dateMapper = dateMapper; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.FilterableService#withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) - */ - @Override - public abstract BlobContract withFilter(ServiceFilter filter); - - protected Client getChannel() { - return channel; - } - - protected String getAccountName() { - return accountName; - } - - protected String getUrl() { - return url; - } - - protected RFC1123DateConverter getDateMapper() { - return dateMapper; - } - - protected ServiceFilter[] getFilters() { - return filters; - } - - private void ThrowIfError(ClientResponse r) { - PipelineHelpers.ThrowIfError(r); - } - - private void ThrowIfNotSuccess(ClientResponse clientResponse) { - PipelineHelpers.ThrowIfNotSuccess(clientResponse); - } - - private WebResource addOptionalQueryParam(WebResource webResource, String key, Object value) { - return PipelineHelpers.addOptionalQueryParam(webResource, key, value); - } - - private WebResource addOptionalQueryParam(WebResource webResource, String key, int value, int defaultValue) { - return PipelineHelpers.addOptionalQueryParam(webResource, key, value, defaultValue); - } - - private Builder addOptionalHeader(Builder builder, String name, Object value) { - return PipelineHelpers.addOptionalHeader(builder, name, value); - } - - private Builder addOptionalMetadataHeader(Builder builder, Map metadata) { - return PipelineHelpers.addOptionalMetadataHeader(builder, metadata); - } - - private Builder addOptionalRangeHeader(Builder builder, Long rangeStart, Long rangeEnd) { - return PipelineHelpers.addOptionalRangeHeader(builder, rangeStart, rangeEnd); - } - - private Builder addOptionalAccessConditionHeader(Builder builder, AccessCondition accessCondition) { - return PipelineHelpers.addOptionalAccessConditionHeader(builder, accessCondition); - } - - private Builder addOptionalSourceAccessConditionHeader(Builder builder, AccessCondition accessCondition) { - return PipelineHelpers.addOptionalSourceAccessConditionHeader(builder, accessCondition); - } - - private HashMap getMetadataFromHeaders(ClientResponse response) { - return PipelineHelpers.getMetadataFromHeaders(response); - } - - private WebResource addOptionalBlobListingIncludeQueryParam(ListBlobsOptions options, WebResource webResource) { - CommaStringBuilder sb = new CommaStringBuilder(); - sb.addValue(options.isIncludeSnapshots(), "snapshots"); - sb.addValue(options.isIncludeUncommittedBlobs(), "uncommittedblobs"); - sb.addValue(options.isIncludeMetadata(), "metadata"); - webResource = addOptionalQueryParam(webResource, "include", sb.toString()); - return webResource; - } - - private WebResource addOptionalContainerIncludeQueryParam(ListContainersOptions options, WebResource webResource) { - CommaStringBuilder sb = new CommaStringBuilder(); - sb.addValue(options.isIncludeMetadata(), "metadata"); - webResource = addOptionalQueryParam(webResource, "include", sb.toString()); - return webResource; - } - - private Builder addPutBlobHeaders(CreateBlobOptions options, Builder builder) { - builder = addOptionalHeader(builder, "Content-Type", options.getContentType()); - if (options.getContentType() == null) { - // Note: Add content type here to enable proper HMAC signing - builder = builder.type("application/octet-stream"); - } - builder = addOptionalHeader(builder, "Content-Encoding", options.getContentEncoding()); - builder = addOptionalHeader(builder, "Content-Language", options.getContentLanguage()); - builder = addOptionalHeader(builder, "Content-MD5", options.getContentMD5()); - builder = addOptionalHeader(builder, "Cache-Control", options.getCacheControl()); - builder = addOptionalHeader(builder, "x-ms-blob-content-type", options.getBlobContentType()); - builder = addOptionalHeader(builder, "x-ms-blob-content-encoding", options.getBlobContentEncoding()); - builder = addOptionalHeader(builder, "x-ms-blob-content-language", options.getBlobContentLanguage()); - builder = addOptionalHeader(builder, "x-ms-blob-content-md5", options.getBlobContentMD5()); - builder = addOptionalHeader(builder, "x-ms-blob-cache-control", options.getBlobCacheControl()); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalMetadataHeader(builder, options.getMetadata()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - return builder; - } - - private GetBlobPropertiesResult getBlobPropertiesResultFromResponse(ClientResponse response) { - // Properties - BlobProperties properties = new BlobProperties(); - properties.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - properties.setBlobType(response.getHeaders().getFirst("x-ms-blob-type")); - properties.setLeaseStatus(response.getHeaders().getFirst("x-ms-lease-status")); - - properties.setContentLength(Long.parseLong(response.getHeaders().getFirst("Content-Length"))); - properties.setContentType(response.getHeaders().getFirst("Content-Type")); - properties.setContentMD5(response.getHeaders().getFirst("Content-MD5")); - properties.setContentEncoding(response.getHeaders().getFirst("Content-Encoding")); - properties.setContentLanguage(response.getHeaders().getFirst("Content-Language")); - properties.setCacheControl(response.getHeaders().getFirst("Cache-Control")); - - properties.setEtag(response.getHeaders().getFirst("Etag")); - if (response.getHeaders().containsKey("x-ms-blob-sequence-number")) { - properties.setSequenceNumber(Long.parseLong(response.getHeaders().getFirst("x-ms-blob-sequence-number"))); - } - - // Metadata - HashMap metadata = getMetadataFromHeaders(response); - - // Result - GetBlobPropertiesResult result = new GetBlobPropertiesResult(); - result.setMetadata(metadata); - result.setProperties(properties); - return result; - } - - private WebResource getResource(BlobServiceOptions options) { - WebResource webResource = channel.resource(url).path("/"); - webResource = addOptionalQueryParam(webResource, "timeout", options.getTimeout()); - for (ServiceFilter filter : filters) { - webResource.addFilter(new ClientFilterAdapter(filter)); - } - - return webResource; - } - - private String getCopyBlobSourceName(String sourceContainer, String sourceBlob, CopyBlobOptions options) { - // Specifies the name of the source blob, in one of the following - // formats: - // Blob in named container: /accountName/containerName/blobName - // - // Snapshot in named container: - // /accountName/containerName/blobName?snapshot= - // - // Blob in root container: /accountName/blobName - // - // Snapshot in root container: /accountName/blobName?snapshot= - String sourceName = "/" + this.accountName; - if (sourceContainer != null) { - sourceName += "/" + sourceContainer; - } - sourceName += "/" + sourceBlob; - if (options.getSourceSnapshot() != null) { - sourceName += "?snapshot=" + options.getSourceSnapshot(); - } - return sourceName; - } - - @Override - public GetServicePropertiesResult getServiceProperties() throws ServiceException { - return getServiceProperties(new BlobServiceOptions()); - } - - @Override - public GetServicePropertiesResult getServiceProperties(BlobServiceOptions options) throws ServiceException { - WebResource webResource = getResource(options).path("/").queryParam("resType", "service") - .queryParam("comp", "properties"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - - GetServicePropertiesResult result = new GetServicePropertiesResult(); - result.setValue(builder.get(ServiceProperties.class)); - return result; - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException { - setServiceProperties(serviceProperties, new BlobServiceOptions()); - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties, BlobServiceOptions options) - throws ServiceException { - WebResource webResource = getResource(options).path("/").queryParam("resType", "service") - .queryParam("comp", "properties"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - - builder.put(serviceProperties); - } - - @Override - public void createContainer(String container) throws ServiceException { - createContainer(container, new CreateContainerOptions()); - } - - @Override - public void createContainer(String container, CreateContainerOptions options) throws ServiceException { - if (container == null || container.isEmpty()) { - throw new IllegalArgumentException("The container cannot be null or empty."); - } - WebResource webResource = getResource(options).path(container).queryParam("resType", "container"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalMetadataHeader(builder, options.getMetadata()); - builder = addOptionalHeader(builder, "x-ms-blob-public-access", options.getPublicAccess()); - - builder.put(); - } - - @Override - public void deleteContainer(String container) throws ServiceException { - deleteContainer(container, new DeleteContainerOptions()); - } - - @Override - public void deleteContainer(String container, DeleteContainerOptions options) throws ServiceException { - if ((container == null) || (container.isEmpty())) { - throw new IllegalArgumentException("The root container has already been created."); - } - WebResource webResource = getResource(options).path(container).queryParam("resType", "container"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - builder.delete(); - } - - @Override - public GetContainerPropertiesResult getContainerProperties(String container) throws ServiceException { - return getContainerProperties(container, new BlobServiceOptions()); - } - - @Override - public GetContainerPropertiesResult getContainerProperties(String container, BlobServiceOptions options) - throws ServiceException { - return getContainerPropertiesImpl(container, options, null); - } - - @Override - public GetContainerPropertiesResult getContainerMetadata(String container) throws ServiceException { - return getContainerMetadata(container, new BlobServiceOptions()); - } - - @Override - public GetContainerPropertiesResult getContainerMetadata(String container, BlobServiceOptions options) - throws ServiceException { - return getContainerPropertiesImpl(container, options, "metadata"); - } - - private GetContainerPropertiesResult getContainerPropertiesImpl(String container, BlobServiceOptions options, - String operation) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).queryParam("resType", "container"); - webResource = addOptionalQueryParam(webResource, "comp", operation); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - GetContainerPropertiesResult properties = new GetContainerPropertiesResult(); - properties.setEtag(response.getHeaders().getFirst("ETag")); - properties.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - properties.setMetadata(getMetadataFromHeaders(response)); - - return properties; - } - - @Override - public GetContainerACLResult getContainerACL(String container) throws ServiceException { - return getContainerACL(container, new BlobServiceOptions()); - } - - @Override - public GetContainerACLResult getContainerACL(String container, BlobServiceOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).queryParam("resType", "container") - .queryParam("comp", "acl"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - ContainerACL.SignedIdentifiers si = response.getEntity(ContainerACL.SignedIdentifiers.class); - ContainerACL acl = new ContainerACL(); - acl.setSignedIdentifiers(si.getSignedIdentifiers()); - if ("container".equals(response.getHeaders().getFirst("x-ms-blob-public-access"))) { - acl.setPublicAccess(PublicAccessType.CONTAINER_AND_BLOBS); - } - else if ("blob".equals(response.getHeaders().getFirst("x-ms-blob-public-access"))) { - acl.setPublicAccess(PublicAccessType.BLOBS_ONLY); - } - else { - acl.setPublicAccess(PublicAccessType.NONE); - } - acl.setEtag(response.getHeaders().getFirst("ETag")); - acl.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - - GetContainerACLResult result = new GetContainerACLResult(); - result.setValue(acl); - return result; - } - - @Override - public void setContainerACL(String container, ContainerACL acl) throws ServiceException { - setContainerACL(container, acl, new BlobServiceOptions()); - } - - @Override - public void setContainerACL(String container, ContainerACL acl, BlobServiceOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).queryParam("resType", "container") - .queryParam("comp", "acl"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - if (acl.getPublicAccess() == PublicAccessType.BLOBS_ONLY) { - builder = addOptionalHeader(builder, "x-ms-blob-public-access", "blob"); - } - else if (acl.getPublicAccess() == PublicAccessType.CONTAINER_AND_BLOBS) { - builder = addOptionalHeader(builder, "x-ms-blob-public-access", "container"); - } - - ContainerACL.SignedIdentifiers si = new ContainerACL.SignedIdentifiers(); - si.setSignedIdentifiers(acl.getSignedIdentifiers()); - - builder.put(si); - } - - @Override - public void setContainerMetadata(String container, HashMap metadata) throws ServiceException { - setContainerMetadata(container, metadata, new SetContainerMetadataOptions()); - } - - @Override - public void setContainerMetadata(String container, HashMap metadata, - SetContainerMetadataOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).queryParam("resType", "container") - .queryParam("comp", "metadata"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalMetadataHeader(builder, metadata); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - builder.put(""); - } - - @Override - public ListContainersResult listContainers() throws ServiceException { - return listContainers(new ListContainersOptions()); - } - - @Override - public ListContainersResult listContainers(ListContainersOptions options) throws ServiceException { - WebResource webResource = getResource(options).path("/").queryParam("comp", "list"); - webResource = addOptionalQueryParam(webResource, "prefix", options.getPrefix()); - webResource = addOptionalQueryParam(webResource, "marker", options.getMarker()); - webResource = addOptionalQueryParam(webResource, "maxresults", options.getMaxResults(), 0); - webResource = addOptionalContainerIncludeQueryParam(options, webResource); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - return builder.get(ListContainersResult.class); - } - - @Override - public ListBlobsResult listBlobs(String container) throws ServiceException { - return listBlobs(container, new ListBlobsOptions()); - } - - @Override - public ListBlobsResult listBlobs(String container, ListBlobsOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).queryParam("comp", "list") - .queryParam("resType", "container"); - webResource = addOptionalQueryParam(webResource, "prefix", options.getPrefix()); - webResource = addOptionalQueryParam(webResource, "marker", options.getMarker()); - webResource = addOptionalQueryParam(webResource, "maxresults", options.getMaxResults(), 0); - webResource = addOptionalQueryParam(webResource, "delimiter", options.getDelimiter()); - webResource = addOptionalBlobListingIncludeQueryParam(options, webResource); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - return builder.get(ListBlobsResult.class); - } - - @Override - public CreateBlobResult createPageBlob(String container, String blob, long length) throws ServiceException { - return createPageBlob(container, blob, length, new CreateBlobOptions()); - } - - @Override - public CreateBlobResult createPageBlob(String container, String blob, long length, CreateBlobOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-blob-type", "PageBlob"); - builder = addOptionalHeader(builder, "Content-Length", 0); - builder = addOptionalHeader(builder, "x-ms-blob-content-length", length); - builder = addOptionalHeader(builder, "x-ms-blob-sequence-number", options.getSequenceNumber()); - builder = addPutBlobHeaders(options, builder); - - ClientResponse clientResponse = builder.put(ClientResponse.class, ""); - ThrowIfError(clientResponse); - - CreateBlobResult createBlobResult = new CreateBlobResult(); - createBlobResult.setEtag(clientResponse.getHeaders().getFirst("ETag")); - createBlobResult.setLastModified(dateMapper.parse(clientResponse.getHeaders().getFirst("Last-Modified"))); - - return createBlobResult; - } - - @Override - public CreateBlobResult createBlockBlob(String container, String blob, InputStream contentStream) - throws ServiceException { - return createBlockBlob(container, blob, contentStream, new CreateBlobOptions()); - } - - @Override - public CreateBlobResult createBlockBlob(String container, String blob, InputStream contentStream, - CreateBlobOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - builder = builder.header("x-ms-blob-type", "BlockBlob"); - builder = addPutBlobHeaders(options, builder); - - Object contentObject = (contentStream == null ? new byte[0] : contentStream); - ClientResponse clientResponse = builder.put(ClientResponse.class, contentObject); - ThrowIfError(clientResponse); - - CreateBlobResult createBlobResult = new CreateBlobResult(); - createBlobResult.setEtag(clientResponse.getHeaders().getFirst("ETag")); - createBlobResult.setLastModified(dateMapper.parse(clientResponse.getHeaders().getFirst("Last-Modified"))); - - return createBlobResult; - } - - @Override - public GetBlobPropertiesResult getBlobProperties(String container, String blob) throws ServiceException { - return getBlobProperties(container, blob, new GetBlobPropertiesOptions()); - } - - @Override - public GetBlobPropertiesResult getBlobProperties(String container, String blob, GetBlobPropertiesOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob); - webResource = addOptionalQueryParam(webResource, "snapshot", options.getSnapshot()); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - ClientResponse response = builder.method("HEAD", ClientResponse.class); - ThrowIfNotSuccess(response); - - return getBlobPropertiesResultFromResponse(response); - } - - @Override - public GetBlobMetadataResult getBlobMetadata(String container, String blob) throws ServiceException { - return getBlobMetadata(container, blob, new GetBlobMetadataOptions()); - } - - @Override - public GetBlobMetadataResult getBlobMetadata(String container, String blob, GetBlobMetadataOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "metadata"); - webResource = addOptionalQueryParam(webResource, "snapshot", options.getSnapshot()); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - GetBlobMetadataResult properties = new GetBlobMetadataResult(); - properties.setEtag(response.getHeaders().getFirst("ETag")); - properties.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - properties.setMetadata(getMetadataFromHeaders(response)); - - return properties; - } - - @Override - public SetBlobPropertiesResult setBlobProperties(String container, String blob, SetBlobPropertiesOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "properties"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-blob-cache-control", options.getCacheControl()); - builder = addOptionalHeader(builder, "x-ms-blob-content-type", options.getContentType()); - builder = addOptionalHeader(builder, "x-ms-blob-content-md5", options.getContentMD5()); - builder = addOptionalHeader(builder, "x-ms-blob-content-encoding", options.getContentEncoding()); - builder = addOptionalHeader(builder, "x-ms-blob-content-language", options.getContentLanguage()); - builder = addOptionalHeader(builder, "x-ms-blob-content-length", options.getContentLength()); - builder = addOptionalHeader(builder, "x-ms-sequence-number-action", options.getSequenceNumberAction()); - builder = addOptionalHeader(builder, "x-ms-blob-sequence-number", options.getSequenceNumber()); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - ClientResponse response = builder.put(ClientResponse.class, ""); - ThrowIfError(response); - - SetBlobPropertiesResult result = new SetBlobPropertiesResult(); - - result.setEtag(response.getHeaders().getFirst("ETag")); - result.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - if (response.getHeaders().getFirst("x-ms-blob-sequence-number") != null) { - result.setSequenceNumber(Long.parseLong(response.getHeaders().getFirst("x-ms-blob-sequence-number"))); - } - - return result; - } - - @Override - public SetBlobMetadataResult setBlobMetadata(String container, String blob, HashMap metadata) - throws ServiceException { - return setBlobMetadata(container, blob, metadata, new SetBlobMetadataOptions()); - } - - @Override - public SetBlobMetadataResult setBlobMetadata(String container, String blob, HashMap metadata, - SetBlobMetadataOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "metadata"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalMetadataHeader(builder, metadata); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - ClientResponse response = builder.put(ClientResponse.class, ""); - ThrowIfError(response); - - SetBlobMetadataResult result = new SetBlobMetadataResult(); - result.setEtag(response.getHeaders().getFirst("ETag")); - result.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - return result; - } - - @Override - public GetBlobResult getBlob(String container, String blob) throws ServiceException { - return getBlob(container, blob, new GetBlobOptions()); - } - - @Override - public GetBlobResult getBlob(String container, String blob, GetBlobOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob); - webResource = addOptionalQueryParam(webResource, "snapshot", options.getSnapshot()); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalRangeHeader(builder, options.getRangeStart(), options.getRangeEnd()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - if (options.isComputeRangeMD5()) { - builder = addOptionalHeader(builder, "x-ms-range-get-content-md5", "true"); - } - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfNotSuccess(response); - - GetBlobPropertiesResult properties = getBlobPropertiesResultFromResponse(response); - GetBlobResult blobResult = new GetBlobResult(); - blobResult.setProperties(properties.getProperties()); - blobResult.setMetadata(properties.getMetadata()); - blobResult.setContentStream(response.getEntityInputStream()); - return blobResult; - } - - @Override - public void deleteBlob(String container, String blob) throws ServiceException { - deleteBlob(container, blob, new DeleteBlobOptions()); - } - - @Override - public void deleteBlob(String container, String blob, DeleteBlobOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob); - webResource = addOptionalQueryParam(webResource, "snapshot", options.getSnapshot()); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - if (options.getDeleteSnaphotsOnly() != null) { - builder = addOptionalHeader(builder, "x-ms-delete-snapshots", options.getDeleteSnaphotsOnly() ? "only" - : "include"); - } - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - builder.delete(); - } - - @Override - public CreateBlobSnapshotResult createBlobSnapshot(String container, String blob) throws ServiceException { - return createBlobSnapshot(container, blob, new CreateBlobSnapshotOptions()); - } - - @Override - public CreateBlobSnapshotResult createBlobSnapshot(String container, String blob, CreateBlobSnapshotOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "snapshot"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalMetadataHeader(builder, options.getMetadata()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - ClientResponse response = builder.put(ClientResponse.class, ""); - ThrowIfError(response); - - CreateBlobSnapshotResult blobSnapshot = new CreateBlobSnapshotResult(); - blobSnapshot.setEtag(response.getHeaders().getFirst("ETag")); - blobSnapshot.setSnapshot(response.getHeaders().getFirst("x-ms-snapshot")); - blobSnapshot.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - - return blobSnapshot; - } - - @Override - public CopyBlobResult copyBlob(String destinationContainer, String destinationBlob, String sourceContainer, - String sourceBlob) throws ServiceException { - return copyBlob(destinationContainer, destinationBlob, sourceContainer, sourceBlob, new CopyBlobOptions()); - } - - @Override - public CopyBlobResult copyBlob(String destinationContainer, String destinationBlob, String sourceContainer, - String sourceBlob, CopyBlobOptions options) { - String path = createPathFromContainer(destinationContainer); - WebResource webResource = getResource(options).path(path).path(destinationBlob); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalHeader(builder, "x-ms-source-lease-id", options.getSourceLeaseId()); - builder = addOptionalHeader(builder, "x-ms-copy-source", - getCopyBlobSourceName(sourceContainer, sourceBlob, options)); - builder = addOptionalMetadataHeader(builder, options.getMetadata()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - builder = addOptionalSourceAccessConditionHeader(builder, options.getSourceAccessCondition()); - - ClientResponse clientResponse = builder.put(ClientResponse.class, ""); - ThrowIfError(clientResponse); - - CopyBlobResult copyBlobResult = new CopyBlobResult(); - copyBlobResult.setEtag(clientResponse.getHeaders().getFirst("ETag")); - copyBlobResult.setLastModified(dateMapper.parse(clientResponse.getHeaders().getFirst("Last-Modified"))); - - return copyBlobResult; - } - - @Override - public AcquireLeaseResult acquireLease(String container, String blob) throws ServiceException { - return acquireLease(container, blob, new AcquireLeaseOptions()); - } - - @Override - public AcquireLeaseResult acquireLease(String container, String blob, AcquireLeaseOptions options) - throws ServiceException { - return putLeaseImpl("acquire", container, blob, null/* leaseId */, options, options.getAccessCondition()); - } - - @Override - public AcquireLeaseResult renewLease(String container, String blob, String leaseId) throws ServiceException { - return renewLease(container, blob, leaseId, new BlobServiceOptions()); - } - - @Override - public AcquireLeaseResult renewLease(String container, String blob, String leaseId, BlobServiceOptions options) - throws ServiceException { - return putLeaseImpl("renew", container, blob, leaseId, options, null/* accessCondition */); - } - - @Override - public void releaseLease(String container, String blob, String leaseId) throws ServiceException { - releaseLease(container, blob, leaseId, new BlobServiceOptions()); - } - - @Override - public void releaseLease(String container, String blob, String leaseId, BlobServiceOptions options) - throws ServiceException { - putLeaseImpl("release", container, blob, leaseId, options, null/* accessCondition */); - } - - @Override - @Deprecated - public void breakLease(String container, String blob, String leaseId) throws ServiceException { - breakLease(container, blob); - } - - @Override - @Deprecated - public void breakLease(String container, String blob, String leaseId, BlobServiceOptions options) - throws ServiceException { - breakLease(container, blob, options); - } - - @Override - public BreakLeaseResult breakLease(String container, String blob) throws ServiceException { - return breakLease(container, blob, new BlobServiceOptions()); - } - - @Override - public BreakLeaseResult breakLease(String container, String blob, BlobServiceOptions options) - throws ServiceException { - ClientResponse response = doLeaseOperation("break", container, blob, null, options, null); - - BreakLeaseResult result = new BreakLeaseResult(); - result.setRemainingLeaseTimeInSeconds(Integer.parseInt(response.getHeaders().getFirst("x-ms-lease-time"))); - return result; - } - - private AcquireLeaseResult putLeaseImpl(String leaseAction, String container, String blob, String leaseId, - BlobServiceOptions options, AccessCondition accessCondition) throws ServiceException { - ClientResponse response = doLeaseOperation(leaseAction, container, blob, leaseId, options, accessCondition); - - AcquireLeaseResult result = new AcquireLeaseResult(); - result.setLeaseId(response.getHeaders().getFirst("x-ms-lease-id")); - return result; - } - - private ClientResponse doLeaseOperation(String leaseAction, String container, String blob, String leaseId, - BlobServiceOptions options, AccessCondition accessCondition) { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "lease"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - if (leaseId != null) { - builder = addOptionalHeader(builder, "x-ms-lease-id", leaseId); - } - builder = addOptionalHeader(builder, "x-ms-lease-action", leaseAction); - builder = addOptionalAccessConditionHeader(builder, accessCondition); - - // Note: Add content type here to enable proper HMAC signing - ClientResponse response = builder.put(ClientResponse.class, ""); - ThrowIfError(response); - return response; - } - - @Override - public CreateBlobPagesResult clearBlobPages(String container, String blob, PageRange range) throws ServiceException { - return clearBlobPages(container, blob, range, new CreateBlobPagesOptions()); - } - - @Override - public CreateBlobPagesResult clearBlobPages(String container, String blob, PageRange range, - CreateBlobPagesOptions options) throws ServiceException { - return updatePageBlobPagesImpl("clear", container, blob, range, 0, null, options); - } - - @Override - public CreateBlobPagesResult createBlobPages(String container, String blob, PageRange range, long length, - InputStream contentStream) throws ServiceException { - return createBlobPages(container, blob, range, length, contentStream, new CreateBlobPagesOptions()); - } - - @Override - public CreateBlobPagesResult createBlobPages(String container, String blob, PageRange range, long length, - InputStream contentStream, CreateBlobPagesOptions options) throws ServiceException { - return updatePageBlobPagesImpl("update", container, blob, range, length, contentStream, options); - } - - private CreateBlobPagesResult updatePageBlobPagesImpl(String action, String container, String blob, - PageRange range, long length, InputStream contentStream, CreateBlobPagesOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "page"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalRangeHeader(builder, range.getStart(), range.getEnd()); - builder = addOptionalHeader(builder, "Content-Length", length); - builder = addOptionalHeader(builder, "Content-MD5", options.getContentMD5()); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalHeader(builder, "x-ms-page-write", action); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - Object contentObject = (contentStream == null ? new byte[0] : contentStream); - ClientResponse response = builder.put(ClientResponse.class, contentObject); - ThrowIfError(response); - - CreateBlobPagesResult result = new CreateBlobPagesResult(); - result.setEtag(response.getHeaders().getFirst("ETag")); - result.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - result.setContentMD5(response.getHeaders().getFirst("Content-MD5")); - result.setSequenceNumber(Long.parseLong(response.getHeaders().getFirst("x-ms-blob-sequence-number"))); - - return result; - } - - @Override - public ListBlobRegionsResult listBlobRegions(String container, String blob) throws ServiceException { - return listBlobRegions(container, blob, new ListBlobRegionsOptions()); - } - - @Override - public ListBlobRegionsResult listBlobRegions(String container, String blob, ListBlobRegionsOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "pagelist"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalRangeHeader(builder, options.getRangeStart(), options.getRangeEnd()); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - ListBlobRegionsResult result = response.getEntity(ListBlobRegionsResult.class); - result.setEtag(response.getHeaders().getFirst("ETag")); - result.setContentLength(Long.parseLong(response.getHeaders().getFirst("x-ms-blob-content-length"))); - result.setLastModified(dateMapper.parse(response.getHeaders().getFirst("Last-Modified"))); - - return result; - } - - @Override - public void createBlobBlock(String container, String blob, String blockId, InputStream contentStream) - throws ServiceException { - createBlobBlock(container, blob, blockId, contentStream, new CreateBlobBlockOptions()); - } - - @Override - public void createBlobBlock(String container, String blob, String blockId, InputStream contentStream, - CreateBlobBlockOptions options) throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "block"); - try { - webResource = addOptionalQueryParam(webResource, "blockid", new String(Base64.encode(blockId), "UTF-8")); - } - catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalHeader(builder, "Content-MD5", options.getContentMD5()); - - builder.put(contentStream); - } - - @Override - public void commitBlobBlocks(String container, String blob, BlockList blockList) throws ServiceException { - commitBlobBlocks(container, blob, blockList, new CommitBlobBlocksOptions()); - } - - @Override - public void commitBlobBlocks(String container, String blob, BlockList blockList, CommitBlobBlocksOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "blocklist"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - builder = addOptionalHeader(builder, "x-ms-blob-cache-control", options.getBlobCacheControl()); - builder = addOptionalHeader(builder, "x-ms-blob-content-type", options.getBlobContentType()); - builder = addOptionalHeader(builder, "x-ms-blob-content-encoding", options.getBlobContentEncoding()); - builder = addOptionalHeader(builder, "x-ms-blob-content-language", options.getBlobContentLanguage()); - builder = addOptionalHeader(builder, "x-ms-blob-content-md5", options.getBlobContentMD5()); - builder = addOptionalMetadataHeader(builder, options.getMetadata()); - builder = addOptionalAccessConditionHeader(builder, options.getAccessCondition()); - - builder.put(blockList); - } - - @Override - public ListBlobBlocksResult listBlobBlocks(String container, String blob) throws ServiceException { - return listBlobBlocks(container, blob, new ListBlobBlocksOptions()); - } - - @Override - public ListBlobBlocksResult listBlobBlocks(String container, String blob, ListBlobBlocksOptions options) - throws ServiceException { - String path = createPathFromContainer(container); - WebResource webResource = getResource(options).path(path).path(blob).queryParam("comp", "blocklist"); - webResource = addOptionalQueryParam(webResource, "snapshot", options.getSnapshot()); - if (options.isCommittedList() && options.isUncommittedList()) { - webResource = addOptionalQueryParam(webResource, "blocklisttype", "all"); - } - else if (options.isCommittedList()) { - webResource = addOptionalQueryParam(webResource, "blocklisttype", "committed"); - } - else if (options.isUncommittedList()) { - webResource = addOptionalQueryParam(webResource, "blocklisttype", "uncommitted"); - } - - Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "x-ms-lease-id", options.getLeaseId()); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - ListBlobBlocksResult result = response.getEntity(ListBlobBlocksResult.class); - result.setEtag(response.getHeaders().getFirst("ETag")); - result.setContentType(response.getHeaders().getFirst("Content-Type")); - - String blobContentLength = response.getHeaders().getFirst("x-ms-blob-content-length"); - if (blobContentLength != null) { - result.setContentLength(Long.parseLong(blobContentLength)); - } - else { - result.setContentLength(0); - } - - String lastModified = response.getHeaders().getFirst("Last-Modified"); - if (lastModified != null) { - result.setLastModified(dateMapper.parse(lastModified)); - } - - return result; - } - - private String createPathFromContainer(String containerName) { - String path; - if (containerName == null || containerName.isEmpty()) { - path = "$root"; - } - else { - path = containerName; - } - return path; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobRestProxy.java deleted file mode 100644 index 3c5c7325d1c19..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/BlobRestProxy.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.implementation; - -import java.util.Arrays; - -import javax.inject.Inject; -import javax.inject.Named; - -import com.microsoft.windowsazure.services.blob.BlobConfiguration; -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.pipeline.HttpURLConnectionClient; -import com.sun.jersey.api.client.Client; - -public class BlobRestProxy extends BlobOperationRestProxy implements BlobContract { - private final SharedKeyFilter sharedKeyFilter; - - @Inject - public BlobRestProxy(HttpURLConnectionClient channel, @Named(BlobConfiguration.ACCOUNT_NAME) String accountName, - @Named(BlobConfiguration.URI) String url, SharedKeyFilter sharedKeyFilter, UserAgentFilter userAgentFilter) { - super(channel, accountName, url); - - this.sharedKeyFilter = sharedKeyFilter; - - channel.addFilter(sharedKeyFilter); - channel.addFilter(userAgentFilter); - } - - public BlobRestProxy(Client client, ServiceFilter[] filters, String accountName, String url, - SharedKeyFilter sharedKeyFilter, RFC1123DateConverter dateMapper) { - super(client, filters, accountName, url, dateMapper); - - this.sharedKeyFilter = sharedKeyFilter; - } - - @Override - public BlobContract withFilter(ServiceFilter filter) { - ServiceFilter[] currentFilters = getFilters(); - ServiceFilter[] newFilters = Arrays.copyOf(currentFilters, currentFilters.length + 1); - newFilters[currentFilters.length] = filter; - return new BlobRestProxy(getChannel(), newFilters, getAccountName(), getUrl(), this.sharedKeyFilter, - getDateMapper()); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyFilter.java deleted file mode 100644 index 6030c865d47b5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyFilter.java +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.implementation; - -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -import javax.inject.Named; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.blob.BlobConfiguration; -import com.microsoft.windowsazure.services.blob.implementation.SharedKeyUtils.QueryParam; -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.utils.pipeline.EntityStreamingListener; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; - -public class SharedKeyFilter extends ClientFilter implements EntityStreamingListener { - private static Log log = LogFactory.getLog(SharedKeyFilter.class); - - private final String accountName; - private final HmacSHA256Sign signer; - - public SharedKeyFilter(@Named(BlobConfiguration.ACCOUNT_NAME) String accountName, - @Named(BlobConfiguration.ACCOUNT_KEY) String accountKey) { - this.accountName = accountName; - this.signer = new HmacSHA256Sign(accountKey); - } - - protected String getHeader(ClientRequest cr, String headerKey) { - return SharedKeyUtils.getHeader(cr, headerKey); - } - - protected HmacSHA256Sign getSigner() { - return signer; - } - - protected String getAccountName() { - return accountName; - } - - @Override - public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { - // Only sign if no other filter is handling authorization - if (cr.getProperties().get(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER) == null) { - cr.getProperties().put(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER, null); - - // Register ourselves as listener so we are called back when the entity is - // written to the output stream by the next filter in line. - if (cr.getProperties().get(EntityStreamingListener.class.getName()) == null) { - cr.getProperties().put(EntityStreamingListener.class.getName(), this); - } - - } - return this.getNext().handle(cr); - } - - @Override - public void onBeforeStreamingEntity(ClientRequest clientRequest) { - // All headers should be known at this point, time to sign! - sign(clientRequest); - } - - /* - * StringToSign = VERB + "\n" + - * Content-Encoding + "\n" - * Content-Language + "\n" - * Content-Length + "\n" - * Content-MD5 + "\n" + - * Content-Type + "\n" + - * Date + "\n" + - * If-Modified-Since + "\n" - * If-Match + "\n" - * If-None-Match + "\n" - * If-Unmodified-Since + "\n" - * Range + "\n" - * CanonicalizedHeaders + - * CanonicalizedResource; - */ - public void sign(ClientRequest cr) { - // gather signed material - addOptionalDateHeader(cr); - - // build signed string - String stringToSign = cr.getMethod() + "\n" + getHeader(cr, "Content-Encoding") + "\n" - + getHeader(cr, "Content-Language") + "\n" + getHeader(cr, "Content-Length") + "\n" - + getHeader(cr, "Content-MD5") + "\n" + getHeader(cr, "Content-Type") + "\n" + getHeader(cr, "Date") - + "\n" + getHeader(cr, "If-Modified-Since") + "\n" + getHeader(cr, "If-Match") + "\n" - + getHeader(cr, "If-None-Match") + "\n" + getHeader(cr, "If-Unmodified-Since") + "\n" - + getHeader(cr, "Range") + "\n"; - - stringToSign += getCanonicalizedHeaders(cr); - stringToSign += getCanonicalizedResource(cr); - - if (log.isDebugEnabled()) { - log.debug(String.format("String to sign: \"%s\"", stringToSign)); - } - //System.out.println(String.format("String to sign: \"%s\"", stringToSign)); - - String signature = this.signer.sign(stringToSign); - cr.getHeaders().putSingle("Authorization", "SharedKey " + this.accountName + ":" + signature); - } - - protected void addOptionalDateHeader(ClientRequest cr) { - String date = getHeader(cr, "Date"); - if (date == "") { - date = new RFC1123DateConverter().format(new Date()); - cr.getHeaders().putSingle("Date", date); - } - } - - /** - * Constructing the Canonicalized Headers String - * - * To construct the CanonicalizedHeaders portion of the signature string, - * follow these steps: - * - * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - * - * 2. Convert each HTTP header name to lowercase. - * - * 3. Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only - * once in the string. - * - * 4. Unfold the string by replacing any breaking white space with a - * single space. - * - * 5. Trim any white space around the colon in the header. - * - * 6. Finally, append a new line character to each canonicalized header in the resulting list. Construct the - * CanonicalizedHeaders string by concatenating all headers in this list into a single string. - */ - private String getCanonicalizedHeaders(ClientRequest cr) { - return SharedKeyUtils.getCanonicalizedHeaders(cr); - } - - /** - * This format supports Shared Key authentication for the 2009-09-19 version of the Blob and Queue services. - * Construct the CanonicalizedResource string in this format as follows: - * - * 1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns - * the resource being accessed. - * - * 2. Append the resource's encoded URI path, without any query parameters. - * - * 3. Retrieve all query parameters on the resource URI, including the comp parameter if it exists. - * - * 4. Convert all parameter names to lowercase. - * - * 5. Sort the query parameters lexicographically by parameter name, in ascending order. - * - * 6. URL-decode each query parameter name and value. - * - * 7. Append each query parameter name and value to the string in the following format, making sure to include the - * colon (:) between the name and the value: - * - * parameter-name:parameter-value - * - * 8. If a query parameter has more than one value, sort all values lexicographically, then include them in a - * comma-separated list: - * - * parameter-name:parameter-value-1,parameter-value-2,parameter-value-n - * - * 9. Append a new line character (\n) after each name-value pair. - */ - private String getCanonicalizedResource(ClientRequest cr) { - // 1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns - // the resource being accessed. - String result = "/" + this.accountName; - - // 2. Append the resource's encoded URI path, without any query parameters. - result += cr.getURI().getPath(); - - // 3. Retrieve all query parameters on the resource URI, including the comp parameter if it exists. - // 6. URL-decode each query parameter name and value. - List queryParams = SharedKeyUtils.getQueryParams(cr.getURI().getQuery()); - - // 4. Convert all parameter names to lowercase. - for (QueryParam param : queryParams) { - param.setName(param.getName().toLowerCase(Locale.US)); - } - - // 5. Sort the query parameters lexicographically by parameter name, in ascending order. - Collections.sort(queryParams); - - // 7. Append each query parameter name and value to the string - // 8. If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list - for (int i = 0; i < queryParams.size(); i++) { - QueryParam param = queryParams.get(i); - - List values = param.getValues(); - //Collections.sort(values); - - // 9. Append a new line character (\n) after each name-value pair. - result += "\n"; - result += param.getName(); - result += ":"; - for (int j = 0; j < values.size(); j++) { - if (j > 0) { - result += ","; - } - result += values.get(j); - } - } - - return result; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyLiteFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyLiteFilter.java deleted file mode 100644 index 5600b07e8ecdb..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/implementation/SharedKeyLiteFilter.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.implementation; - -import java.util.Date; -import java.util.List; - -import javax.inject.Named; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.blob.BlobConfiguration; -import com.microsoft.windowsazure.services.blob.implementation.SharedKeyUtils.QueryParam; -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.utils.pipeline.EntityStreamingListener; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; - -public class SharedKeyLiteFilter extends ClientFilter implements EntityStreamingListener { - private static Log log = LogFactory.getLog(SharedKeyLiteFilter.class); - - private final String accountName; - private final HmacSHA256Sign signer; - - public SharedKeyLiteFilter(@Named(BlobConfiguration.ACCOUNT_NAME) String accountName, - @Named(BlobConfiguration.ACCOUNT_KEY) String accountKey) { - - this.accountName = accountName; - this.signer = new HmacSHA256Sign(accountKey); - } - - @Override - public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { - // Only sign if no other filter is handling authorization - if (cr.getProperties().get(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER) == null) { - cr.getProperties().put(SharedKeyUtils.AUTHORIZATION_FILTER_MARKER, null); - - // Register ourselves as listener so we are called back when the entity is - // written to the output stream by the next filter in line. - if (cr.getProperties().get(EntityStreamingListener.class.getName()) == null) { - cr.getProperties().put(EntityStreamingListener.class.getName(), this); - } - } - - return this.getNext().handle(cr); - } - - @Override - public void onBeforeStreamingEntity(ClientRequest clientRequest) { - // All headers should be known at this point, time to sign! - sign(clientRequest); - } - - /* - * StringToSign = VERB + "\n" + Content-MD5 + "\n" + Content-Type + "\n" + - * Date + "\n" + CanonicalizedHeaders + CanonicalizedResource; - */ - public void sign(ClientRequest cr) { - // gather signed material - String requestMethod = cr.getMethod(); - String contentMD5 = getHeader(cr, "Content-MD5"); - String contentType = getHeader(cr, "Content-Type"); - String date = getHeader(cr, "Date"); - - if (date == "") { - date = new RFC1123DateConverter().format(new Date()); - cr.getHeaders().add("Date", date); - } - - // build signed string - String stringToSign = requestMethod + "\n" + contentMD5 + "\n" + contentType + "\n" + date + "\n"; - - stringToSign += addCanonicalizedHeaders(cr); - stringToSign += addCanonicalizedResource(cr); - - if (log.isDebugEnabled()) { - log.debug(String.format("String to sign: \"%s\"", stringToSign)); - } - - String signature = this.signer.sign(stringToSign); - cr.getHeaders().putSingle("Authorization", "SharedKeyLite " + this.accountName + ":" + signature); - } - - /** - * Constructing the Canonicalized Headers String - * - * To construct the CanonicalizedHeaders portion of the signature string, - * follow these steps: - * - * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - * - * 2. Convert each HTTP header name to lowercase. - * - * 3. Sort the headers lexicographically by header name in ascending order. Note that each header may appear only - * once in the string. - * - * 4. Unfold the string by replacing any breaking white space with a single space. - * - * 5. Trim any white space around the colon in the header. - * - * 6. Finally, append a new line character to each canonicalized header in the resulting list. Construct the - * CanonicalizedHeaders string by concatenating all headers in this list into a single string. - */ - private String addCanonicalizedHeaders(ClientRequest cr) { - return SharedKeyUtils.getCanonicalizedHeaders(cr); - } - - /** - * This format supports Shared Key and Shared Key Lite for all versions of the Table service, and Shared Key Lite - * for the 2009-09-19 version of the Blob and Queue services. This format is identical to that used with previous - * versions of the storage services. Construct the CanonicalizedResource string in this format as follows: - * - * 1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns - * the resource being accessed. - * - * 2. Append the resource's encoded URI path. If the request URI addresses a component of the resource, append the - * appropriate query string. The query string should include the question mark and the comp parameter (for example, - * ?comp=metadata). No other parameters should be included on the query string. - */ - private String addCanonicalizedResource(ClientRequest cr) { - String result = "/" + this.accountName; - - result += cr.getURI().getPath(); - - List queryParams = SharedKeyUtils.getQueryParams(cr.getURI().getQuery()); - for (QueryParam p : queryParams) { - if ("comp".equals(p.getName())) { - result += "?" + p.getName() + "=" + p.getValues().get(0); - } - } - return result; - } - - private String getHeader(ClientRequest cr, String headerKey) { - return SharedKeyUtils.getHeader(cr, headerKey); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessCondition.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessCondition.java deleted file mode 100644 index cd4a21fb17bf5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AccessCondition.java +++ /dev/null @@ -1,183 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; - -/** - * Represents a set of access conditions for operations that use storage services. - */ -public final class AccessCondition { - - /** - * Specifies an access condition with no conditions set. - */ - public static final AccessCondition NONE = new AccessCondition(AccessConditionHeaderType.NONE, null); - - /** - * Creates an access condition that only allows an operation if the resource's ETag value matches the specified ETag - * value. - *

- * Setting this access condition modifies the request to include the HTTP If-Match conditional header. If - * this access condition is set, the operation is performed only if the ETag of the resource matches the specified - * ETag. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param etag - * A String that represents the ETag value to check. - * - * @return An AccessCondition object that represents the If-Match condition. - */ - public static AccessCondition ifMatch(String etag) { - return new AccessCondition(AccessConditionHeaderType.IF_MATCH, etag); - } - - /** - * Creates an access condition that only allows an operation if the resource has been modified since the specified - * time. - *

- * Setting this access condition modifies the request to include the HTTP If-Modified-Since conditional - * header. If this access condition is set, the operation is performed only if the resource has been modified since - * the specified time. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param lastMotified - * A java.util.Date object that represents the last-modified time to check for the resource. - * - * @return An AccessCondition object that represents the If-Modified-Since condition. - */ - public static AccessCondition ifModifiedSince(Date lastMotified) { - return new AccessCondition(AccessConditionHeaderType.IF_MODIFIED_SINCE, - new RFC1123DateConverter().format(lastMotified)); - } - - /** - * Creates an access condition that only allows an operation if the resource's ETag value does not match the - * specified ETag value. - *

- * Setting this access condition modifies the request to include the HTTP If-None-Match conditional header. - * If this access condition is set, the operation is performed only if the ETag of the resource does not match the - * specified ETag. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param etag - * A String that represents the ETag value to check. - * - * @return An AccessCondition object that represents the If-None-Match condition. - */ - public static AccessCondition ifNoneMatch(String etag) { - return new AccessCondition(AccessConditionHeaderType.IF_NONE_MATCH, etag); - } - - /** - * Creates an access condition that only allows an operation if the resource has not been modified since the - * specified time. - *

- * Setting this access condition modifies the request to include the HTTP If-Unmodified-Since conditional - * header. If this access condition is set, the operation is performed only if the resource has not been modified - * since the specified time. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param lastMotified - * A java.util.Date object that represents the last-modified time to check for the resource. - * - * @return An AccessCondition object that represents the If-Unmodified-Since condition. - */ - public static AccessCondition ifNotModifiedSince(Date lastMotified) { - return new AccessCondition(AccessConditionHeaderType.IF_UNMODIFIED_SINCE, - new RFC1123DateConverter().format(lastMotified)); - } - - /** - * Represents the access condition header type. - */ - private AccessConditionHeaderType header = AccessConditionHeaderType.NONE; - - /** - * Represents the access condition header value. - */ - private String value; - - /** - * Creates an instance of the AccessCondition class. - */ - protected AccessCondition() { - // Empty Default Ctor - } - - /** - * Creates an instance of the AccessCondition class using the specified header type and value. - * - * @param headerType - * An {@link AccessConditionHeaderType} value that represents the header type. - * @param value - * A String that represents the value of the header. - */ - protected AccessCondition(AccessConditionHeaderType headerType, String value) { - this.setHeader(headerType); - this.setValue(value); - } - - /** - * Gets the access condition header type set in this AccessCondition instance. - * - * @return - * The {@link AccessConditionHeaderType} set in this AccessCondition instance. - */ - public AccessConditionHeaderType getHeader() { - return header; - } - - /** - * Sets the access condition header type in this AccessCondition instance. - * - * @param header - * The {@link AccessConditionHeaderType} to set in this AccessCondition instance. - */ - public void setHeader(AccessConditionHeaderType header) { - this.header = header; - } - - /** - * Gets the access condition value set in this AccessCondition instance. - * - * @return - * A {@link String} containing the access condition value set in this AccessCondition instance. - */ - public String getValue() { - return value; - } - - /** - * Sets the access condition value in this AccessCondition instance. - * - * @param value - * A {@link String} containing the access condition value to set in this AccessCondition - * instance. - */ - public void setValue(String value) { - this.value = value; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseOptions.java deleted file mode 100644 index dce54430b5386..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseOptions.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on an {@link BlobContract#acquireLease(String, String, AcquireLeaseOptions) - * acquireLease} request. - * These options include an optional server timeout for the operation and any access conditions for the operation. - */ -public class AcquireLeaseOptions extends BlobServiceOptions { - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link AcquireLeaseOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link AcquireLeaseOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link AcquireLeaseOptions} instance. - */ - @Override - public AcquireLeaseOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the access conditions set in this {@link AcquireLeaseOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions for acquiring a lease on a blob. By default, the operation will acquire the lease - * unconditionally. Use this method to specify conditions on the ETag or last modified time value for performing the - * operation. - *

- * The accessCondition value only affects calls made on methods where this {@link AcquireLeaseOptions} - * instance is passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link AcquireLeaseOptions} instance. - */ - public AcquireLeaseOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseResult.java deleted file mode 100644 index 4c4803afeb0f1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/AcquireLeaseResult.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Lease Blob operation. This is returned by - * calls to implementations of {@link BlobContract#acquireLease(String, String)}, - * {@link BlobContract#acquireLease(String, String, AcquireLeaseOptions)}, - * {@link BlobContract#renewLease(String, String, String, BlobServiceOptions)}, and - * {@link BlobContract#renewLease(String, String, String)}. - *

- * See the Lease Blob documentation on - * MSDN for details of the underlying Blob Service REST API operation. - */ -public class AcquireLeaseResult { - private String leaseId; - - /** - * Gets the lease ID of the blob. - *

- * This value is used when updating or deleting a blob with an active lease, and when renewing or releasing the - * lease. - * - * @return - * A {@link String} containing the server-assigned lease ID for the blob. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Reserved for internal use. Sets the lease ID of the blob from the x-ms-lease-id header of the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param leaseId - * A {@link String} containing the server-assigned lease ID for the blob. - */ - public void setLeaseId(String leaseId) { - this.leaseId = leaseId; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobProperties.java deleted file mode 100644 index a19d7e73f8c95..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobProperties.java +++ /dev/null @@ -1,300 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.core.RFC1123DateAdapter; - -/** - * Represents the HTML properties and system properties that may be set on a blob. - */ -public class BlobProperties { - private Date lastModified; - private String etag; - private String contentType; - private long contentLength; - private String contentEncoding; - private String contentLanguage; - private String contentMD5; - private String cacheControl; - private String blobType; - private String leaseStatus; - private long sequenceNumber; - - /** - * Gets the last modified time of the blob. For block blobs, this value is returned only if the blob has committed - * blocks. - *

- * Any operation that modifies the blob, including updates to the blob's metadata or properties, changes the last - * modified time of the blob. This value can be used in an access condition when updating or deleting a blob to - * prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the blob. - */ - @XmlElement(name = "Last-Modified") - @XmlJavaTypeAdapter(RFC1123DateAdapter.class) - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the blob from the Last-Modified header - * value returned in a server response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the ETag of the blob. For block blobs, this value is returned only if the blob has committed blocks. - *

- * This value can be used in an access condition when updating or deleting a blob to prevent the client from - * modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the blob. - */ - @XmlElement(name = "Etag") - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag value of the blob from the ETag header value returned in a - * server response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the MIME content type of the blob. - * - * @return - * A {@link String} containing the MIME content type value for the blob. - */ - @XmlElement(name = "Content-Type") - public String getContentType() { - return contentType; - } - - /** - * Reserved for internal use. Sets the MIME content type value for the blob from the Content-Type - * header value returned in the server response. - * - * @param contentType - * A {@link String} containing the MIME content type value for the blob. - */ - public void setContentType(String contentType) { - this.contentType = contentType; - } - - /** - * Gets the size of the blob in bytes. - * - * @return - * The size of the blob in bytes. - */ - @XmlElement(name = "Content-Length") - public long getContentLength() { - return contentLength; - } - - /** - * Reserved for internal use. Sets the content length value for the blob from the Content-Length header - * value returned in the server response. - * - * @param contentLength - * The size of the blob in bytes. - */ - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - /** - * Gets the HTTP content encoding value of the blob. - * - * @return - * A {@link String} containing the HTTP content encoding value set, if any. - */ - @XmlElement(name = "Content-Encoding") - public String getContentEncoding() { - return contentEncoding; - } - - /** - * Reserved for internal use. Sets the HTTP content encoding value for the blob from the - * Content-Encoding header value returned in the server response. - * - * @param contentEncoding - * A {@link String} containing the HTTP content encoding value to set. - */ - public void setContentEncoding(String contentEncoding) { - this.contentEncoding = contentEncoding; - } - - /** - * Gets the HTTP content language value of the blob. - * - * @return - * A {@link String} containing the HTTP content language value set, if any. - */ - @XmlElement(name = "Content-Language") - public String getContentLanguage() { - return contentLanguage; - } - - /** - * Reserved for internal use. Sets the HTTP content language value for the blob from the - * Content-Language header value returned in the server response. - * - * @param contentLanguage - * A {@link String} containing the HTTP content language value to set. - */ - public void setContentLanguage(String contentLanguage) { - this.contentLanguage = contentLanguage; - } - - /** - * Gets the MD5 hash value of the blob content. - * - * @return - * A {@link String} containing the MD5 hash value of the blob content. - */ - @XmlElement(name = "Content-MD5") - public String getContentMD5() { - return contentMD5; - } - - /** - * Reserved for internal use. Sets the MD5 hash value of the blob content from the Content-MD5 header - * value returned in the server response. - * - * @param contentMD5 - * A {@link String} containing the MD5 hash value of the blob content. - */ - public void setContentMD5(String contentMD5) { - this.contentMD5 = contentMD5; - } - - /** - * Gets the HTTP cache control value of the blob. - * - * @return - * A {@link String} containing the HTTP cache control value of the blob. - */ - @XmlElement(name = "Cache-Control") - public String getCacheControl() { - return cacheControl; - } - - /** - * Reserved for internal use. Sets the HTTP cache control value of the blob from the Cache-Control - * header value returned in the server response. - * - * @param cacheControl - * A {@link String} containing the HTTP cache control value of the blob. - */ - public void setCacheControl(String cacheControl) { - this.cacheControl = cacheControl; - } - - /** - * Gets a string representing the type of the blob, with a value of "BlockBlob" for block blobs, and "PageBlob" - * for page blobs. - * - * @return - * A {@link String} containing "BlockBlob" for block blobs, or "PageBlob" for page blobs. - */ - @XmlElement(name = "BlobType") - public String getBlobType() { - return blobType; - } - - /** - * Reserved for internal use. Sets the blob type from the x-ms-blob-type header value returned in the - * server response. - * - * @param blobType - * A {@link String} containing "BlockBlob" for block blobs, or "PageBlob" for page blobs. - */ - public void setBlobType(String blobType) { - this.blobType = blobType; - } - - /** - * Gets a string representing the lease status of the blob, with a value of "locked" for blobs with an active lease, - * and "unlocked" for blobs without an active lease. - * - * @return - * A {@link String} containing "locked" for blobs with an active lease, and "unlocked" for blobs without an - * active lease. - */ - @XmlElement(name = "LeaseStatus") - public String getLeaseStatus() { - return leaseStatus; - } - - /** - * Reserved for internal use. Sets the blob lease status from the x-ms-lease-status header value - * returned in the server response. - * - * @param leaseStatus - * A {@link String} containing "locked" for blobs with an active lease, and "unlocked" for blobs without - * an active lease. - */ - public void setLeaseStatus(String leaseStatus) { - this.leaseStatus = leaseStatus; - } - - /** - * Gets the current sequence number for a page blob. This value is not set for block blobs. - * - * @return - * The current sequence number of the page blob. - */ - @XmlElement(name = "x-ms-blob-sequence-number") - public long getSequenceNumber() { - return sequenceNumber; - } - - /** - * Reserved for internal use. Sets the page blob sequence number from the x-ms-blob-sequence-number - * header value returned in the server response. - * - * @param sequenceNumber - * The current sequence number of the page blob. - */ - public void setSequenceNumber(long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobServiceOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobServiceOptions.java deleted file mode 100644 index 1abb7d1984af5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BlobServiceOptions.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the base class for options that may be set on Blob Service REST API operations invoked through the - * {@link BlobContract} interface. This class defines a server request timeout, which can be applied to all operations. - */ -public class BlobServiceOptions { - // Nullable because it is optional - private Integer timeout; - - /** - * Gets the server request timeout value associated with this {@link BlobServiceOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link BlobServiceOptions} instance is passed as - * a parameter. - * - * @return - * The server request timeout value in milliseconds. - */ - public Integer getTimeout() { - return timeout; - } - - /** - * Sets the server request timeout value associated with this {@link BlobServiceOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link BlobServiceOptions} instance is passed as - * a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link BlobServiceOptions} instance. - */ - public BlobServiceOptions setTimeout(Integer timeout) { - this.timeout = timeout; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BreakLeaseResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BreakLeaseResult.java deleted file mode 100644 index d76f5e6564a1a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/BreakLeaseResult.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.blob.models; - -/** - * A wrapper class for the response returned from a Blob Service REST API Break Lease Blob operation. This is returned by - * calls to implementations of {@link com.microsoft.windowsazure.services.blob.BlobContract#breakLease(String, String, BlobServiceOptions)}, - *

- * See the Lease Blob documentation on - * MSDN for details of the underlying Blob Service REST API operation. - */ -public class BreakLeaseResult { - private int remainingLeaseTimeInSeconds; - - public int getRemainingLeaseTimeInSeconds() { - return remainingLeaseTimeInSeconds; - } - - public void setRemainingLeaseTimeInSeconds(int remainingLeaseTimeInSeconds) { - this.remainingLeaseTimeInSeconds = remainingLeaseTimeInSeconds; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CommitBlobBlocksOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CommitBlobBlocksOptions.java deleted file mode 100644 index 477c4b4bc0e16..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CommitBlobBlocksOptions.java +++ /dev/null @@ -1,300 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions) commitBlobBlocks} request. - * These options include an optional server timeout for the operation, the MIME content type and content encoding for - * the blob, the content language, the MD5 hash, a cache control value, blob metadata, a blob lease ID, and any access - * conditions for the operation. - */ -public class CommitBlobBlocksOptions extends BlobServiceOptions { - private String blobContentType; - private String blobContentEncoding; - private String blobContentLanguage; - private String blobContentMD5; - private String blobCacheControl; - private HashMap metadata = new HashMap(); - private String leaseId; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link CommitBlobBlocksOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CommitBlobBlocksOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - @Override - public CommitBlobBlocksOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the MIME content type value set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the MIME content type value set, if any. - */ - public String getBlobContentType() { - return blobContentType; - } - - /** - * Sets the optional MIME content type for the blob content. This value will be returned to clients in the - * Content-Type header of the response when the blob data or blob properties are requested. If no - * content type is specified, the default content type is application/octet-stream. - *

- * Note that this value only affects calls made on methods where this {@link CommitBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param blobContentType - * A {@link String} containing the MIME content type value to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setBlobContentType(String blobContentType) { - this.blobContentType = blobContentType; - return this; - } - - /** - * Gets the HTTP content encoding value set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the HTTP content encoding value set, if any. - */ - public String getBlobContentEncoding() { - return blobContentEncoding; - } - - /** - * Sets the optional HTTP content encoding value for the blob content. Use this value to specify any HTTP content - * encodings applied to the blob, passed as a x-ms-blob-content-encoding header value to the server. - * This value will be returned to clients in the headers of the response when the blob data or blob properties are - * requested. Pass an empty value to update a blob to the default value, which will cause no content encoding header - * to be returned with the blob. - *

- * Note that this value only affects calls made on methods where this {@link CommitBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param blobContentEncoding - * A {@link String} containing the x-ms-blob-content-encoding header value to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setBlobContentEncoding(String blobContentEncoding) { - this.blobContentEncoding = blobContentEncoding; - return this; - } - - /** - * Gets the HTTP content language header value set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the HTTP content language header value set, if any. - */ - public String getBlobContentLanguage() { - return blobContentLanguage; - } - - /** - * Sets the optional HTTP content language header value for the blob content. Use this value to - * specify the content language of the blob. This value will be returned to clients in the - * x-ms-blob-content-language header of the response when the blob data or blob properties are - * requested. - *

- * Note that this value only affects calls made on methods where this {@link CommitBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param blobContentLanguage - * A {@link String} containing the x-ms-blob-content-language header value to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setBlobContentLanguage(String blobContentLanguage) { - this.blobContentLanguage = blobContentLanguage; - return this; - } - - /** - * Gets the MD5 hash value for the blob content set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the MD5 hash value for the blob content set, if any. - */ - public String getBlobContentMD5() { - return blobContentMD5; - } - - /** - * Sets the optional MD5 hash value for the blob content. This value will be returned to clients in the - * x-ms-blob-content-md5 header value of the response when the blob data or blob properties are - * requested. This hash is used to verify the integrity of the blob during transport. When this header is specified, - * the storage service checks the hash of the content that has arrived with the one that was sent. If the two hashes - * do not match, the operation will fail with error code 400 (Bad Request), which will cause a ServiceException to - * be thrown. - *

- * Note that this value only affects calls made on methods where this {@link CommitBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param blobContentMD5 - * A {@link String} containing the MD5 hash value for the blob content to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setBlobContentMD5(String blobContentMD5) { - this.blobContentMD5 = blobContentMD5; - return this; - } - - /** - * Gets the HTTP cache control value set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the HTTP cache control value set, if any. - */ - public String getBlobCacheControl() { - return blobCacheControl; - } - - /** - * Sets the optional HTTP cache control value for the blob content. The Blob service stores - * this value but does not use or modify it. This value will be returned to clients in the headers of the response - * when the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CommitBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param blobCacheControl - * A {@link String} containing the HTTP cache control value to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setBlobCacheControl(String blobCacheControl) { - this.blobCacheControl = blobCacheControl; - return this; - } - - /** - * Gets the blob metadata collection set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata set, if any. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Sets the blob metadata collection to associate with the created blob. Metadata is a collection of name-value - * {@link String} pairs for client use and is opaque to the server. Metadata names must adhere to the naming rules - * for C# identifiers. - *

- * The metadata value only affects calls made on methods where this {@link CommitBlobBlocksOptions} - * instance is passed as a parameter. - * - * @param metadata - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setMetadata(HashMap metadata) { - this.metadata = metadata; - return this; - } - - /** - * Adds a name-value pair to the blob metadata collection associated with this {@link CommitBlobBlocksOptions} - * instance. - * - * @param key - * A {@link String} containing the name portion of the name-value pair to add to the metadata collection. - * @param value - * A {@link String} containing the value portion of the name-value pair to add to the metadata - * collection. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions addMetadata(String key, String value) { - this.getMetadata().put(key, value); - return this; - } - - /** - * Gets the lease ID for the blob set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets a lease ID value to match when updating the blob. If the blob has a lease, this parameter must be set with - * the matching leaseId value for the commit block blobs operation to succeed. - *

- * The leaseId value only affects calls made on methods where this {@link CommitBlobBlocksOptions} instance - * is passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the access conditions set in this {@link CommitBlobBlocksOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions for updating a blob. By default, the commit block blobs operation will set the - * container metadata unconditionally. Use this method to specify conditions on the ETag or last modified time value - * for performing the commit block blobs operation. - *

- * The accessCondition value only affects calls made on methods where this {@link CommitBlobBlocksOptions} - * instance is passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link CommitBlobBlocksOptions} instance. - */ - public CommitBlobBlocksOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ContainerACL.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ContainerACL.java deleted file mode 100644 index 1668ff5fef8a0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ContainerACL.java +++ /dev/null @@ -1,432 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.blob.implementation.ContainerACLDateAdapter; - -/** - * Represents the public access properties and the container-level access policies of a container in the Blob storage - * service. This is returned by calls to implementations of {@link BlobContract#getContainerACL(String)} and - * {@link BlobContract#getContainerACL(String, BlobServiceOptions)}, and passed as a parameter to calls to - * implementations of {@link BlobContract#setContainerACL(String, ContainerACL)} and - * {@link BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. - *

- * See the Get Container ACL and the Set Container ACL documentation on MSDN - * for details of the underlying Blob Service REST API operations. - */ -public class ContainerACL { - private String etag; - private Date lastModified; - private PublicAccessType publicAccess; - private List signedIdentifiers = new ArrayList(); - - /** - * Gets the Etag value associated with this {@link ContainerACL} instance. This is the value - * returned for a container by a Blob service REST API Get Container ACL operation, or the value to set on a - * container with a Set Container ACL operation. - * - * @return - * A {@link String} containing the Etag value associated with this {@link ContainerACL} - * instance. - */ - public String getEtag() { - return etag; - } - - /** - * Sets the Etag value to associate with this {@link ContainerACL} instance. - *

- * This value is only set on a container when this {@link ContainerACL} instance is passed as a parameter to a call - * to an implementation of {@link BlobContract#setContainerACL(String, ContainerACL)} or - * {@link BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. - * - * @param etag - * A {@link String} containing the Etag value to associate with this - * {@link ContainerACL} instance. - * - * @return - * A reference to this {@link ContainerACL} instance. - */ - public ContainerACL setEtag(String etag) { - this.etag = etag; - return this; - } - - /** - * Gets the last modified time associated with this {@link ContainerACL} instance. This is the value - * returned for a container by a Blob service REST API Get Container ACL operation, or the value to set on a - * container with a Set Container ACL operation. - * - * @return - * A {@link Date} containing the last modified time associated with this {@link ContainerACL} instance. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Sets the last modified time to associate with this {@link ContainerACL} instance. - *

- * This value is only set on a container when this {@link ContainerACL} instance is passed as a parameter to a call - * to an implementation of {@link BlobContract#setContainerACL(String, ContainerACL)} or - * {@link BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time to associate with this {@link ContainerACL} instance. - * @return - * A reference to this {@link ContainerACL} instance. - */ - public ContainerACL setLastModified(Date lastModified) { - this.lastModified = lastModified; - return this; - } - - /** - * Gets the public access level associated with this {@link ContainerACL} instance. This is the value - * returned for a container by a Blob service REST API Get Container ACL operation, or the value to set on a - * container with a Set Container ACL operation. - * - * @return - * A {@link PublicAccessType} value representing the public access level associated with this - * {@link ContainerACL} instance. - */ - public PublicAccessType getPublicAccess() { - return publicAccess; - } - - /** - * Sets the public access level to associate with this {@link ContainerACL} instance. - *

- * This value is only set on a container when this {@link ContainerACL} instance is passed as a parameter to a call - * to an implementation of {@link BlobContract#setContainerACL(String, ContainerACL)} or - * {@link BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. - * - * @param publicAccess - * A {@link PublicAccessType} value representing the public access level to associate with this - * {@link ContainerACL} instance. - * @return - * A reference to this {@link ContainerACL} instance. - */ - public ContainerACL setPublicAccess(PublicAccessType publicAccess) { - this.publicAccess = publicAccess; - return this; - } - - /** - * Gets the list of container-level access policies associated with this {@link ContainerACL} instance. This is the - * value returned for a container by a Blob service REST API Get Container ACL operation, or the value to set on a - * container with a Set Container ACL operation. - * - * @return - * A {@link List} of {@link SignedIdentifier} instances containing up to five container-level access - * policies associated with this {@link ContainerACL} instance. - */ - public List getSignedIdentifiers() { - return signedIdentifiers; - } - - /** - * Sets the list of container-level access policies to associate with this {@link ContainerACL} instance. - *

- * This value is only set on a container when this {@link ContainerACL} instance is passed as a parameter to a call - * to an implementation of {@link BlobContract#setContainerACL(String, ContainerACL)} or - * {@link BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. - * - * @param signedIdentifiers - * A {@link List} of {@link SignedIdentifier} instances containing up to five container-level access - * policies to associate with this {@link ContainerACL} instance. - * @return - * A reference to this {@link ContainerACL} instance. - */ - public ContainerACL setSignedIdentifiers(List signedIdentifiers) { - this.signedIdentifiers = signedIdentifiers; - return this; - } - - /** - * Adds a container-level access policy to the list associated with this {@link ContainerACL} instance. A container - * may have up to five container-level access policies. - *

- * Use the id parameter to specify a name for the access policy. The name may be up to 64 characters in - * length and must be unique within the container. - *

- * Use the start parameter to specify the start time for valid access to a resource using the access - * policy. If this value is null, the start time for any resource request using the access policy is - * assumed to be the time when the Blob service receives the request. - *

- * Use the expiry parameter to specify the expiration time for valid access to a resource using the access - * policy. If this value is null, the expiry time must be included in the Shared Access Signature for - * any resource request using the access policy. - *

- * Use the permission parameter to specify the operations that can be performed on a blob that is accessed - * with the access policy. Supported permissions include read (r), write (w), delete (d), and list (l). Permissions - * may be grouped so as to allow multiple operations to be performed with the access policy. For example, to grant - * all permissions to a resource, specify "rwdl" for the parameter. To grant only read/write permissions, specify - * "rw" for the parameter. - *

- * This value is only set on a container when this {@link ContainerACL} instance is passed as a parameter to a call - * to an implementation of {@link BlobContract#setContainerACL(String, ContainerACL)} or - * {@link BlobContract#setContainerACL(String, ContainerACL, BlobServiceOptions)}. - * - * @param id - * A {@link String} containing the name for the access policy. - * @param start - * A {@link Date} representing the start time for the access policy. If this value is null, - * any Shared Access Signature that refers to this policy may specify the start time. - * @param expiry - * A {@link Date} representing the expiration time for the access policy. If this value is - * null, any Shared Access Signature that refers to this policy must specify the expiry - * value. Resource access using a Shared Access Signature that refers to this policy after this time is - * not valid. - * @param permission - * A {@link String} containing the permissions specified for the access policy. - */ - public void addSignedIdentifier(String id, Date start, Date expiry, String permission) { - AccessPolicy accessPolicy = new AccessPolicy(); - accessPolicy.setStart(start); - accessPolicy.setExpiry(expiry); - accessPolicy.setPermission(permission); - - SignedIdentifier signedIdentifier = new SignedIdentifier(); - signedIdentifier.setId(id); - signedIdentifier.setAccessPolicy(accessPolicy); - - this.getSignedIdentifiers().add(signedIdentifier); - } - - /** - * A static inner class representing a collection of container-level access policies. A container may have up to - * five container-level access policies, which may be associated with any number of Shared Access Signatures. - */ - @XmlRootElement(name = "SignedIdentifiers") - public static class SignedIdentifiers { - private List signedIdentifiers = new ArrayList(); - - /** - * Gets the list of container-level access policies associated with this {@link SignedIdentifiers} instance. - * - * @return - * A {@link List} of {@link SignedIdentifier} instances containing container-level access policies. - */ - @XmlElement(name = "SignedIdentifier") - public List getSignedIdentifiers() { - return signedIdentifiers; - } - - /** - * Sets the list of container-level access policies associated with this {@link SignedIdentifiers} instance. - * - * @param signedIdentifiers - * A {@link List} of {@link SignedIdentifier} instances containing container-level access policies. - */ - public void setSignedIdentifiers(List signedIdentifiers) { - this.signedIdentifiers = signedIdentifiers; - } - } - - /** - * A static inner class representing a container-level access policy with a unique name. - */ - public static class SignedIdentifier { - private String id; - private AccessPolicy accessPolicy; - - /** - * Gets the name of the container-level access policy. The name may be up to 64 characters in - * length and must be unique within the container. - * - * @return - * A {@link String} containing the name for the access policy. - */ - @XmlElement(name = "Id") - public String getId() { - return id; - } - - /** - * Sets the name of the container-level access policy. The name may be up to 64 characters in - * length and must be unique within the container. - * - * @param id - * A {@link String} containing the name for the access policy. - * @return - * A reference to this {@link SignedIdentifier} instance. - */ - public SignedIdentifier setId(String id) { - this.id = id; - return this; - } - - /** - * Gets an {@link AccessPolicy} reference containing the start time, expiration time, and permissions associated - * with the container-level access policy. - * - * @return - * An {@link AccessPolicy} reference containing the start time, expiration time, and permissions - * associated with the access policy. - */ - @XmlElement(name = "AccessPolicy") - public AccessPolicy getAccessPolicy() { - return accessPolicy; - } - - /** - * Sets an {@link AccessPolicy} reference containing the start time, expiration time, and permissions to - * associate with the container-level access policy. - * - * @param accessPolicy - * An {@link AccessPolicy} reference containing the start time, expiration time, and permissions - * to associate with the access policy. - * @return - * A reference to this {@link SignedIdentifier} instance. - */ - public SignedIdentifier setAccessPolicy(AccessPolicy accessPolicy) { - this.accessPolicy = accessPolicy; - return this; - } - } - - /** - * An inner class representing the start time, expiration time, and permissions associated with an access policy. - */ - public static class AccessPolicy { - private Date start; - private Date expiry; - private String permission; - - /** - * Gets the start time for valid access to a resource using the access policy. If this value is - * null, the start time for any resource request using the access policy is assumed to be the time - * when the Blob service receives the request. - * - * @return - * A {@link Date} representing the start time for the access policy, or null if none is - * specified. - */ - @XmlElement(name = "Start") - @XmlJavaTypeAdapter(ContainerACLDateAdapter.class) - public Date getStart() { - return start; - } - - /** - * Sets the start time for valid access to a resource using the access policy. If this value is - * null, the start time for any resource request using the access policy is assumed to be the time - * when the Blob service receives the request. - * - * @param start - * A {@link Date} representing the start time for the access policy, or null to leave - * the time unspecified. - * @return - * A reference to this {@link AccessPolicy} instance. - */ - public AccessPolicy setStart(Date start) { - this.start = start; - return this; - } - - /** - * Gets the expiration time for valid access to a resource using the access policy. If this value is - * null, any Shared Access Signature that refers to this access policy must specify the expiry - * value. - * - * @return - * A {@link Date} representing the expiration time for the access policy, or null if none - * is specified. - */ - @XmlElement(name = "Expiry") - @XmlJavaTypeAdapter(ContainerACLDateAdapter.class) - public Date getExpiry() { - return expiry; - } - - /** - * Sets the expiration time for valid access to a resource using the access policy. If this value is - * null, any Shared Access Signature that refers to this access policy must specify the expiry - * value. - * - * @param expiry - * A {@link Date} representing the expiration time for the access policy, or null to - * leave the time unspecified. - * @return - * A reference to this {@link AccessPolicy} instance. - */ - public AccessPolicy setExpiry(Date expiry) { - this.expiry = expiry; - return this; - } - - /** - * Gets the permissions for operations on resources specified by the access policy. Supported permissions - * include read (r), write (w), delete (d), and list (l). Permissions may be grouped so as to allow multiple - * operations to be performed with the access policy. For example, if all permissions to a resource are granted, - * the method returns "rwdl" as the result. If only read/write permissions are granted, the method returns "rw" - * as the result. - * - * @return - * A {@link String} containing the permissions specified for the access policy. - */ - @XmlElement(name = "Permission") - public String getPermission() { - return permission; - } - - /** - * Sets the permissions for operations on resources specified by the access policy. Supported permissions - * include read (r), write (w), delete (d), and list (l). Permissions may be grouped so as to allow multiple - * operations to be performed with the access policy. For example, to grant all permissions to a resource, - * specify "rwdl" for the parameter. To grant only read/write permissions, specify "rw" for the parameter. - * - * @param permission - * A {@link String} containing the permissions specified for the access policy. - * @return - * A reference to this {@link AccessPolicy} instance. - */ - public AccessPolicy setPermission(String permission) { - this.permission = permission; - return this; - } - } - - /** - * An enumeration type for the public access levels that can be set on a blob container. - */ - public static enum PublicAccessType { - /** - * Access to this container and its blobs is restricted to calls made with the storage account private key. - */ - NONE, - /** - * Anonymous public read-only access is allowed for individual blobs within the container, but it is not - * possible to enumerate the blobs within the container or to enumerate the containers in the storage account. - */ - BLOBS_ONLY, - /** - * Anonymous public read-only access is allowed for individual blobs within the container, and the blobs within - * the container can be enumerated, but it is not possible to enumerate the containers in the storage account. - */ - CONTAINER_AND_BLOBS, - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobOptions.java deleted file mode 100644 index dd5524eaba212..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobOptions.java +++ /dev/null @@ -1,239 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#copyBlob(String, String, String, String, CopyBlobOptions) copyBlob} request. These options - * include an optional server timeout for the operation, an optional source snapshot timestamp value to copy from a - * particular snapshot of the source blob, blob metadata to set on the destination blob, a blob lease ID - * to overwrite a blob with an active lease, a source lease ID to copy from a source blob with an active lease, any - * access conditions to satisfy on the destination, and any access conditions to satisfy on the source. - */ -public class CopyBlobOptions extends BlobServiceOptions { - private String leaseId; - private AccessCondition accessCondition; - private String sourceLeaseId; - private String sourceSnapshot; - private HashMap metadata = new HashMap(); - private AccessCondition sourceAccessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link CopyBlobOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CopyBlobOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CopyBlobOptions} instance. - */ - @Override - public CopyBlobOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the source snapshot timestamp value set in this {@link CopyBlobOptions} instance. - * - * @return - * A {@link String} containing the snapshot timestamp value of the source blob snapshot to list. - */ - public String getSourceSnapshot() { - return sourceSnapshot; - } - - /** - * Sets the snapshot timestamp value used to identify the particular snapshot of the source blob to copy. The - * snapshot timestamp value is an opaque value returned by the server to identify a snapshot. When this option is - * set, the properties, metadata, and content of the snapshot are copied to the destination. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param sourceSnapshot - * A {@link String} containing the snapshot timestamp value of the source blob snapshot to list. - * @return - * A reference to this {@link ListBlobBlocksOptions} instance. - */ - public CopyBlobOptions setSourceSnapshot(String sourceSnapshot) { - this.sourceSnapshot = sourceSnapshot; - return this; - } - - /** - * Gets the blob metadata collection set in this {@link CopyBlobOptions} instance. - * - * @return - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata set, if any. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Sets the blob metadata collection to associate with the destination blob. Metadata is a collection of name-value - * {@link String} pairs for client use and is opaque to the server. Metadata names must adhere to the naming rules - * for C# identifiers. - *

- * Note that if any metadata is set with this option, no source blob metadata will be copied to the destination - * blob. - *

- * The metadata value only affects calls made on methods where this {@link CreateBlobOptions} instance is - * passed as a parameter. - * - * @param metadata - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CopyBlobOptions setMetadata(HashMap metadata) { - this.metadata = metadata; - return this; - } - - /** - * Adds a name-value pair to the blob metadata collection associated with this {@link CopyBlobOptions} instance. - *

- * Note that if any metadata is set with this option, no source blob metadata will be copied to the destination - * blob. - * - * @param key - * A {@link String} containing the name portion of the name-value pair to add to the metadata collection. - * @param value - * A {@link String} containing the value portion of the name-value pair to add to the metadata - * collection. - * @return - * A reference to this {@link CopyBlobOptions} instance. - */ - public CopyBlobOptions addMetadata(String key, String value) { - this.getMetadata().put(key, value); - return this; - } - - /** - * Gets the lease ID to match for the destination blob set in this {@link CopyBlobOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets a lease ID value to match on the destination blob. If set, there must be an active lease with a matching - * lease ID set on the destination blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link CopyBlobOptions} instance is passed as - * a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link CopyBlobOptions} instance. - */ - public CopyBlobOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the lease ID to match for the source blob set in this {@link CopyBlobOptions} instance. - * - * @return - * A {@link String} containing the source blob lease ID set, if any. - */ - public String getSourceLeaseId() { - return sourceLeaseId; - } - - /** - * Sets a lease ID value to match on the source blob. If set, there must be an active lease with a matching - * lease ID set on the source blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link CopyBlobOptions} instance is passed as - * a parameter. - * - * @param sourceLeaseId - * A {@link String} containing the source blob lease ID to set. - * @return - * A reference to this {@link CopyBlobOptions} instance. - */ - public CopyBlobOptions setSourceLeaseId(String sourceLeaseId) { - this.sourceLeaseId = sourceLeaseId; - return this; - } - - /** - * Gets the access conditions on the destination blob set in this {@link CopyBlobOptions} instance. - * - * @return - * An {@link AccessCondition} containing the destination blob access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets optional access conditions for the destination blob. The operation will return an error if the access - * conditions are not met. - *

- * Note that this value only affects calls made on methods where this {@link CopyBlobOptions} instance is passed as - * a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the destination blob access conditions to set. - * @return - * A reference to this {@link CopyBlobOptions} instance. - */ - public CopyBlobOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } - - /** - * Gets the access conditions on the source blob set in this {@link CopyBlobOptions} instance. - * - * @return - * An {@link AccessCondition} containing the source blob access conditions set, if any. - */ - public AccessCondition getSourceAccessCondition() { - return sourceAccessCondition; - } - - /** - * Sets optional access conditions for the source blob. The operation will return an error if the access - * conditions are not met. - *

- * Note that this value only affects calls made on methods where this {@link CopyBlobOptions} instance is passed as - * a parameter. - * - * @param sourceAccessCondition - * An {@link AccessCondition} containing the source blob access conditions to set. - * @return - * A reference to this {@link CopyBlobOptions} instance. - */ - public CopyBlobOptions setSourceAccessCondition(AccessCondition sourceAccessCondition) { - this.sourceAccessCondition = sourceAccessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobResult.java deleted file mode 100644 index 9d3395c2a722e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CopyBlobResult.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Copy Blob operation. This is returned by calls - * to implementations of {@link BlobContract#copyBlob(String, String, String, String, CopyBlobOptions)}. - *

- * See the Copy Blob documentation on - * MSDN for details of the underlying Blob Service REST API operation. - */ -public class CopyBlobResult { - private String etag; - private Date lastModified; - - /** - * Gets the ETag of the blob. - * - * @return - * A {@link String} containing the server-assigned ETag value for the copy blob. - */ - public String getEtag() { - return etag; - } - - /** - * Sets the ETag of the blob from the ETag header returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modified time of the blob. - *

- * - * @return - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Sets the last modified time of the blob from the Last-Modified header - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobBlockOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobBlockOptions.java deleted file mode 100644 index 24661cdbd6d5e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobBlockOptions.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#createBlobBlock(String, String, String, java.io.InputStream, CreateBlobBlockOptions) - * createBlobBlock} request. These options include an optional server timeout for the operation, the lease ID if the - * blob has an active lease, and the MD5 hash value for the block content. - */ -public class CreateBlobBlockOptions extends BlobServiceOptions { - private String leaseId; - private String contentMD5; - - /** - * Sets the optional server request timeout value associated with this {@link CreateBlobBlockOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CreateBlobBlockOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CreateBlobBlockOptions} instance. - */ - @Override - public CreateBlobBlockOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link CreateBlobBlockOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets a lease ID value to match when updating the blob. This value must match the lease ID set on a leased blob - * for an update to succeed. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobBlockOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link CreateBlobBlockOptions} instance. - */ - public CreateBlobBlockOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the MD5 hash value for the block content set in this {@link CreateBlobBlockOptions} instance. - * - * @return - * A {@link String} containing the MD5 hash value for the block content set, if any. - */ - public String getContentMD5() { - return contentMD5; - } - - /** - * Sets the optional MD5 hash value for the block content. This hash is used to verify the integrity of the blob - * during transport. When this value is specified, the storage service checks the hash of the content that has - * arrived with the one that was sent. If the two hashes do not match, the operation will fail with error code 400 - * (Bad Request), which will cause a ServiceException to be thrown. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobBlockOptions} instance is - * passed as a parameter. - * - * @param contentMD5 - * A {@link String} containing the MD5 hash value for the block content to set. - * @return - * A reference to this {@link CreateBlobBlockOptions} instance. - */ - public CreateBlobBlockOptions setContentMD5(String contentMD5) { - this.contentMD5 = contentMD5; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobOptions.java deleted file mode 100644 index 44e3e63090b45..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobOptions.java +++ /dev/null @@ -1,461 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#createPageBlob(String, String, long, CreateBlobOptions) createPageBlob} or - * {@link BlobContract#createBlockBlob(String, String, java.io.InputStream, CreateBlobOptions) createBlockBlob} request. - * These options include an optional server timeout for the operation, the MIME content type and content encoding for - * the blob, the content language, the MD5 hash, a cache control value, blob metadata, a blob lease ID, a sequence - * number, and access conditions. - */ -public class CreateBlobOptions extends BlobServiceOptions { - private String contentType; - private String contentEncoding; - private String contentLanguage; - private String contentMD5; - private String cacheControl; - private String blobContentType; - private String blobContentEncoding; - private String blobContentLanguage; - private String blobContentMD5; - private String blobCacheControl; - private HashMap metadata = new HashMap(); - private String leaseId; - private Long sequenceNumber; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link CreateBlobOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CreateBlobOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - @Override - public CreateBlobOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the Content-Type header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the Content-Type header value set, if any. - */ - public String getContentType() { - return contentType; - } - - /** - * Sets the optional Content-Type header value for the blob content. This value will be returned to - * clients in the headers of the response when the blob data or blob properties are requested. If no content type is - * specified, the default content type is application/octet-stream. - * - * @param contentType - * A {@link String} containing the Content-Type header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Gets the Content-Encoding header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the Content-Encoding header value set, if any. - */ - public String getContentEncoding() { - return contentEncoding; - } - - /** - * Sets the optional Content-Encoding header value for the blob content. Use this value to specify the - * content encodings applied to the blob. This value will be returned to clients in the headers of the response when - * the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param contentEncoding - * A {@link String} containing the Content-Encoding header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setContentEncoding(String contentEncoding) { - this.contentEncoding = contentEncoding; - return this; - } - - /** - * Gets the Content-Language header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the Content-Language header value set, if any. - */ - public String getContentLanguage() { - return contentLanguage; - } - - /** - * Sets the optional Content-Language header value for the blob content. Use this value to specify the - * content language of the blob. This value will be returned to clients in the headers of the response when the blob - * data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param contentLanguage - * A {@link String} containing the Content-Language header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setContentLanguage(String contentLanguage) { - this.contentLanguage = contentLanguage; - return this; - } - - /** - * Gets the Content-MD5 header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the Content-MD5 header value set, if any. - */ - public String getContentMD5() { - return contentMD5; - } - - /** - * Sets the optional Content-MD5 header value for the blob content. Use this value to specify an - * MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. When this - * header is specified, the storage service checks the hash that has arrived with the one that was sent. If the two - * hashes do not match, the operation will fail with error code 400 (Bad Request). This value will be returned to - * clients in the headers of the response when the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param contentMD5 - * A {@link String} containing the Content-MD5 header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setContentMD5(String contentMD5) { - this.contentMD5 = contentMD5; - return this; - } - - /** - * Gets the Cache-Control header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the Cache-Control header value set, if any. - */ - public String getCacheControl() { - return cacheControl; - } - - /** - * Sets the optional Cache-Control header value for the blob content. The Blob service stores this - * value but does not use or modify it. This value will be returned to clients in the headers of the response when - * the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param cacheControl - * A {@link String} containing the Cache-Control header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setCacheControl(String cacheControl) { - this.cacheControl = cacheControl; - return this; - } - - /** - * Gets the x-ms-blob-content-type header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the x-ms-blob-content-type header value set, if any. - */ - public String getBlobContentType() { - return blobContentType; - } - - /** - * Sets the optional x-ms-blob-content-type header value for the blob content. This value will be - * returned to clients in the headers of the response when the blob data or blob properties are requested. If no - * content type is specified, the default content type is application/octet-stream. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param blobContentType - * A {@link String} containing the x-ms-blob-content-type header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setBlobContentType(String blobContentType) { - this.blobContentType = blobContentType; - return this; - } - - /** - * Gets the x-ms-blob-content-encoding header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the x-ms-blob-content-encoding header value set, if any. - */ - public String getBlobContentEncoding() { - return blobContentEncoding; - } - - /** - * Sets the optional x-ms-blob-content-encoding header value for the blob content. Use this value to - * specify the content encodings applied to the blob. This value will be returned to clients in the headers of the - * response when the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param blobContentEncoding - * A {@link String} containing the x-ms-blob-content-encoding header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setBlobContentEncoding(String blobContentEncoding) { - this.blobContentEncoding = blobContentEncoding; - return this; - } - - /** - * Gets the x-ms-blob-content-language header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the x-ms-blob-content-language header value set, if any. - */ - public String getBlobContentLanguage() { - return blobContentLanguage; - } - - /** - * Sets the optional x-ms-blob-content-language header value for the blob content. Use this value to - * specify the content language of the blob. This value will be returned to clients in the headers of the response - * when the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param blobContentLanguage - * A {@link String} containing the x-ms-blob-content-language header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setBlobContentLanguage(String blobContentLanguage) { - this.blobContentLanguage = blobContentLanguage; - return this; - } - - /** - * Gets the x-ms-blob-content-md5 header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the x-ms-blob-content-md5 header value set, if any. - */ - public String getBlobContentMD5() { - return blobContentMD5; - } - - /** - * Sets the optional MD5 hash value for the blob content. This value will be returned to clients in the - * x-ms-blob-content-md5 header value of the response when the blob data or blob properties are - * requested. This hash is used to verify the integrity of the blob during transport. When this header is specified, - * the storage service checks the hash of the content that has arrived with the one that was sent. If the two hashes - * do not match, the operation will fail with error code 400 (Bad Request), which will cause a ServiceException to - * be thrown. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param blobContentMD5 - * A {@link String} containing the x-ms-blob-content-md5 header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setBlobContentMD5(String blobContentMD5) { - this.blobContentMD5 = blobContentMD5; - return this; - } - - /** - * Gets the x-ms-blob-cache-control header value set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the x-ms-blob-cache-control header value set, if any. - */ - public String getBlobCacheControl() { - return blobCacheControl; - } - - /** - * Sets the optional x-ms-blob-cache-control header value for the blob content. The Blob service stores - * this value but does not use or modify it. This value will be returned to clients in the headers of the response - * when the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param blobCacheControl - * A {@link String} containing the x-ms-blob-cache-control header value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setBlobCacheControl(String blobCacheControl) { - this.blobCacheControl = blobCacheControl; - return this; - } - - /** - * Gets the blob metadata collection set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata set, if any. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Sets the blob metadata collection to associate with the created blob. Metadata is a collection of name-value - * {@link String} pairs for client use and is opaque to the server. Metadata names must adhere to the naming rules - * for C# identifiers. - *

- * The metadata value only affects calls made on methods where this {@link CreateBlobOptions} instance is - * passed as a parameter. - * - * @param metadata - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setMetadata(HashMap metadata) { - this.metadata = metadata; - return this; - } - - /** - * Adds a name-value pair to the blob metadata collection associated with this {@link CreateBlobOptions} instance. - * - * @param key - * A {@link String} containing the name portion of the name-value pair to add to the metadata collection. - * @param value - * A {@link String} containing the value portion of the name-value pair to add to the metadata - * collection. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions addMetadata(String key, String value) { - this.getMetadata().put(key, value); - return this; - } - - /** - * Gets the lease ID for the blob set in this {@link CreateBlobOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets a lease ID value to match when updating the blob. This value is not used when creating a blob. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the sequence number set in this {@link CreateBlobOptions} instance. - * - * @return - * The page blob sequence number value set. - */ - public Long getSequenceNumber() { - return sequenceNumber; - } - - /** - * Sets the optional sequence number for a page blob in this {@link CreateBlobOptions} instance. This value is not - * used for block blobs. The sequence number is a user-controlled value that you can use to track requests. The - * value of the sequence number must be between 0 and 2^63 - 1. The default value is 0. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobOptions} instance is passed - * as a parameter. - * - * @param sequenceNumber - * The page blob sequence number value to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setSequenceNumber(Long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - return this; - } - - /** - * Gets the access conditions set in this {@link CreateBlobOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions for updating a blob. This value is not used when creating a blob. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link CreateBlobOptions} instance. - */ - public CreateBlobOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesOptions.java deleted file mode 100644 index 6d25af5908e74..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesOptions.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#createBlobPages(String, String, PageRange, long, java.io.InputStream, CreateBlobPagesOptions)} - * request. These options include an optional server timeout for the operation, a blob lease ID to create pages in a - * blob with an active lease, an optional MD5 hash for the content, and any access conditions to satisfy. - */ -public class CreateBlobPagesOptions extends BlobServiceOptions { - private String leaseId; - private String contentMD5; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link CreateBlobPagesOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CreateBlobPagesOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CreateBlobPagesOptions} instance. - */ - @Override - public CreateBlobPagesOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link CreateBlobPagesOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets an optional lease ID value to match when getting the blob. If set, the lease must be active and the value - * must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobPagesOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link CreateBlobPagesOptions} instance. - */ - public CreateBlobPagesOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the MD5 hash value for the page content set in this {@link CreateBlobPagesOptions} instance. - * - * @return - * A {@link String} containing the MD5 hash value for the block content set, if any. - */ - public String getContentMD5() { - return contentMD5; - } - - /** - * Sets the optional MD5 hash value for the page content. This hash is used to verify the integrity of the blob - * during transport. When this value is specified, the storage service checks the hash of the content that has - * arrived with the one that was sent. If the two hashes do not match, the operation will fail with error code 400 - * (Bad Request), which will cause a ServiceException to be thrown. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobPagesOptions} instance is - * passed as a parameter. - * - * @param contentMD5 - * A {@link String} containing the MD5 hash value for the block content to set. - * @return - * A reference to this {@link CreateBlobPagesOptions} instance. - */ - public CreateBlobPagesOptions setContentMD5(String contentMD5) { - this.contentMD5 = contentMD5; - return this; - } - - /** - * Gets the access conditions set in this {@link CreateBlobPagesOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets optional access conditions for getting the blob. The operation will return an error if the access conditions - * are not met. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobPagesOptions} instance is - * passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link CreateBlobPagesOptions} instance. - */ - public CreateBlobPagesOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesResult.java deleted file mode 100644 index 5c7711cc2500f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobPagesResult.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Put Page operation. This is returned by - * calls to implementations of {@link BlobContract#clearBlobPages(String, String, PageRange)}, - * {@link BlobContract#clearBlobPages(String, String, PageRange, CreateBlobPagesOptions)}, - * {@link BlobContract#createBlobPages(String, String, PageRange, long, java.io.InputStream)} and - * {@link BlobContract#createBlobPages(String, String, PageRange, long, java.io.InputStream, CreateBlobPagesOptions)}. - *

- * See the Put Page documentation on - * MSDN for details of the underlying Blob Service REST API operation. - */ -public class CreateBlobPagesResult { - private String etag; - private Date lastModified; - private String contentMD5; - private long sequenceNumber; - - /** - * Gets the ETag of the blob. - *

- * This value can be used in an access condition when updating or deleting a blob to prevent the client from - * modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the blob from the ETag element returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modified time of the blob. - *

- * Any operation that modifies the blob, including updates to the blob's metadata or properties, changes the last - * modified time of the blob. This value can be used in an access condition when updating or deleting a blob to - * prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the page blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the blob from the Last-Modified - * element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the MD5 hash value of the page blob. This value can be used to determine if the blob content has been - * corrupted in transmission. - * - * @return - * A {@link String} containing the MD5 hash value of the page blob. - */ - public String getContentMD5() { - return contentMD5; - } - - /** - * Reserved for internal use. Sets the MD5 hash value of the page blob from the Content-MD5 element - * returned in the response. - * - * @param contentMD5 - * A {@link String} containing the MD5 hash value of the page blob. - */ - public void setContentMD5(String contentMD5) { - this.contentMD5 = contentMD5; - } - - /** - * Gets the sequence number of the page blob. This value can be used when updating or deleting a page blob using an - * optimistic concurrency model to prevent the client from modifying data that has been changed by another - * client. - * - * @return - * A {@link String} containing the client-assigned sequence number value for the page blob. - */ - public long getSequenceNumber() { - return sequenceNumber; - } - - /** - * Reserved for internal use. Sets the sequence number of the page blob from the - * x-ms-blob-sequence-number element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param sequenceNumber - * A {@link String} containing the client-assigned sequence number value for the page blob. - */ - public void setSequenceNumber(long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobResult.java deleted file mode 100644 index 57a4c0faebce1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobResult.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Create Blob operation. This is returned by - * calls to implementations of {@link BlobContract#createPageBlob(String, String, long, CreateBlobOptions)} and - * {@link BlobContract#createBlockBlob(String, String, java.io.InputStream, CreateBlobOptions)}. - *

- * See the Put Blob documentation on - * MSDN for details of the underlying Blob Service REST API operation. - */ -public class CreateBlobResult { - private String etag; - private Date lastModified; - - /** - * Gets the ETag of the blob. - * - * @return - * A {@link String} containing the server-assigned ETag value for the snapshot. - */ - public String getEtag() { - return etag; - } - - /** - * Sets the ETag of the snapshot from the ETag header returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modified time of the snapshot. - * - * @return - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the snapshot from the Last-Modified header - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the snapshot. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotOptions.java deleted file mode 100644 index 76b41429f1c12..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotOptions.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#createBlobSnapshot(String, String, CreateBlobSnapshotOptions) createBlobSnapshot} request. These - * options include an optional server timeout for the operation, blob metadata to set on the snapshot, a blob lease ID - * to get a blob with an active lease, an optional start and end range for blob content to - * return, and any access conditions to satisfy. - */ -public class CreateBlobSnapshotOptions extends BlobServiceOptions { - private HashMap metadata = new HashMap(); - private String leaseId; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link CreateBlobSnapshotOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CreateBlobSnapshotOptions} - * instance is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CreateBlobSnapshotOptions} instance. - */ - @Override - public CreateBlobSnapshotOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the metadata collection set in this {@link CreateBlobSnapshotOptions} instance. - * - * @return - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata set, if any. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Sets the metadata collection to associate with a snapshot. Metadata is a collection of name-value {@link String} - * pairs for client use and is opaque to the server. Metadata names must adhere to the naming rules for C# identifiers. - *

- * The metadata value only affects calls made on methods where this {@link CreateBlobSnapshotOptions} - * instance is passed as a parameter. - * - * @param metadata - * A {@link java.util.HashMap} of name-value pairs of {@link String} containing the names and values of - * the metadata to set. - * @return - * A reference to this {@link CreateBlobSnapshotOptions} instance. - */ - public CreateBlobSnapshotOptions setMetadata(HashMap metadata) { - this.metadata = metadata; - return this; - } - - /** - * Adds a name-value pair to the metadata collection associated with this {@link CreateBlobSnapshotOptions} - * instance. - * - * @param key - * A {@link String} containing the name portion of the name-value pair to add to the metadata collection. - * @param value - * A {@link String} containing the value portion of the name-value pair to add to the metadata - * collection. - * @return - * A reference to this {@link CreateBlobSnapshotOptions} instance. - */ - public CreateBlobSnapshotOptions addMetadata(String key, String value) { - this.getMetadata().put(key, value); - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link CreateBlobSnapshotOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets an optional lease ID value to match when creating a snapshot of the blob. If set, the lease must be active - * and the value must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobSnapshotOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link CreateBlobSnapshotOptions} instance. - */ - public CreateBlobSnapshotOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the access conditions set in this {@link CreateBlobSnapshotOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets optional access conditions for creating a snapshot of the blob. The operation will return an error if the - * access conditions are not met. - *

- * Note that this value only affects calls made on methods where this {@link CreateBlobSnapshotOptions} instance is - * passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link CreateBlobSnapshotOptions} instance. - */ - public CreateBlobSnapshotOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotResult.java deleted file mode 100644 index a35964af62d6e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateBlobSnapshotResult.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Snapshot Blob operation. This is returned by - * calls to implementations of {@link BlobContract#createBlobSnapshot(String, String)} and - * {@link BlobContract#createBlobSnapshot(String, String, CreateBlobSnapshotOptions)}. - *

- * See the Snapshot Blob documentation - * on MSDN for details of the underlying Blob Service REST API operation. - */ -public class CreateBlobSnapshotResult { - private String snapshot; - private String etag; - private Date lastModified; - - /** - * Gets the snapshot timestamp value returned by the server to uniquely identify the newly created snapshot. - *

- * The snapshot timestamp value is an opaque value returned by the server to uniquely identify a snapshot version, - * and may be used in subsequent requests to access the snapshot. - *

- * - * @return - * A {@link String} containing the snapshot timestamp value of the newly created snapshot. - */ - public String getSnapshot() { - return snapshot; - } - - /** - * Reserved for internal use. Sets the snapshot timestamp value from the x-ms-snapshot header - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp value of the newly created snapshot. - */ - public void setSnapshot(String snapshot) { - this.snapshot = snapshot; - } - - /** - * Gets the ETag of the snapshot. - *

- * Note that a snapshot cannot be written to, so the ETag of a given snapshot will never change. However, the ETag - * of the snapshot will differ from that of the base blob if new metadata was supplied with the create blob snapshot - * request. If no metadata was specified with the request, the ETag of the snapshot will be identical to that of the - * base blob at the time the snapshot was taken. - * - * @return - * A {@link String} containing the server-assigned ETag value for the snapshot. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the snapshot from the ETag header returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modified time of the snapshot. - *

- * Note that a snapshot cannot be written to, so the last modified time of a given snapshot will never change. - * However, the last modified time of the snapshot will differ from that of the base blob if new metadata was - * supplied with the create blob snapshot request. If no metadata was specified with the request, the last modified - * time of the snapshot will be identical to that of the base blob at the time the snapshot was taken. - * - * @return - * A {@link java.util.Date} containing the last modified time of the snapshot. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the snapshot from the Last-Modified header - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the snapshot. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateContainerOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateContainerOptions.java deleted file mode 100644 index 42bc57b029fdf..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/CreateContainerOptions.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a {@link BlobContract#createContainer(String, CreateContainerOptions) - * createContainer} request. These options include a server response timeout for the request, metadata to set on the - * container, and the public access level for container and blob data. Options that are not set will not be passed to - * the server with a request. - */ -public class CreateContainerOptions extends BlobServiceOptions { - private String publicAccess; - private HashMap metadata = new HashMap(); - - /** - * Sets the server request timeout value associated with this {@link CreateContainerOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CreateContainerOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CreateContainerOptions} instance. - */ - @Override - public CreateContainerOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the metadata collection associated with this {@link CreateContainerOptions} instance. - * - * @return - * A {@link java.util.HashMap} of name-value pairs of {@link String} containing the names and values of - * the container metadata to set. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Sets the metadata collection associated with this {@link CreateContainerOptions} instance. Metadata is a - * collection of name-value {@link String} pairs for client use and is opaque to the server. Metadata names must - * adhere to the naming rules for C# - * identifiers. - *

- * The metadata value only affects calls made on methods where this {@link CreateContainerOptions} instance - * is passed as a parameter. - * - * @param metadata - * A {@link java.util.HashMap} of name-value pairs of {@link String} containing the names and values of - * the container metadata to set. - * @return - * A reference to this {@link CreateContainerOptions} instance. - */ - public CreateContainerOptions setMetadata(HashMap metadata) { - this.metadata = metadata; - return this; - } - - /** - * Adds a metadata name-value pair to the metadata collection associated with this {@link CreateContainerOptions} - * instance. - * - * @param key - * A {@link String} containing the name portion of the name-value pair to add to the metadata collection. - * @param value - * A {@link String} containing the value portion of the name-value pair to add to the metadata - * collection. - * @return - * A reference to this {@link CreateContainerOptions} instance. - */ - public CreateContainerOptions addMetadata(String key, String value) { - this.getMetadata().put(key, value); - return this; - } - - /** - * Gets the public access level value associated with this {@link CreateContainerOptions} instance. The public - * access level specifies whether data in the container may be accessed publicly and the level of access. Possible - * values include: - *

    - *
  • container  Specifies full public read access for container and blob data. Clients can - * enumerate blobs within the container via anonymous request, but cannot enumerate containers within the storage - * account.
  • - *
  • blob  Specifies public read access for blobs. Blob data within this container can be read - * via anonymous request, but container data is not available. Clients cannot enumerate blobs within the container - * via anonymous request.
  • - *
- * The default value of null sets the container data private to the storage account owner. - * - * @return - * A {@link String} containing the public access level value to set, or null. - */ - public String getPublicAccess() { - return publicAccess; - } - - /** - * Sets the public access level value associated with this {@link CreateContainerOptions} instance. The public - * access level specifies whether data in the container may be accessed publicly and the level of access. Possible - * values include: - *
    - *
  • container  Specifies full public read access for container and blob data. Clients can - * enumerate blobs within the container via anonymous request, but cannot enumerate containers within the storage - * account.
  • - *
  • blob  Specifies public read access for blobs. Blob data within this container can be read - * via anonymous request, but container data is not available. Clients cannot enumerate blobs within the container - * via anonymous request.
  • - *
- * The default value of null sets the container data private to the storage account owner. - *

- * The publicAccess value only affects calls made on methods where this {@link CreateContainerOptions} - * instance is passed as a parameter. - * - * @param publicAccess - * A {@link String} containing the public access level value to set, or null to set the - * container data private to the storage account owner. - * @return - * A reference to this {@link CreateContainerOptions} instance. - */ - public CreateContainerOptions setPublicAccess(String publicAccess) { - this.publicAccess = publicAccess; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteBlobOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteBlobOptions.java deleted file mode 100644 index 281f0d14979b4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteBlobOptions.java +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Represents the options that may be set on a {@link BlobContract#deleteBlob(String, String, DeleteBlobOptions) - * deleteBlob} request. These options include an optional server timeout for the operation, a snapshot timestamp to - * specify an individual snapshot to delete, a blob lease ID to delete a blob with an active lease, a flag indicating - * whether to delete all snapshots but not the blob, or both the blob and all snapshots, and any access conditions to - * satisfy. - */ -public class DeleteBlobOptions extends BlobServiceOptions { - private String snapshot; - private String leaseId; - private Boolean deleteSnaphotsOnly; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link DeleteBlobOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link DeleteBlobOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link DeleteBlobOptions} instance. - */ - @Override - public DeleteBlobOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the snapshot timestamp value set in this {@link DeleteBlobOptions} instance. - * - * @return - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get. - */ - public String getSnapshot() { - return snapshot; - } - - /** - * Reserved for future use. Sets an optional snapshot timestamp value used to identify the particular snapshot of - * the blob to delete. - *

- * The snapshot timestamp value is an opaque value returned by the server to identify a snapshot. This option cannot - * be set if the delete snapshots only option is set to true or false. - *

- * Note that this value only affects calls made on methods where this {@link DeleteBlobOptions} instance is passed - * as a parameter. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get. - * @return - * A reference to this {@link DeleteBlobOptions} instance. - */ - public DeleteBlobOptions setSnapshot(String snapshot) { - this.snapshot = snapshot; - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link DeleteBlobOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets an optional lease ID value to match when deleting the blob. If set, the lease must be active and the value - * must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link DeleteBlobOptions} instance is passed - * as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link DeleteBlobOptions} instance. - */ - public DeleteBlobOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the flag indicating whether to delete only snapshots of the blob, or both the blob and all its snapshots set - * in this {@link DeleteBlobOptions} instance. - * - * @return - * A value of true to delete only the snapshots, or false to delete both snapshots - * and the blob. When the value null is set, x-ms-delete-snapshots in the header will not be - * set. - */ - public Boolean getDeleteSnaphotsOnly() { - return deleteSnaphotsOnly; - } - - /** - * Sets a flag indicating whether to delete only snapshots of the blob, or both the blob and all its snapshots. - *

- * If the deleteSnaphotsOnly parameter is set to true, only the snapshots of the blob are - * deleted by the operation. If the parameter is set to false, both the blob and all its snapshots are - * deleted by the operation. If this option is not set on a request, and the blob has associated snapshots, the Blob - * service returns a 409 (Conflict) status code and a {@link ServiceException} is thrown. - *

- * This option is not compatible with the snapshot option; if both are set the Blob service returns status code 400 - * (Bad Request) and a {@link StorageException} is thrown. - *

- * Note that this value only affects calls made on methods where this {@link DeleteBlobOptions} instance is passed - * as a parameter. - * - * @param deleteSnaphotsOnly - * Set to true to delete only the snapshots, or false to delete both snapshots - * and the blob. - * @return - * A reference to this {@link DeleteBlobOptions} instance. - */ - public DeleteBlobOptions setDeleteSnaphotsOnly(boolean deleteSnaphotsOnly) { - this.deleteSnaphotsOnly = deleteSnaphotsOnly; - return this; - } - - /** - * Gets the access conditions set in this {@link DeleteBlobOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets optional access conditions for getting the blob. The operation will return an error if the access conditions - * are not met. - *

- * Note that this value only affects calls made on methods where this {@link DeleteBlobOptions} instance is passed - * as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link DeleteBlobOptions} instance. - */ - public DeleteBlobOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteContainerOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteContainerOptions.java deleted file mode 100644 index 64bf97b199a5a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/DeleteContainerOptions.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a {@link BlobContract#deleteContainer(String, DeleteContainerOptions) - * deleteContainer} request. These options include a server response timeout for the request and access conditions that - * specify whether to perform the operation or not depending on the values of the Etag or last modified time of the - * container. Options that are not set will not be passed to the server with a request. - */ -public class DeleteContainerOptions extends BlobServiceOptions { - private AccessCondition accessCondition; - - /** - * Sets the server request timeout value associated with this {@link DeleteContainerOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link DeleteContainerOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link DeleteContainerOptions} instance. - */ - @Override - public DeleteContainerOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the access conditions associated with this {@link DeleteContainerOptions} instance. - * - * @return - * An {@link AccessCondition} reference containing the Etag and last modified time conditions for performing - * the delete container operation, or null if not set. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions associated with this {@link DeleteContainerOptions} instance. By default, the delete - * container operation will delete the container unconditionally. Use this method to specify conditions on the Etag - * or last modified time value for performing the delete container operation. - *

- * The accessCondition value only affects calls made on methods where this {@link DeleteContainerOptions} - * instance is passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} reference containing the Etag and last modified time conditions for - * performing the delete container operation. Specify null to make the operation - * unconditional. - * @return - * A reference to this {@link DeleteContainerOptions} instance. - */ - public DeleteContainerOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataOptions.java deleted file mode 100644 index 4471ddf1a3f50..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataOptions.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#getBlobMetadata(String, String, GetBlobMetadataOptions) getBlobMetadata} request. - * These options include an optional server timeout for the operation, the lease ID if the blob has an active lease, the - * snapshot timestamp to get the properties of a snapshot, and any access conditions for the request. - */ -public class GetBlobMetadataOptions extends BlobServiceOptions { - private String snapshot; - private String leaseId; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link GetBlobMetadataOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link GetBlobMetadataOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link GetBlobMetadataOptions} instance. - */ - @Override - public GetBlobMetadataOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the snapshot timestamp value set in this {@link GetBlobMetadataOptions} instance. - * - * @return - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get metadata for. - */ - public String getSnapshot() { - return snapshot; - } - - /** - * Sets the snapshot timestamp value used to identify the particular snapshot of the blob to get metadata for. The - * snapshot timestamp value is an opaque value returned by the server to identify a snapshot. When this option is - * set, only the metadata of the snapshot is returned. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobMetadataOptions} instance is - * passed as a parameter. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get metadata for. - * @return - * A reference to this {@link GetBlobMetadataOptions} instance. - */ - public GetBlobMetadataOptions setSnapshot(String snapshot) { - this.snapshot = snapshot; - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link GetBlobMetadataOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets a lease ID value to match when getting the metadata of the blob. If set, the lease must be active and the - * value must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobMetadataOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link GetBlobMetadataOptions} instance. - */ - public GetBlobMetadataOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the access conditions set in this {@link GetBlobMetadataOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions for getting the metadata of the blob. The operation will return an error if the - * access conditions are not met. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link GetBlobMetadataOptions} instance. - */ - public GetBlobMetadataOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataResult.java deleted file mode 100644 index 272547f5d7e0c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobMetadataResult.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Get Blob Metadata operation. This is - * returned by calls to implementations of {@link BlobContract#getBlobMetadata(String, String)} and - * {@link BlobContract#getBlobMetadata(String, String, GetBlobMetadataOptions)}. - *

- * See the Get Blob Metadata - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -public class GetBlobMetadataResult { - private String etag; - private Date lastModified; - private HashMap metadata; - - /** - * Gets the ETag of the blob. For block blobs, this value is returned only if the blob has committed blocks. - *

- * This value can be used in an access condition when updating or deleting a blob to prevent the client from - * modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the blob from the ETag header returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modified time of the block blob. For block blobs, this value is returned only if the blob has - * committed blocks. - *

- * Any operation that modifies the blob, including updates to the blob's metadata or properties, changes the last - * modified time of the blob. This value can be used in an access condition when updating or deleting a blob to - * prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the blob from the Last-Modified header - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the user-defined blob metadata as a map of name and value pairs. The metadata is for client use and is - * opaque to the server. - * - * @return - * A {@link java.util.HashMap} of name-value pairs of {@link String} containing the names and values of - * the blob metadata. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. Sets the blob metadata from the x-ms-meta-name:value headers - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param metadata - * A {@link java.util.HashMap} of name-value pairs of {@link String} containing the names and values - * of the blob metadata. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobOptions.java deleted file mode 100644 index eb944c04f1d93..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobOptions.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.core.ServiceException; - -/** - * Represents the options that may be set on a {@link BlobContract#getBlob(String, String, GetBlobOptions) getBlob} - * request. These options include an optional server timeout for the operation, a snapshot timestamp to specify a - * snapshot, a blob lease ID to get a blob with an active lease, an optional start and end range for blob content to - * return, and any access conditions to satisfy. - */ -public class GetBlobOptions extends BlobServiceOptions { - private String snapshot; - private String leaseId; - private boolean computeRangeMD5; - private Long rangeStart; - private Long rangeEnd; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link GetBlobOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link GetBlobOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link GetBlobOptions} instance. - */ - @Override - public GetBlobOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the snapshot timestamp value set in this {@link GetBlobOptions} instance. - * - * @return - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get. - */ - public String getSnapshot() { - return snapshot; - } - - /** - * Sets an optional snapshot timestamp value used to identify the particular snapshot of the blob to get properties, - * metadata, and content for. The snapshot timestamp value is an opaque value returned by the server to identify a - * snapshot. When this option is set, only the properties, metadata, and content of the snapshot are returned. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobOptions} instance is passed as a - * parameter. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get. - * @return - * A reference to this {@link GetBlobOptions} instance. - */ - public GetBlobOptions setSnapshot(String snapshot) { - this.snapshot = snapshot; - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link GetBlobOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets an optional lease ID value to match when getting the blob. If set, the lease must be active and the value - * must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobOptions} instance is passed as a - * parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link GetBlobOptions} instance. - */ - public GetBlobOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Reserved for future use. Gets a flag indicating whether to return an MD5 hash for the specified range of blob - * content set in this {@link GetBlobOptions} instance. - * - * @return - * A flag value of true to get the MD5 hash value for the specified range, otherwise - * false. - */ - public boolean isComputeRangeMD5() { - return computeRangeMD5; - } - - /** - * Reserved for future use. Sets a flag indicating whether to return an MD5 hash for the specified range of blob - * content. - *

- * When the computeRangeMD5 parameter is set to true and specified together with a range less - * than or equal to 4 MB in size, the get blob operation response includes the MD5 hash for the range. If the - * computeRangeMD5 parameter is set to true and no range is specified or the range exceeds 4 - * MB in size, a {@link ServiceException} is thrown. - * - * @param computeRangeMD5 - * Reserved for future use. Set a flag value of true to get the MD5 hash value for the - * specified range, otherwise false. - * @return - * A reference to this {@link GetBlobOptions} instance. - */ - public GetBlobOptions setComputeRangeMD5(boolean computeRangeMD5) { - this.computeRangeMD5 = computeRangeMD5; - return this; - } - - /** - * Gets the beginning byte offset value of the blob content range to return set in this {@link GetBlobOptions} - * instance. - * - * @return - * The beginning offset value in bytes for the blob content range to return. - */ - public Long getRangeStart() { - return rangeStart; - } - - /** - * Sets an optional beginning byte offset value of the blob content range to return for the request, inclusive. - *

- * When this value is set, the blob content beginning at the byte offset specified by the rangeStart value - * and ending at the range end value, inclusive, is returned in the server response to the get blob operation. If - * the range end is not set, the response includes blob content from the rangeStart value to the end of the - * blob. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobOptions} instance is passed as a - * parameter. - * - * @param rangeStart - * The beginning offset value in bytes for the blob content range to return, inclusive. - * @return - * A reference to this {@link GetBlobOptions} instance. - */ - public GetBlobOptions setRangeStart(Long rangeStart) { - this.rangeStart = rangeStart; - return this; - } - - /** - * Gets the ending byte offset value for the blob content range to return set in this {@link GetBlobOptions} - * instance. - * - * @return - * The ending offset value in bytes for the blob content range to return. - */ - public Long getRangeEnd() { - return rangeEnd; - } - - /** - * Sets an optional ending byte offset value of the blob content range to return for the request, inclusive. - *

- * If the range start is not set, this value is ignored and the response includes content from the entire blob. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobOptions} instance is passed as a - * parameter. - * - * @param rangeEnd - * The ending offset value in bytes for the blob content range to return, inclusive. - * @return - * A reference to this {@link GetBlobOptions} instance. - */ - public GetBlobOptions setRangeEnd(Long rangeEnd) { - this.rangeEnd = rangeEnd; - return this; - } - - /** - * Gets the access conditions set in this {@link GetBlobOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets optional access conditions for getting the blob. The operation will return an error if the access conditions - * are not met. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobOptions} instance is passed as a - * parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link GetBlobOptions} instance. - */ - public GetBlobOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesOptions.java deleted file mode 100644 index 6d1c433ca5fd8..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesOptions.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#getBlobProperties(String, String, GetBlobPropertiesOptions) getBlobProperties} request. - * These options include an optional server timeout for the operation, the lease ID if the blob has an active lease, the - * snapshot timestamp to get the properties of a snapshot, and any access conditions for the request. - */ -public class GetBlobPropertiesOptions extends BlobServiceOptions { - private String snapshot; - private String leaseId; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link GetBlobPropertiesOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link GetBlobPropertiesOptions} - * instance is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link GetBlobPropertiesOptions} instance. - */ - @Override - public GetBlobPropertiesOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the snapshot timestamp value set in this {@link GetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get properties for. - */ - public String getSnapshot() { - return snapshot; - } - - /** - * Sets the snapshot timestamp value used to identify the particular snapshot of the blob to get properties for. The - * snapshot timestamp value is an opaque value returned by the server to identify a snapshot. When this option is - * set, only the properties of the snapshot are returned. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get properties for. - * @return - * A reference to this {@link GetBlobPropertiesOptions} instance. - */ - public GetBlobPropertiesOptions setSnapshot(String snapshot) { - this.snapshot = snapshot; - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link GetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets a lease ID value to match when getting the properties of the blob. If set, the lease must be active and the - * value must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link GetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link GetBlobPropertiesOptions} instance. - */ - public GetBlobPropertiesOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the access conditions set in this {@link GetBlobPropertiesOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions for getting the properties of the blob. The operation will return an error if the - * access conditions are not met. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link GetBlobPropertiesOptions} instance. - */ - public GetBlobPropertiesOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesResult.java deleted file mode 100644 index 6bc1830d487d4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobPropertiesResult.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Get Blob Properties operation. This is - * returned by calls to implementations of {@link BlobContract#getBlobProperties(String, String)} and - * {@link BlobContract#getBlobProperties(String, String, GetBlobPropertiesOptions)}. - *

- * See the Get Blob Properties - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -public class GetBlobPropertiesResult { - private BlobProperties properties; - private HashMap metadata = new HashMap(); - - /** - * Gets the standard HTTP properties and system properties of the blob. - * - * @return - * A {@link BlobProperties} instance containing the properties of the blob. - */ - public BlobProperties getProperties() { - return properties; - } - - /** - * Reserved for internal use. Sets the blob properties from the headers returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param properties - * A {@link BlobProperties} instance containing the properties of the blob. - */ - public void setProperties(BlobProperties properties) { - this.properties = properties; - } - - /** - * Gets the user-defined blob metadata as a map of name and value pairs. The metadata is for client use and is - * opaque to the server. - * - * @return - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values of - * the blob metadata. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. Sets the blob metadata from the x-ms-meta-name:value headers - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param metadata - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values - * of the blob metadata. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobResult.java deleted file mode 100644 index 850d509f48eb7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetBlobResult.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.io.InputStream; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Get Blob operation. This is returned by calls - * to implementations of {@link BlobContract#getBlob(String, String, GetBlobOptions)}. - *

- * See the Get Blob documentation on - * MSDN for details of the underlying Blob Service REST API operation. - */ -public class GetBlobResult { - private InputStream contentStream; - private BlobProperties properties; - private HashMap metadata; - - /** - * Gets the content of the blob. - * - * @return - * An {@link InputStream} instance containing the content of the blob. - */ - public InputStream getContentStream() { - return contentStream; - } - - /** - * Reserved for internal use. Sets the blob content from the body returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param contentStream - * An {@link InputStream} instance containing the content of the blob. - */ - public void setContentStream(InputStream contentStream) { - this.contentStream = contentStream; - } - - /** - * Gets the standard HTTP properties and system properties of the blob. - * - * @return - * A {@link BlobProperties} instance containing the properties of the blob. - */ - public BlobProperties getProperties() { - return properties; - } - - /** - * Reserved for internal use. Sets the blob properties from the headers returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param properties - * A {@link BlobProperties} instance containing the properties of the blob. - */ - public void setProperties(BlobProperties properties) { - this.properties = properties; - } - - /** - * Gets the user-defined blob metadata as a map of name and value pairs. The metadata is for client use and is - * opaque to the server. - * - * @return - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values of - * the blob metadata. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. Sets the blob metadata from the x-ms-meta-name:value headers - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param metadata - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values - * of the blob metadata. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerACLResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerACLResult.java deleted file mode 100644 index 68d2f677f1cd2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerACLResult.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Get Container ACL operation. This is returned - * by calls to implementations of {@link BlobContract#getContainerACL(String)} and - * {@link BlobContract#getContainerACL(String, BlobServiceOptions)}. - *

- * See the Get Container ACL - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -public class GetContainerACLResult { - private ContainerACL containerACL; - - /** - * Gets the container's public access level and container-level access policies from the headers and body returned - * in the response. - * - * @return - * A {@link ContainerACL} instance representing the public access level and container-level access policies - * returned by the request. - */ - public ContainerACL getContainerACL() { - return containerACL; - } - - /** - * Reserved for internal use. Sets the container's public access level and container-level access policies from the - * headers and body returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param containerACL - * A {@link ContainerACL} instance representing the public access level and container-level access - * policies returned by the request. - */ - public void setValue(ContainerACL containerACL) { - this.containerACL = containerACL; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerPropertiesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerPropertiesResult.java deleted file mode 100644 index 09dbc31e85fe4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetContainerPropertiesResult.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Get Container Properties and Get Container - * Metadata operations. This is returned by - * calls to implementations of {@link BlobContract#getContainerProperties(String)}, - * {@link BlobContract#getContainerProperties(String, BlobServiceOptions)}, - * {@link BlobContract#getContainerMetadata(String)}, and - * {@link BlobContract#getContainerMetadata(String, BlobServiceOptions)}. - *

- * See the Get Container Properties and - * Get Container Metadata documentation - * on MSDN for details of the underlying Blob Service REST API operations. - */ -public class GetContainerPropertiesResult { - private String etag; - private Date lastModified; - private HashMap metadata; - - /** - * Gets the Etag of the container. This value can be used when updating or deleting a container using an optimistic - * concurrency model to prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned Etag value for the container. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the Etag of the container from the ETag header returned in - * the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned Etag value for the container. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modifed time of the container. This value can be used when updating or deleting a container using - * an optimistic concurrency model to prevent the client from modifying data that has been changed by another - * client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the container. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the container from the Last-Modified - * header returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the container. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the container metadata as a map of name and value pairs. The container metadata is for client use and is - * opaque to the server. - * - * @return - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values of - * the container metadata. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. Sets the container metadata from the x-ms-meta-name headers - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param metadata - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values - * of the container metadata. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetServicePropertiesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetServicePropertiesResult.java deleted file mode 100644 index a37e55400a08f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/GetServicePropertiesResult.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the service properties returned in response to Blob Service REST API operations. This is - * returned by calls to implementations of {@link BlobContract#getServiceProperties()} and - * {@link BlobContract#getServiceProperties(BlobServiceOptions)}. - *

- * See the Get Blob Service Properties - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -public class GetServicePropertiesResult { - private ServiceProperties value; - - /** - * Gets a {@link ServiceProperties} instance containing the service property values associated with the storage - * account. - *

- * Modifying the values in the {@link ServiceProperties} instance returned does not affect the values associated - * with the storage account. To change the values in the storage account, call the - * {@link BlobContract#setServiceProperties} method and pass the modified {@link ServiceProperties} instance as a - * parameter. - * - * @return - * A {@link ServiceProperties} instance containing the property values associated with the storage account. - */ - public ServiceProperties getValue() { - return value; - } - - /** - * Reserved for internal use. Sets the value of the {@link ServiceProperties} instance associated with a - * storage service call result. This method is invoked by the API to store service properties returned by - * a call to a REST operation and is not intended for public use. - * - * @param value - * A {@link ServiceProperties} instance containing the property values associated with the storage - * account. - */ - public void setValue(ServiceProperties value) { - this.value = value; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksOptions.java deleted file mode 100644 index ddd560c352a94..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksOptions.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#listBlobBlocks(String, String, ListBlobBlocksOptions) listBlobBlocks} request. These options - * include an optional server timeout for the operation, the lease ID if the blob has an active lease, the snapshot - * timestamp to get the committed blocks of a snapshot, whether to return the committed block list, and whether to - * return the uncommitted block list. - */ -public class ListBlobBlocksOptions extends BlobServiceOptions { - private String leaseId; - private String snapshot; - private boolean committedList; - private boolean uncommittedList; - - /** - * Sets the optional server request timeout value associated with this {@link ListBlobBlocksOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link ListBlobBlocksOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link ListBlobBlocksOptions} instance. - */ - @Override - public ListBlobBlocksOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link ListBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets a lease ID value to match when listing the blocks of the blob. If set, the lease must be active and the - * value must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link ListBlobBlocksOptions} instance. - */ - public ListBlobBlocksOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the snapshot timestamp value set in this {@link ListBlobBlocksOptions} instance. - * - * @return - * A {@link String} containing the snapshot timestamp value of the blob snapshot to list. - */ - public String getSnapshot() { - return snapshot; - } - - /** - * Sets the snapshot timestamp value used to identify the particular snapshot of the blob to list blocks for. The - * snapshot timestamp value is an opaque value returned by the server to identify a snapshot. When this option is - * set, only the list of committed blocks of the snapshot is returned. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp value of the blob snapshot to list. - * @return - * A reference to this {@link ListBlobBlocksOptions} instance. - */ - public ListBlobBlocksOptions setSnapshot(String snapshot) { - this.snapshot = snapshot; - return this; - } - - /** - * Gets the flag value indicating whether to return the committed blocks of the blob set in this - * {@link ListBlobBlocksOptions} instance. - * - * @return - * A boolean flag value indicating whether to return the committed blocks of the blob. - */ - public boolean isCommittedList() { - return committedList; - } - - /** - * Sets a flag indicating whether to return the committed blocks of the blob in the response to the list blob blocks - * request. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param committedList - * Set to true to return the committed blocks of the blob; otherwise, false. - * @return - * A reference to this {@link ListBlobBlocksOptions} instance. - */ - public ListBlobBlocksOptions setCommittedList(boolean committedList) { - this.committedList = committedList; - return this; - } - - /** - * Gets the flag value indicating whether to return the uncommitted blocks of the blob set in this - * {@link ListBlobBlocksOptions} instance. - * - * @return - * A boolean flag value indicating whether to return the uncommitted blocks of the blob. - */ - public boolean isUncommittedList() { - return uncommittedList; - } - - /** - * Sets a flag indicating whether to return the uncommitted blocks of the blob in the response to the list blob - * blocks request. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobBlocksOptions} instance is - * passed as a parameter. - * - * @param uncommittedList - * Set to true to return the uncommitted blocks of the blob; otherwise, false. - * @return - * A reference to this {@link ListBlobBlocksOptions} instance. - */ - public ListBlobBlocksOptions setUncommittedList(boolean uncommittedList) { - this.uncommittedList = uncommittedList; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksResult.java deleted file mode 100644 index 9dc09239113b9..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobBlocksResult.java +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.core.utils.pipeline.Base64StringAdapter; - -/** - * A wrapper class for the response returned from a Blob Service REST API Get Block List operation. This is returned by - * calls to implementations of {@link BlobContract#listBlobBlocks(String, String)} and - * {@link BlobContract#listBlobBlocks(String, String, ListBlobBlocksOptions)}. - *

- * See the Get Block List documentation - * on MSDN for details of the underlying Blob Service REST API operation. - */ -@XmlRootElement(name = "BlockList") -public class ListBlobBlocksResult { - private Date lastModified; - private String etag; - private String contentType; - private long contentLength; - private List committedBlocks = new ArrayList(); - private List uncommittedBlocks = new ArrayList(); - - /** - * Gets the last modified time of the block blob. This value is returned only if the blob has committed blocks. - *

- * Any operation that modifies the blob, including updates to the blob's metadata or properties, changes the last - * modified time of the blob. This value can be used in an access condition when updating or deleting a blob to - * prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the blob from the Last-Modified - * header returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the ETag of the blob. This value is returned only if the blob has committed blocks. - *

- * This value can be used in an access condition when updating or deleting a blob to prevent the client from - * modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the blob from the ETag header returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the MIME content type of the blob. This value defaults to application/xml. - * - * @return - * A {@link String} containing the MIME content type value for the blob. - */ - public String getContentType() { - return contentType; - } - - /** - * Reserved for internal use. Sets the MIME content type of the blob from the Content-Type header - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param contentType - * A {@link String} containing the MIME content type value for the blob. - */ - public void setContentType(String contentType) { - this.contentType = contentType; - } - - /** - * Gets the size of the blob in bytes. For blobs with no committed blocks, this value is 0. - * - * @return - * The size of the blob in bytes. - */ - public long getContentLength() { - return contentLength; - } - - /** - * Reserved for internal use. Sets the content length of the blob from the x-ms-blob-content-length - * header returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param contentLength - * The size of the blob in bytes. - */ - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - /** - * Gets a list of the committed blocks of the blob. This list may be empty if no blocks have been committed or if - * committed blocks were not specified in the request. - * - * @return - * A {@link List} of {@link Entry} instances representing the committed blocks of the blob. - */ - @XmlElementWrapper(name = "CommittedBlocks") - @XmlElement(name = "Block") - public List getCommittedBlocks() { - return committedBlocks; - } - - /** - * Reserved for internal use. Sets the list of the committed blocks of the blob from the Block - * elements in the CommittedBlocks element of the BlockList element in the - * response body returned by the server. - * - * @param committedBlocks - * A {@link List} of {@link Entry} instances representing the committed blocks of the blob. - */ - public void setCommittedBlocks(List committedBlocks) { - this.committedBlocks = committedBlocks; - } - - /** - * Gets a list of the uncommitted blocks of the blob. This list may be empty if no uncommitted blocks are associated - * with the blob, or if uncommitted blocks were not specified in the {@link ListBlobBlocksOptions options} parameter - * of the request. - * - * @return - * A {@link List} of {@link Entry} instances representing the uncommitted blocks of the blob. - */ - @XmlElementWrapper(name = "UncommittedBlocks") - @XmlElement(name = "Block") - public List getUncommittedBlocks() { - return uncommittedBlocks; - } - - /** - * Reserved for internal use. Sets the list of the uncommitted blocks of the blob from the Block - * elements in the UncommittedBlocks element of the BlockList element in the - * response body returned by the server. - * - * @param uncommittedBlocks - * A {@link List} of {@link Entry} instances representing the uncommitted blocks of the blob. - */ - public void setUncommittedBlocks(List uncommittedBlocks) { - this.uncommittedBlocks = uncommittedBlocks; - } - - /** - * The class for an entry in a list of blocks, representing a committed or uncommitted block. - */ - public static class Entry { - private String blockId; - private long blockLength; - - /** - * Gets the client-specified block ID for a block list entry. - * - * @return - * A {@link String} containing the client-specified block ID for a block. - */ - @XmlElement(name = "Name") - @XmlJavaTypeAdapter(Base64StringAdapter.class) - public String getBlockId() { - return blockId; - } - - /** - * Reserved for internal use. Sets the client-specified block ID for a block list entry from the - * Name element in the Block element in the list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param blockId - * A {@link String} containing the client-specified block ID for the block. - */ - public void setBlockId(String blockId) { - this.blockId = blockId; - } - - /** - * Gets the length in bytes of a block list entry. - * - * @return - * The length of the block in bytes. - */ - @XmlElement(name = "Size") - public long getBlockLength() { - return blockLength; - } - - /** - * Reserved for internal use. Sets the length in bytes of a block list entry from the Size - * element in the Block element in the list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param blockLength - * The length of the block in bytes. - */ - public void setBlockLength(long blockLength) { - this.blockLength = blockLength; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsOptions.java deleted file mode 100644 index a16c5a6be5d82..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsOptions.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#listBlobRegions(String, String, ListBlobRegionsOptions) listBlobRegions} request. - * These options include an optional server timeout for the operation, the lease ID if the blob has an active lease, the - * snapshot timestamp to get the valid page ranges of a snapshot, the start offset and/or end offset to use to narrow - * the returned valid page range results, and any access conditions for the request. - */ -public class ListBlobRegionsOptions extends BlobServiceOptions { - private String leaseId; - private String snapshot; - private Long rangeStart; - private Long rangeEnd; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link ListBlobRegionsOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link ListBlobRegionsOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link ListBlobRegionsOptions} instance. - */ - @Override - public ListBlobRegionsOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link ListBlobRegionsOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets an optional lease ID value to match when getting the valid page ranges of the blob. If set, the lease must - * be active and the value must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobRegionsOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link ListBlobRegionsOptions} instance. - */ - public ListBlobRegionsOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the snapshot timestamp value set in this {@link ListBlobRegionsOptions} instance. - * - * @return - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get valid page ranges - * for. - */ - public String getSnapshot() { - return snapshot; - } - - /** - * Sets an optional snapshot timestamp value used to identify the particular snapshot of the blob to get valid page - * ranges for. The snapshot timestamp value is an opaque value returned by the server to identify a snapshot. When - * this option is set, only the valid page ranges of the snapshot are returned. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobRegionsOptions} instance is - * passed as a parameter. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp value of the blob snapshot to get valid page ranges - * for. - * @return - * A reference to this {@link ListBlobRegionsOptions} instance. - */ - public ListBlobRegionsOptions setSnapshot(String snapshot) { - this.snapshot = snapshot; - return this; - } - - /** - * Gets the beginning byte offset value of the valid page ranges to return set in this - * {@link ListBlobRegionsOptions} instance. - * - * @return - * The beginning offset value in bytes for the valid page ranges to return. - */ - public Long getRangeStart() { - return rangeStart; - } - - /** - * Sets an optional beginning byte offset value of the valid page ranges to return for the request, inclusive. - *

- * If the range end is not set, the response includes valid page ranges from the rangeStart value to the - * end of the blob. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobRegionsOptions} instance is - * passed as a parameter. - * - * @param rangeStart - * The beginning offset value in bytes for the valid page ranges to return, inclusive. - * @return - * A reference to this {@link ListBlobRegionsOptions} instance. - */ - public ListBlobRegionsOptions setRangeStart(Long rangeStart) { - this.rangeStart = rangeStart; - return this; - } - - /** - * Gets the ending byte offset value for the valid page ranges to return set in this {@link ListBlobRegionsOptions} - * instance. - * - * @return - * The ending offset value in bytes for the valid page ranges to return. - */ - public Long getRangeEnd() { - return rangeEnd; - } - - /** - * Sets an optional ending byte offset value of the valid page ranges to return for the request, inclusive. - *

- * If the range start is not set, this value is ignored and the response includes valid page ranges from the entire - * blob. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobRegionsOptions} instance is - * passed as a parameter. - * - * @param rangeEnd - * The ending offset value in bytes for the valid page ranges to return, inclusive. - * @return - * A reference to this {@link ListBlobRegionsOptions} instance. - */ - public ListBlobRegionsOptions setRangeEnd(Long rangeEnd) { - this.rangeEnd = rangeEnd; - return this; - } - - /** - * Gets the access conditions set in this {@link ListBlobRegionsOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets optional access conditions for getting the valid page ranges of the blob. The operation will return an error - * if the access conditions are not met. - *

- * Note that this value only affects calls made on methods where this {@link ListBlobRegionsOptions} instance is - * passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link ListBlobRegionsOptions} instance. - */ - public ListBlobRegionsOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsResult.java deleted file mode 100644 index a9b3fff40103f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobRegionsResult.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Get Page Ranges operation. This is returned by - * calls to implementations of {@link BlobContract#listBlobRegions(String, String, ListBlobRegionsOptions)}. - *

- * See the Get Page Ranges - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -@XmlRootElement(name = "PageList") -public class ListBlobRegionsResult { - private Date lastModified; - private String etag; - private long contentLength; - private List pageRanges; - - /** - * Gets the last modified time of the blob. - *

- * Any operation that modifies the blob, including updates to the blob's metadata or properties, changes the last - * modified time of the blob. This value can be used in an access condition when updating or deleting a blob to - * prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the blob from the Last-Modified header - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the ETag of the blob. - *

- * This value can be used in an access condition when updating or deleting a blob to prevent the client from - * modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the blob from the ETag header returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the size of the blob in bytes. - * - * @return - * The size of the blob in bytes. - */ - public long getContentLength() { - return contentLength; - } - - /** - * Reserved for internal use. Sets the content length of the blob from the x-ms-blob-content-length - * header returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param contentLength - * The size of the blob in bytes. - */ - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - /** - * Gets the list of non-overlapping valid page ranges in the blob that match the parameters of the request, sorted - * by increasing address page range. - * - * @return - * A {@link List} of {@link PageRange} instances containing the valid page ranges for the blob. - */ - @XmlElement(name = "PageRange") - public List getPageRanges() { - return pageRanges; - } - - /** - * Reserved for internal use. Sets the list of valid page ranges in the blob that match the parameters of the - * request from the PageRange elements of the PageList element returned by the - * server in the response body. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param pageRanges - * A {@link List} of {@link PageRange} instances containing the valid page ranges for the blob. - */ - public void setPageRanges(List pageRanges) { - this.pageRanges = pageRanges; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsOptions.java deleted file mode 100644 index 091d829076765..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsOptions.java +++ /dev/null @@ -1,290 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.core.ServiceException; - -/** - * Represents the options that may be set on a {@link BlobContract#listBlobs(String, ListBlobsOptions)} request. These - * options include a server response timeout for the request, a prefix for blobs to match, a marker to - * continue a list operation, a maximum number of results to return with one list operation, a delimiter for - * structuring virtual blob hierarchies, and whether to include blob metadata, blob snapshots, and uncommitted blobs - * in the results. - */ -public class ListBlobsOptions extends BlobServiceOptions { - private String prefix; - private String marker; - private int maxResults; - private String delimiter; - private boolean includeMetadata; - private boolean includeSnapshots; - private boolean includeUncommittedBlobs; - - /** - * Sets the optional server request timeout value associated with this {@link ListBlobsOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link ListBlobsOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link ListBlobsOptions} instance. - */ - @Override - public ListBlobsOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the prefix filter associated with this {@link ListBlobsOptions} instance. This value is used to return only - * blobs beginning with the prefix from the container in methods where this {@link ListBlobsOptions} instance is - * passed as a parameter. - * - * @return - * A {@link String} containing the prefix used to filter the blob names returned, if any. - */ - public String getPrefix() { - return prefix; - } - - /** - * Sets the optional blob name prefix filter value to use in a request. If this value is set, the server will return - * only blob names that match the prefix value in the response. - *

- * The prefix value only affects calls made on methods where this {@link ListBlobsOptions} instance is - * passed as a parameter. - * - * @param prefix - * A {@link String} containing a prefix to use to filter the blob names returned. - */ - public ListBlobsOptions setPrefix(String prefix) { - this.prefix = prefix; - return this; - } - - /** - * Gets the marker value set in this {@link ListBlobsOptions} instance. If this value is set, the server will return - * blob names beginning at the specified marker in the response. - * - * @return - * A {@link String} containing the marker value to use to specify the beginning of the request results, if - * any. - */ - public String getMarker() { - return marker; - } - - /** - * Sets the optional marker value to use in a request. If this value is set, the server will return blob names - * beginning at the specified marker in the response. Leave this value unset for an initial request. - *

- * The List Blobs operation returns a marker value in a NextMarker element if the blob list - * returned is not complete. The marker value may then be used in a subsequent call to request the next set of blob - * list items. The marker value is opaque to the client. - *

- * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method on a {@link ListBlobsResult} instance to get - * the marker value to set on a {@link ListBlobsOptions} instance using a call to this method. Pass the - * {@link ListBlobsOptions} instance as a parameter to a {@link BlobContract#listBlobs(String, ListBlobsOptions)} - * call to get the next portion of the blob list. - *

- * The marker value only affects calls made on methods where this {@link ListBlobsOptions} instance is - * passed as a parameter. - * - * @param marker - * A {@link String} containing the marker value to use to specify the beginning of the request results. - * @return - * A reference to this {@link ListBlobsOptions} instance. - */ - public ListBlobsOptions setMarker(String marker) { - this.marker = marker; - return this; - } - - /** - * Gets the value of the maximum number of results to return set in this {@link ListBlobsOptions} instance. - * - * @return - * The maximum number of results to return. If the value is zero, the server will return up to 5,000 items. - */ - public int getMaxResults() { - return maxResults; - } - - /** - * Sets the optional maximum number of results to return for a request. If this value is set, the server will return - * up to this number of blob and blob prefix results in the response. If a value is not specified, or a value - * greater than 5,000 is specified, the server will return up to 5,000 items. - *

- * If there are more blobs and blob prefixes that can be returned than this maximum, the server returns a marker - * value in a NextMarker element in the response. The marker value may then be used in a subsequent - * call to request the next set of blob list items. The marker value is opaque to the client. - *

- * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method on a {@link ListBlobsResult} instance to get - * the marker value to set on a {@link ListBlobsOptions} instance using a call to - * {@link ListBlobsOptions#setMarker(String)}. Pass the {@link ListBlobsOptions} instance as a parameter to a - * {@link BlobContract#listBlobs(String, ListBlobsOptions)} call to get the next portion of the blob list. - *

- * The maxResults value only affects calls made on methods where this {@link ListBlobsOptions} instance is - * passed as a parameter. - * - * @param maxResults - * The maximum number of results to return. - * @return - * A reference to this {@link ListBlobsOptions} instance. - */ - public ListBlobsOptions setMaxResults(int maxResults) { - this.maxResults = maxResults; - return this; - } - - /** - * Gets the value of the delimiter to use for grouping virtual blob hierarchy set in this {@link ListBlobsOptions} - * instance. - * - * @return - * A {@link String} containing the delimiter value, if any. - */ - public String getDelimiter() { - return delimiter; - } - - /** - * Sets the value of the optional delimiter to use for grouping in a virtual blob hierarchy. - *

- * When the request includes this optional parameter, the operation returns a blob prefix in a - * BlobPrefix element in the response that acts as a placeholder for all blobs whose names begin - * with the same substring up to the appearance of the delimiter character. The delimiter may be a single character - * or a string. - *

- * The delimiter parameter enables the caller to traverse the blob namespace by using a user-configured - * delimiter. In this way, you can traverse a virtual hierarchy of blobs as though it were a file system. The - * delimiter is a string that may be one or more characters long. When the request includes this parameter, the - * operation response includes one BlobPrefix element for each set of blobs whose names begin with - * a common substring up to the first appearance of the delimiter string that comes after any prefix specified for - * the request. The value of the BlobPrefix element is substring+delimiter, where - * substring is the common substring that begins one or more blob names, and delimiter is - * the value of the delimiter parameter. - *

- * The BlobPrefix elements in the response are accessed with the - * {@link ListBlobsResult#getBlobPrefixes()} method. You can use each value in the list returned to make a list - * blobs request for the blobs that begin with that blob prefix value, by specifying the value as the prefix option - * with a call to the {@link ListBlobsOptions#setPrefix(String) setPrefix} method on a {@link ListBlobsOptions} - * instance passed as a parameter to the request. - *

- * Note that each blob prefix returned in the response counts toward the maximum number of blob results, just as - * each blob does. - *

- * Note that if a delimiter is set, you cannot include snapshots. A request that includes both returns an - * InvalidQueryParameter error (HTTP status code 400 - Bad Request), which causes a {@link ServiceException} to be - * thrown. - *

- * The delimiter value only affects calls made on methods where this {@link ListBlobsOptions} instance is - * passed as a parameter. - * - * @param delimiter - * A {@link String} containing the delimiter value to use for grouping virtual blob hierarchy. - * @return - * A reference to this {@link ListBlobsOptions} instance. - */ - public ListBlobsOptions setDelimiter(String delimiter) { - this.delimiter = delimiter; - return this; - } - - /** - * Gets the value of a flag indicating whether to include blob metadata with a response set in this - * {@link ListBlobsOptions} instance. - * - * @return - * A value of true to include blob metadata with a response, otherwise, false. - */ - public boolean isIncludeMetadata() { - return includeMetadata; - } - - /** - * Sets the value of an optional flag indicating whether to include blob metadata with a response. - * - * @param includeMetadata - * Set a value of true to include blob metadata with a response, otherwise, - * false. - * @return - * A reference to this {@link ListBlobsOptions} instance. - */ - public ListBlobsOptions setIncludeMetadata(boolean includeMetadata) { - this.includeMetadata = includeMetadata; - return this; - } - - /** - * Gets the value of a flag indicating whether to include blob snapshots with a response set in this - * {@link ListBlobsOptions} instance. - * - * @return - * A value of true to include blob metadata with a response, otherwise, false. - */ - public boolean isIncludeSnapshots() { - return includeSnapshots; - } - - /** - * Sets the value of an optional flag indicating whether to include blob snapshots with a response. - *

- * Note that if this flag is set, you cannot set a delimiter. A request that includes both returns an - * InvalidQueryParameter error (HTTP status code 400 - Bad Request), which causes a {@link ServiceException} to be - * thrown. - * - * @param includeSnapshots - * Set a value of true to include blob metadata with a response, otherwise, - * false. - * @return - * A reference to this {@link ListBlobsOptions} instance. - */ - public ListBlobsOptions setIncludeSnapshots(boolean includeSnapshots) { - this.includeSnapshots = includeSnapshots; - return this; - } - - /** - * Gets the value of a flag indicating whether to include uncommitted blobs with a response set in this - * {@link ListBlobsOptions} instance. - * - * @return - * A value of true to include uncommitted blobs with a response, otherwise, false. - */ - public boolean isIncludeUncommittedBlobs() { - return includeUncommittedBlobs; - } - - /** - * Sets the value of an optional flag indicating whether to include uncommitted blobs with a response. Uncommitted - * blobs are blobs for which blocks have been uploaded, but which have not been committed with a request to - * {@link BlobContract#commitBlobBlocks(String, String, BlockList)} or - * {@link BlobContract#commitBlobBlocks(String, String, BlockList, CommitBlobBlocksOptions)}. - * - * @param includeUncommittedBlobs - * Set a value of true to include uncommitted blobs with a response, otherwise, - * false. - * @return - * A reference to this {@link ListBlobsOptions} instance. - */ - public ListBlobsOptions setIncludeUncommittedBlobs(boolean includeUncommittedBlobs) { - this.includeUncommittedBlobs = includeUncommittedBlobs; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsResult.java deleted file mode 100644 index fb55ed889d725..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListBlobsResult.java +++ /dev/null @@ -1,524 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.blob.implementation.MetadataAdapter; - -/** - * A wrapper class for the response returned from a Blob Service REST API List Blobs operation. This is returned by - * calls to implementations of {@link BlobContract#listBlobs(String)} and - * {@link BlobContract#listBlobs(String, ListBlobsOptions)}. - *

- * See the List Blobs documentation on - * MSDN for details of the underlying Blob Service REST API operation. - */ -@XmlRootElement(name = "EnumerationResults") -public class ListBlobsResult { - private List blobPrefixes = new ArrayList(); - private List blobs = new ArrayList(); - private String containerName; - private String prefix; - private String marker; - private String nextMarker; - private String delimiter; - private int maxResults; - - /** - * Gets the list of ListBlobsEntry entries generated from the server response to the list blobs - * request. - * - * @return - * The {@link List} of {@link ListBlobsEntry} entries generated from the server response to the list blobs - * request. - */ - @XmlElementWrapper(name = "Blobs") - @XmlElementRefs({ @XmlElementRef(name = "BlobPrefix", type = BlobPrefixEntry.class), - @XmlElementRef(name = "Blob", type = BlobEntry.class) }) - public List getEntries() { - ArrayList result = new ArrayList(); - result.addAll(this.blobPrefixes); - result.addAll(this.blobs); - return result; - } - - /** - * Sets the lists of blob entries and blob prefix entries from a common list of ListBlobsEntry entries - * generated from the server response to the list blobs request. - * - * @param entries - * The {@link List} of {@link ListBlobsEntry} entries to set the lists of blob entries and blob prefix - * entries from. - */ - public void setEntries(List entries) { - // Split collection into "blobs" and "blobPrefixes" collections - this.blobPrefixes = new ArrayList(); - this.blobs = new ArrayList(); - - for (ListBlobsEntry entry : entries) { - if (entry instanceof BlobPrefixEntry) { - this.blobPrefixes.add((BlobPrefixEntry) entry); - } - else if (entry instanceof BlobEntry) { - this.blobs.add((BlobEntry) entry); - } - } - } - - /** - * Gets the list of blob prefix entries that satisfied the request. Each BlobPrefixEntry represents one - * or more blobs that have a common substring up to the delimiter specified in the request options. - *

- * This list may contain only a portion of the blob prefix entries that satisfy the request, limited by a server - * timeout or a maximum results parameter. If there are more blob entries and blob prefix entries that could satisfy - * the result, the server returns a NextMarker element with the response. - *

- * The delimiter option enables the caller to traverse the blob namespace by using a user-configured delimiter. In - * this way, you can traverse a virtual hierarchy of blobs as though it were a file system. The delimiter may be a - * single character or a string. When the request includes the delimiter option, the response includes a - * BlobPrefixEntry in place of all blobs whose names begin with the same substring up to the appearance - * of the delimiter string. The value of {@link BlobPrefixEntry#getName()} is substring+ delimiter - * , where substring is the common substring that begins one or more blob names, and delimiter is - * the value of the delimiter option. - *

- * To move down a level in the virtual hierarchy, you can use the {@link BlobPrefixEntry#getName()} method to get - * the prefix value to use to make a subsequent call to list blobs that begin with this prefix. - *

- * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to get this value and pass it as a marker - * option to a subsequent list blobs request to get the next set of blob results. - *

- * Blobs are listed in alphabetical order in the response body, with upper-case letters listed first. - * - * @return - * A {@link List} of {@link BlobEntry} instances for the blobs that satisfied the request. - */ - public List getBlobPrefixes() { - return this.blobPrefixes; - } - - /** - * Gets the list of blobs that satisfied the request from the response. This list may contain only a portion of the - * blobs that satisfy the request, limited by a server timeout or a maximum results parameter. If there are more - * blobs or blob prefixes that could satisfy the result, the server returns a NextMarker element - * with the response. - *

- * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to get this value and pass it as a marker - * option to a subsequent list blobs request to get the next set of blob results. - *

- * Blobs are listed in alphabetical order in the response body, with upper-case letters listed first. - * - * @return - * A {@link List} of {@link BlobEntry} instances for the blobs that satisfied the request. - */ - public List getBlobs() { - return this.blobs; - } - - /** - * Gets the value of the filter used to return only blobs beginning with the prefix. This value is not set if a - * prefix was not specified in the list blobs request. - * - * @return - * A {@link String} containing the prefix used to filter the blob names returned, if any. - */ - @XmlElement(name = "Prefix") - public String getPrefix() { - return prefix; - } - - /** - * Reserved for internal use. Sets the filter used to return only blobs beginning with the prefix from the - * Prefix element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param prefix - * A {@link String} containing the prefix used to filter the blob names returned, if any. - */ - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - /** - * Gets the value of the marker that was used to specify the beginning of the container list to return with the - * request. This value is not set if a marker was not specified in the request. - *

- * The list blobs operation returns a marker value in a NextMarker element if the blob list - * returned is not complete. The marker value may then be used in a subsequent call to request the next set of blob - * list items. The marker value is opaque to the client. - *

- * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to get the marker value to set on a - * {@link ListBlobsOptions} instance using a call to {@link ListBlobsOptions#setMarker(String)}. Pass the - * {@link ListBlobsOptions} instance as a parameter to a {@link BlobContract#listBlobs(String, ListBlobsOptions) - * listBlobs} call to get the next portion of the blob list. - * - * @return - * A {@link String} containing the marker used to specify the beginning of the blob list returned, if any. - */ - @XmlElement(name = "Marker") - public String getMarker() { - return marker; - } - - /** - * Reserved for internal use. Sets the marker used to specify the beginning of the blob list to return from the - * Marker element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param marker - * A {@link String} containing the marker used to specify the beginning of the blob list returned. - */ - public void setMarker(String marker) { - this.marker = marker; - } - - /** - * Gets the next marker value needed to specify the beginning of the next portion of the blob list to return, if any - * was set in the response from the server. - *

- * The list blobs operation returns a marker value in a NextMarker element if the blob list - * returned is not complete. The marker value may then be used in a subsequent call to request the next set of blob - * list items. The marker value is opaque to the client. - *

- * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to get the marker value to set on a - * {@link ListBlobsOptions} instance using a call to {@link ListBlobsOptions#setMarker(String)}. Pass the - * {@link ListBlobsOptions} instance as a parameter to a {@link BlobContract#listBlobs(String, ListBlobsOptions) - * listBlobs} call to get the next portion of the blob list. - * - * @return - * A {@link String} containing the next marker value needed to specify the beginning of the next portion - * of the blob list to return, if any was set in the response from the server. - */ - @XmlElement(name = "NextMarker") - public String getNextMarker() { - return nextMarker; - } - - /** - * Reserved for internal use. Sets the next marker value needed to specify the beginning of the next portion of the - * blob list to return from the NextMarker element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param nextMarker - * A {@link String} containing the next marker value needed to specify the beginning of the next portion - * of the blob list to return. - */ - public void setNextMarker(String nextMarker) { - this.nextMarker = nextMarker; - } - - /** - * Gets the maximum results to return used to generate the response, if present. The number of entries returned in - * the response will not exceed this number, including all BlobPrefix elements. This value is not - * set if a maximum number was not specified in the request. If the request does not specify this parameter or - * specifies a value greater than 5,000, the server will return up to 5,000 items. If there are more blobs or blob - * prefixes that satisfy the request than this maximum value, the server will include a next marker value in the - * response, which can be used to get the remaining blobs with a subsequent request. - *

- * Use the {@link ListBlobsResult#getNextMarker() getNextMarker} method to get the marker value to set on a - * {@link ListBlobsOptions} instance using a call to {@link ListBlobsOptions#setMarker(String)}. Pass the - * {@link ListBlobsOptions} instance as a parameter to a {@link BlobContract#listBlobs(String, ListBlobsOptions) - * listBlobs} call to get the next portion of the blob list. - * - * @return - * The maximum results to return value in the response, if any. - */ - @XmlElement(name = "MaxResults") - public int getMaxResults() { - return maxResults; - } - - /** - * Reserved for internal use. Sets the maximum results to return value from the MaxResults element - * of the EnumerationResults element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param maxResults - * The maximum results to return value in the response, if any. - */ - public void setMaxResults(int maxResults) { - this.maxResults = maxResults; - } - - /** - * Gets the delimiter value used to generate the response, if present. When the request includes this parameter, the - * operation returns BlobPrefix elements in the response body that act as a placeholder for all - * blobs whose names begin with the same substring up to the appearance of the delimiter character. - * - * @return - * A {@link String} containing the delimiter value used as a request parameter. - */ - @XmlElement(name = "Delimiter") - public String getDelimiter() { - return delimiter; - } - - /** - * Reserved for internal use. Sets the delimiter value from the Delimiter element of the - * EnumerationResults element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param delimiter - * A {@link String} containing the delimiter value in the response, if any. - */ - public void setDelimiter(String delimiter) { - this.delimiter = delimiter; - } - - /** - * Gets the container URI. This value is returned in the ContainerName attribute of the - * EnumerationResults element returned in the response. - * - * @return - * A {@link String} containing the container URI. - */ - @XmlAttribute(name = "ContainerName") - public String getContainerName() { - return containerName; - } - - /** - * Reserved for internal use. Sets the container URI value from the ContainerName attribute of the - * EnumerationResults element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param containerName - * A {@link String} containing the container URI. - */ - public void setContainerName(String containerName) { - this.containerName = containerName; - } - - /** - * The abstract base class for Blob and BlobPrefix entries in the list of results returned - * in the response. - */ - public static abstract class ListBlobsEntry { - - } - - /** - * Represents a BlobPrefix element returned in the response. When the request includes a delimiter - * parameter, a single BlobPrefix element is returned in place of all blobs whose names begin with - * the same substring up to the appearance of the delimiter character. - */ - @XmlRootElement(name = "BlobPrefix") - public static class BlobPrefixEntry extends ListBlobsEntry { - private String name; - - /** - * Gets the value of the Name element within a BlobPrefix element returned in - * the response. The value of the element is substring+delimiter, where substring is - * the common substring that begins one or more blob names, and delimiter is the value of the delimiter - * parameter. - * - * @return - * A {@link String} containing the common substring that begins one or more blob names up to and - * including the delimiter specified in the request. - */ - @XmlElement(name = "Name") - public String getName() { - return name; - } - - /** - * Reserved for internal use. Sets the blob prefix name from the Name element in the - * BlobPrefix element in the Blobs list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param name - * A {@link String} containing the value of the Name element within a - * BlobPrefix element. - */ - public void setName(String name) { - this.name = name; - } - } - - /** - * Represents a Blob element returned in the response. A BlobEntry includes - * committed blobs, and can optionally include blob metadata, blob snapshots, and uncommitted blobs, depending on - * the request options set. - */ - @XmlRootElement(name = "Blob") - public static class BlobEntry extends ListBlobsEntry { - private String name; - private String url; - private String snapshot; - private HashMap metadata = new HashMap(); - private BlobProperties properties; - - /** - * Gets the value of the Name element within a Blob element returned in - * the response. The value of the element is the complete name of the blob, including any virtual hierarchy. - * - * @return - * A {@link String} containing the complete blob name. - */ - @XmlElement(name = "Name") - public String getName() { - return name; - } - - /** - * Reserved for internal use. Sets the blob name from the Name element in the - * Blob element in the Blobs list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param name - * A {@link String} containing the value of the Name element within a - * Blob element. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Gets the value of the Url element within a Blob element returned in - * the response. The value of the element is the complete URI address of the blob, including any virtual - * hierarchy. - * - * @return - * A {@link String} containing the complete URI address of the blob. - */ - @XmlElement(name = "Url") - public String getUrl() { - return url; - } - - /** - * Reserved for internal use. Sets the blob URI address from the Uri element in the - * Blob element in the Blobs list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param url - * A {@link String} containing the complete URI address of the blob. - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * Gets a {@link BlobProperties} instance with the blob properties returned in the response. - * - * @return - * A {@link BlobProperties} instance with the blob properties returned in the response. - */ - @XmlElement(name = "Properties") - public BlobProperties getProperties() { - return properties; - } - - /** - * Reserved for internal use. Sets the blob properties from the Uri element in the - * Blob element in the Blobs list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param properties - * A {@link BlobProperties} instance with the blob properties returned in the response. - */ - public void setProperties(BlobProperties properties) { - this.properties = properties; - } - - /** - * Gets the snapshot timestamp value for a blob snapshot returned in the response. The value is set from the - * Snapshot element in the Blob element in the Blobs list in - * the response. Snapshots are included in the enumeration only if specified in the request options. Snapshots - * are listed from oldest to newest in the response. - * - * @return - * A {@link String} containing the snapshot timestamp of the blob snapshot. - */ - @XmlElement(name = "Snapshot") - public String getSnapshot() { - return snapshot; - } - - /** - * Reserved for internal use. Sets the blob snapshot timestamp from the Snapshot element in the - * Blob element in the Blobs list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param snapshot - * A {@link String} containing the snapshot timestamp of the blob snapshot. - */ - public void setSnapshot(String snapshot) { - this.snapshot = snapshot; - } - - /** - * Gets the blob's metadata collection set in the Metadata element in the Blob - * element in the Blobs list in the response. Metadata is included in the enumeration only if - * specified in the request options. - * - * @return - * A {@link HashMap} of name-value pairs of {@link String} containing the blob metadata set, if any. - */ - @XmlElement(name = "Metadata") - @XmlJavaTypeAdapter(MetadataAdapter.class) - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. Sets the blob metadata from the Metadata element in the - * Blob element in the Blobs list in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param metadata - * A {@link java.util.HashMap} of name-value pairs of {@link String} containing the names and values - * of the blob metadata, if present. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersOptions.java deleted file mode 100644 index d1dcb76c3fd34..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersOptions.java +++ /dev/null @@ -1,176 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a {@link BlobContract#listContainers(ListContainersOptions) listContainers} - * request. These options include a server response timeout for the request, a container name prefix filter, a marker - * for continuing requests, the maximum number of results to return in a request, and whether to include container - * metadata in the results. Options that are not set will not be passed to the server with a request. - */ -public class ListContainersOptions extends BlobServiceOptions { - private String prefix; - private String marker; - private int maxResults; - private boolean includeMetadata; - - /** - * Sets the optional server request timeout value associated with this {@link ListContainersOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link ListContainersOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link ListContainersOptions} instance. - */ - @Override - public ListContainersOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the container name prefix filter value set in this {@link ListContainersOptions} instance. - * - * @return - * A {@link String} containing the container name prefix value, if any. - */ - public String getPrefix() { - return prefix; - } - - /** - * Sets the optional container name prefix filter value to use in a request. If this value is set, the server will - * return only container names that match the prefix value in the response. - *

- * The prefix value only affects calls made on methods where this {@link ListContainersOptions} instance is - * passed as a parameter. - * - * @param prefix - * A {@link String} containing the container name prefix value to use to filter the request results. - * @return - * A reference to this {@link ListContainersOptions} instance. - */ - public ListContainersOptions setPrefix(String prefix) { - this.prefix = prefix; - return this; - } - - /** - * Gets the marker value set in this {@link ListContainersOptions} instance. - * - * @return - * A {@link String} containing the marker value to use to specify the beginning of the request results. - */ - public String getMarker() { - return marker; - } - - /** - * Sets the optional marker value to use in a request. If this value is set, the server will return container names - * beginning at the specified marker in the response. - *

- * The List Containers operation returns a marker value in a NextMarker element if the container - * list returned is not complete. The marker value may then be used in a subsequent call to request the next set of - * container list items. The marker value is opaque to the client. - *

- * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method on a {@link ListContainersResult} - * instance to get the marker value to set on a {@link ListContainersOptions} instance using a call to this method. - * Pass the {@link ListContainersOptions} instance as a parameter to a - * {@link BlobContract#listContainers(ListContainersOptions)} call to get the next portion of the container list. - *

- * The marker value only affects calls made on methods where this {@link ListContainersOptions} instance is - * passed as a parameter. - * - * @param marker - * A {@link String} containing the marker value to use to specify the beginning of the request results. - * @return - * A reference to this {@link ListContainersOptions} instance. - */ - public ListContainersOptions setMarker(String marker) { - this.marker = marker; - return this; - } - - /** - * Gets the value of the maximum number of results to return set in this {@link ListContainersOptions} instance. - * - * @return - * The maximum number of results to return. - */ - public int getMaxResults() { - return maxResults; - } - - /** - * Sets the optional maximum number of results to return for a request. If this value is set, the server will return - * up to this number of results in the response. If a value is not specified, or a value greater than 5,000 is - * specified, the server will return up to 5,000 items. - *

- * If there are more containers than this value that can be returned, the server returns a marker value in a - * NextMarker element in the response. The marker value may then be used in a subsequent call to - * request the next set of container list items. The marker value is opaque to the client. - *

- * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method on a {@link ListContainersResult} - * instance to get the marker value to set on a {@link ListContainersOptions} instance using a call to - * {@link ListContainersOptions#setMarker(String)}. Pass the {@link ListContainersOptions} instance as a parameter - * to a {@link BlobContract#listContainers(ListContainersOptions)} call to get the next portion of the container - * list. - *

- * The maxResults value only affects calls made on methods where this {@link ListContainersOptions} - * instance is passed as a parameter. - * - * @param maxResults - * The maximum number of results to return. - * @return - * A reference to this {@link ListContainersOptions} instance. - */ - public ListContainersOptions setMaxResults(int maxResults) { - this.maxResults = maxResults; - return this; - } - - /** - * Gets the value of a flag set in this {@link ListContainersOptions} instance indicating whether to include - * container metadata in the response to the request. - * - * @return - * true to include container metadata in the response to the request. - */ - public boolean isIncludeMetadata() { - return includeMetadata; - } - - /** - * Sets the value of an optional flag indicating whether to include container metadata with the response to the - * request. - *

- * The includeMetadata value only affects calls made on methods where this {@link ListContainersOptions} - * instance is passed as a parameter. - * - * @param includeMetadata - * Set to true to include container metadata in the response to the request. - * @return - * A reference to this {@link ListContainersOptions} instance. - */ - public ListContainersOptions setIncludeMetadata(boolean includeMetadata) { - this.includeMetadata = includeMetadata; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersResult.java deleted file mode 100644 index e3e7a035b6f77..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ListContainersResult.java +++ /dev/null @@ -1,413 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; -import java.util.HashMap; -import java.util.List; - -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.blob.implementation.MetadataAdapter; -import com.microsoft.windowsazure.services.core.RFC1123DateAdapter; - -/** - * A wrapper class for the response returned from a Blob Service REST API List Containers operation. This is returned by - * calls to implementations of {@link BlobContract#listContainers} and - * {@link BlobContract#listContainers(ListContainersOptions)}. - *

- * See the List Containers - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -@XmlRootElement(name = "EnumerationResults") -public class ListContainersResult { - private List containers; - private String accountName; - private String prefix; - private String marker; - private String nextMarker; - private int maxResults; - - /** - * Gets the container list returned in the response. - * - * @return - * A {@link List} of {@link Container} instances representing the blob containers returned by the request. - */ - @XmlElementWrapper(name = "Containers") - @XmlElement(name = "Container") - public List getContainers() { - return containers; - } - - /** - * Reserved for internal use. Sets the container list from the Containers element returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param value - * A {@link List} of {@link Container} instances representing the blob containers returned by the - * request. - */ - public void setContainers(List value) { - this.containers = value; - } - - /** - * Gets the base URI for invoking Blob Service REST API operations on the storage account. - * - * @return - * A {@link String} containing the base URI for Blob Service REST API operations on the storage account. - */ - @XmlAttribute(name = "AccountName") - public String getAccountName() { - return accountName; - } - - /** - * Reserved for internal use. Sets the base URI for invoking Blob Service REST API operations on the storage account - * from the value of the AccountName attribute of the EnumerationResults element - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param accountName - * A {@link String} containing the base URI for Blob Service REST API operations on the storage account. - */ - public void setAccountName(String accountName) { - this.accountName = accountName; - } - - /** - * Gets the value of the filter used to return only containers beginning with the prefix. This value is not - * set if a prefix was not specified in the list containers request. - * - * @return - * A {@link String} containing the prefix used to filter the container names returned, if any. - */ - @XmlElement(name = "Prefix") - public String getPrefix() { - return prefix; - } - - /** - * Reserved for internal use. Sets the filter used to return only containers beginning with the prefix from the - * Prefix element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param prefix - * A {@link String} containing the prefix used to filter the container names returned, if any. - */ - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - /** - * Gets the value of the marker that was used to specify the beginning of the container list to return with the - * request. This value is not set if a marker was not specified in the request. - *

- * The List Containers operation returns a marker value in a NextMarker element if the container - * list returned is not complete. The marker value may then be used in a subsequent call to request the next set of - * container list items. The marker value is opaque to the client. - *

- * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method to get the marker value to set on a - * {@link ListContainersOptions} instance using a call to {@link ListContainersOptions#setMarker(String)}. Pass the - * {@link ListContainersOptions} instance as a parameter to a - * {@link BlobContract#listContainers(ListContainersOptions)} call to get the next portion of the container list. - * - * @return - * A {@link String} containing the marker used to specify the beginning of the container list returned, if - * any. - */ - @XmlElement(name = "Marker") - public String getMarker() { - return marker; - } - - /** - * Reserved for internal use. Sets the marker used to specify the beginning of the container list to return from the - * Marker element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param marker - * A {@link String} containing the marker used to specify the beginning of the container list returned. - */ - public void setMarker(String marker) { - this.marker = marker; - } - - /** - * Gets the next marker value needed to specify the beginning of the next portion of the container list to return, - * if any was set in the response from the server. - *

- * The List Containers operation returns a marker value in a NextMarker element if the container - * list returned is not complete. The marker value may then be used in a subsequent call to request the next set of - * container list items. The marker value is opaque to the client. - *

- * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method to get the marker value to set on a - * {@link ListContainersOptions} instance using a call to {@link ListContainersOptions#setMarker(String)}. Pass the - * {@link ListContainersOptions} instance as a parameter to a - * {@link BlobContract#listContainers(ListContainersOptions)} call to get the next portion of the container list. - * - * @return - * A {@link String} containing the next marker value needed to specify the beginning of the next portion - * of the container list to return, if any was set in the response from the server. - */ - @XmlElement(name = "NextMarker") - public String getNextMarker() { - return nextMarker; - } - - /** - * Reserved for internal use. Sets the next marker value needed to specify the beginning of the next portion of the - * container list to return from the NextMarker element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param nextMarker - * A {@link String} containing the next marker value needed to specify the beginning of the next portion - * of the container list to return. - */ - public void setNextMarker(String nextMarker) { - this.nextMarker = nextMarker; - } - - /** - * Gets the maximum number of container list items to return that was specified in the request. The number of - * containers returned in a single response will not exceed this value. This value is not set if a maximum number - * was not specified in the request. If there are more containers that satisfy the request than this maximum value, - * the server will include a next marker value in the response, which can be used to get the remaining containers - * with a subsequent request. - *

- * Use the {@link ListContainersResult#getNextMarker() getNextMarker} method to get the marker value to set on a - * {@link ListContainersOptions} instance using a call to {@link ListContainersOptions#setMarker(String)}. Pass the - * {@link ListContainersOptions} instance as a parameter to a - * {@link BlobContract#listContainers(ListContainersOptions)} call to get the next portion of the container list. - * - * @return - * The maximum number of container list items to return that was specified in the request, if any. - */ - @XmlElement(name = "MaxResults") - public int getMaxResults() { - return maxResults; - } - - /** - * Reserved for internal use. Sets the maximum number of container list items to return that was specified in the - * request from the MaxResults element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param maxResults - * The maximum number of container list items to return that was specified in the request, if any. - */ - public void setMaxResults(int maxResults) { - this.maxResults = maxResults; - } - - /** - * Represents a container for blob storage returned by the server. A {@link Container} instance contains a copy of - * the container properties and metadata in the storage service as of the time the container list was requested. - */ - public static class Container { - private String name; - private String url; - private HashMap metadata = new HashMap(); - private ContainerProperties properties; - - /** - * Gets the name of the container. - * - * @return - * A {@link String} containing the name of the container. - */ - @XmlElement(name = "Name") - public String getName() { - return name; - } - - /** - * Reserved for internal use. Sets the name of the container from the Name element returned in - * the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param name - * A {@link String} containing the name of the container. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Gets the URI of the container. - * - * @return - * A {@link String} containing the URI of the container. - */ - @XmlElement(name = "Url") - public String getUrl() { - return url; - } - - /** - * Reserved for internal use. Sets the URI of the container from the Url element returned in - * the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param url - * A {@link String} containing the URI of the container. - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * Gets the container properties. The container properties include the last modified time and an ETag value. - * - * @return - * A {@link ContainerProperties} instance containing the properties associated with the container. - */ - @XmlElement(name = "Properties") - public ContainerProperties getProperties() { - return properties; - } - - /** - * Reserved for internal use. Sets the container properties from the Properties element - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param properties - * A {@link ContainerProperties} instance containing the properties associated with the container. - */ - public void setProperties(ContainerProperties properties) { - this.properties = properties; - } - - /** - * Gets the container metadata as a map of name and value pairs. The container metadata is for client use and is - * opaque to the server. - * - * @return - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values of - * the container metadata. - */ - @XmlElement(name = "Metadata") - @XmlJavaTypeAdapter(MetadataAdapter.class) - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. Sets the container metadata from the Metadata element - * returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param metadata - * A {@link java.util.HashMap} of key-value pairs of {@link String} containing the names and values - * of the container metadata. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } - } - - /** - * Represents the properties of a container for blob storage returned by the server. A {@link ContainerProperties} - * instance contains a copy of the container properties in the storage service as of the time the container list was - * requested. - */ - public static class ContainerProperties { - private Date lastModified; - private String etag; - - /** - * Gets the last modifed time of the container. This value can be used when updating or deleting a container - * using an optimistic concurrency model to prevent the client from modifying data that has been changed by - * another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the container. - */ - @XmlElement(name = "Last-Modified") - @XmlJavaTypeAdapter(RFC1123DateAdapter.class) - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the container from the - * Last-Modified element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the container. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the ETag of the container. This value can be used when updating or deleting a container using an - * optimistic concurrency model to prevent the client from modifying data that has been changed by another - * client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the container. - */ - @XmlElement(name = "Etag") - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the container from the ETag element returned in - * the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned - * by the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the container. - */ - public void setEtag(String etag) { - this.etag = etag; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/PageRange.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/PageRange.java deleted file mode 100644 index 57fb592e24afe..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/PageRange.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import javax.xml.bind.annotation.XmlElement; - -/** - * Represents the range of bytes in a single page within a page blob. - *

- * For a page update operation, the page range can be up to 4 MB in size. For a page clear operation, the page range can - * be up to the value of the blob's full size. - *

- * Pages are aligned with 512-byte boundaries. When specifying a page range, the start offset must be a modulus of 512 - * and the end offset must be a modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. - */ -public class PageRange { - private long start; - private long end; - - /** - * Default constructor. The start and end values must be set for this {@link PageRange} instance to be valid. - */ - public PageRange() { - } - - /** - * Creates a page range from the specified start and end byte offsets, inclusive. - *

- * Pages are aligned with 512-byte boundaries. When specifying a page range, the start offset must be a modulus of - * 512 and the end offset must be a modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. - * - * @param start - * The beginning offset value in bytes for the page range, inclusive. - * @param end - * The ending offset value in bytes for the page range, inclusive. - */ - public PageRange(long start, long end) { - this.start = start; - this.end = end; - } - - /** - * Gets the byte offset of the start of the page range within the blob, inclusive. - * - * @return - * The beginning offset value in bytes for the page range, inclusive. - */ - @XmlElement(name = "Start") - public long getStart() { - return start; - } - - /** - * Sets the byte offset of the start of the page range within the blob, inclusive. - *

- * Pages are aligned with 512-byte boundaries. When specifying a page range, the start offset must be a modulus of - * 512 and the end offset must be a modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. - * - * @param start - * The beginning offset value in bytes for the page range, inclusive. - * @return - * A reference to this {@link PageRange} instance. - */ - public PageRange setStart(long start) { - this.start = start; - return this; - } - - /** - * Gets the byte offset of the end of the page range within the blob, inclusive. - * - * @return - * The ending offset value in bytes for the page range, inclusive. - */ - @XmlElement(name = "End") - public long getEnd() { - return end; - } - - /** - * Sets the byte offset of the end of the page range within the blob, inclusive. - *

- * Pages are aligned with 512-byte boundaries. When specifying a page range, the start offset must be a modulus of - * 512 and the end offset must be a modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. - * - * @param end - * The ending offset value in bytes for the page range, inclusive. - * @return - * A reference to this {@link PageRange} instance. - */ - public PageRange setEnd(long end) { - this.end = end; - return this; - } - - /** - * Gets the size of the page range in bytes. - * - * @return - * The size of the page range in bytes. - */ - public long getLength() { - return end - start + 1; - } - - /** - * Sets the length of the page range in bytes. This updates the byte offset of the end of the page range to the - * start value plus the length specified by the value parameter. The length must be a positive multiple of - * 512 bytes. - *

- * Pages are aligned with 512-byte boundaries. When specifying a page range, the start offset must be a modulus of - * 512 and the end offset must be a modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. - * - * @param value - * The ending offset value in bytes for the page range, inclusive. - * @return - * A reference to this {@link PageRange} instance. - */ - public PageRange setLength(long value) { - this.end = this.start + value - 1; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ServiceProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ServiceProperties.java deleted file mode 100644 index f9ee9985e50c8..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/ServiceProperties.java +++ /dev/null @@ -1,412 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the Blob service properties that can be set on a storage account, including Windows Azure Storage - * Analytics. This class is used by the {@link BlobContract#getServiceProperties()} method to return the service - * property values set on the storage account, and by the {@link BlobContract#setServiceProperties(ServiceProperties)} - * and {@link BlobContract#setServiceProperties(ServiceProperties, BlobServiceOptions)} methods to set the values of the - * service properties. - */ -@XmlRootElement(name = "StorageServiceProperties") -public class ServiceProperties { - private Logging logging = new Logging(); - private Metrics metrics = new Metrics(); - private String defaultServiceVersion; - - /** - * Gets the value of the logging options on the storage account. - * - * @return - * A {@link Logging} instance containing the logging options. - */ - @XmlElement(name = "Logging") - public Logging getLogging() { - return logging; - } - - /** - * Sets the value of the logging options on the storage account. - * - * @param logging - * A {@link Logging} instance containing the logging options. - * @return - * A reference to this {@link ServiceProperties} instance. - */ - public ServiceProperties setLogging(Logging logging) { - this.logging = logging; - return this; - } - - /** - * Gets the value of the metrics options on the storage account. - * - * @return - * A {@link Metrics} instance containing the metrics options. - */ - @XmlElement(name = "Metrics") - public Metrics getMetrics() { - return metrics; - } - - /** - * Sets the value of the metrics options on the storage account. - * - * @param metrics - * A {@link Metrics} instance containing the metrics options. - * @return - * A reference to this {@link ServiceProperties} instance. - */ - public ServiceProperties setMetrics(Metrics metrics) { - this.metrics = metrics; - return this; - } - - /** - * Gets the default service version string used for operations on the storage account. - * - * @return - * A {@link String} containing the default service version string used for operations on the storage - * account. - */ - @XmlElement(name = "DefaultServiceVersion") - public String getDefaultServiceVersion() { - return defaultServiceVersion; - } - - /** - * Sets the default service version string used for operations on the storage account. This value is optional - * for a set service properties request. Allowed values include version 2009-09-19 and more recent versions. - *

- * See Storage Services Versioning - * on MSDN for more information on applicable versions. - * - * @param defaultServiceVersion - * A {@link String} containing the default service version string used for operations on the storage - * account. - * @return - * A reference to this {@link ServiceProperties} instance. - */ - public ServiceProperties setDefaultServiceVersion(String defaultServiceVersion) { - this.defaultServiceVersion = defaultServiceVersion; - return this; - } - - /** - * Represents the logging options that can be set on a storage account. - */ - public static class Logging { - private String version; - private Boolean delete; - private Boolean read; - private Boolean write; - private RetentionPolicy retentionPolicy; - - /** - * Gets the retention policy for logging data set on the storage account. - * - * @return - * The {@link RetentionPolicy} set on the storage account. - */ - @XmlElement(name = "RetentionPolicy") - public RetentionPolicy getRetentionPolicy() { - return retentionPolicy; - } - - /** - * Sets the retention policy to use for logging data on the storage account. - * - * @param retentionPolicy - * The {@link RetentionPolicy} to set on the storage account. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setRetentionPolicy(RetentionPolicy retentionPolicy) { - this.retentionPolicy = retentionPolicy; - return this; - } - - /** - * Gets a flag indicating whether all write requests are logged. - * - * @return - * A flag value of true if all write operations are logged; otherwise, false. - */ - @XmlElement(name = "Write") - public boolean isWrite() { - return write; - } - - /** - * Sets a flag indicating whether all write requests should be logged. - * - * @param write - * Set a flag value of true to log all write operations; otherwise, false. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setWrite(boolean write) { - this.write = write; - return this; - } - - /** - * Gets a flag indicating whether all read requests are logged. - * - * @return - * A flag value of true if all read operations are logged; otherwise, false. - */ - @XmlElement(name = "Read") - public boolean isRead() { - return read; - } - - /** - * Sets a flag indicating whether all read requests should be logged. - * - * @param read - * Set a flag value of true to log all read operations; otherwise, false. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setRead(boolean read) { - this.read = read; - return this; - } - - /** - * Gets a flag indicating whether all delete requests are logged. - * - * @return - * A flag value of true if all delete operations are logged; otherwise, false. - */ - @XmlElement(name = "Delete") - public boolean isDelete() { - return delete; - } - - /** - * Sets a flag indicating whether all delete requests should be logged. - * - * @param delete - * Set a flag value of true to log all delete operations; otherwise, false. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setDelete(boolean delete) { - this.delete = delete; - return this; - } - - /** - * Gets the version of logging configured on the storage account. - * - * @return - * A {@link String} containing the version of logging configured on the storage account. - */ - @XmlElement(name = "Version") - public String getVersion() { - return version; - } - - /** - * Sets the version of logging configured on the storage account. - * - * @param version - * A {@link String} containing the version of logging configured on the storage account. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setVersion(String version) { - this.version = version; - return this; - } - } - - /** - * Represents the metrics options that can be set on a storage account. - */ - public static class Metrics { - private String version; - private boolean enabled; - private Boolean includeAPIs; - private RetentionPolicy retentionPolicy; - - /** - * Gets the retention policy for metrics data set on the storage account. - * - * @return - * The {@link RetentionPolicy} set on the storage account. - */ - @XmlElement(name = "RetentionPolicy") - public RetentionPolicy getRetentionPolicy() { - return retentionPolicy; - } - - /** - * Sets the retention policy to use for metrics data on the storage account. - * - * @param retentionPolicy - * The {@link RetentionPolicy} to set on the storage account. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setRetentionPolicy(RetentionPolicy retentionPolicy) { - this.retentionPolicy = retentionPolicy; - return this; - } - - /** - * Gets a flag indicating whether metrics generates summary statistics for called API operations. - * - * @return - * A flag value of true if metrics generates summary statistics for called API operations; - * otherwise, false. - */ - @XmlElement(name = "IncludeAPIs") - public Boolean isIncludeAPIs() { - return includeAPIs; - } - - /** - * Sets a flag indicating whether metrics should generate summary statistics for called API operations. This - * flag is optional if metrics is not enabled. - * - * @param includeAPIs - * Set a flag value of true to generate summary statistics for called API operations; - * otherwise, false. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setIncludeAPIs(Boolean includeAPIs) { - this.includeAPIs = includeAPIs; - return this; - } - - /** - * Gets a flag indicating whether metrics is enabled for the storage account. - * - * @return - * A flag value of true if metrics is enabled for the storage account; otherwise, - * false. - */ - @XmlElement(name = "Enabled") - public boolean isEnabled() { - return enabled; - } - - /** - * Sets a flag indicating whether to enable metrics for the storage account. - * - * @param enabled - * Set a flag value of true to enable metrics for the storage account; otherwise, - * false. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Gets the version of Storage Analytics configured on the storage account. - * - * @return - * A {@link String} containing the version of Storage Analytics configured on the storage account. - */ - @XmlElement(name = "Version") - public String getVersion() { - return version; - } - - /** - * Sets the version of Storage Analytics configured on the storage account. - * - * @param version - * A {@link String} containing the version of Storage Analytics configured on the storage account. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setVersion(String version) { - this.version = version; - return this; - } - } - - /** - * Represents the optional retention policy that can be applied to logging or metrics on the storage account. - */ - public static class RetentionPolicy { - private boolean enabled; - private Integer days; // nullable, because optional if "enabled" is false - - /** - * Gets the number of days that metrics or logging data should be retained, if logging is enabled. - * - * @return - * The number of days to retain logging or metrics data if logging is enabled, or null. - */ - @XmlElement(name = "Days") - public Integer getDays() { - return days; - } - - /** - * Sets the number of days that metrics or logging data should be retained. The minimum value you can specify is - * 1; the largest value is 365 (one year). This value must be specified even if the enabled flag is set - * to false. - * - * @param days - * The number of days to retain logging or metrics data. - * @return - * A reference to this {@link RetentionPolicy} instance. - */ - public RetentionPolicy setDays(Integer days) { - this.days = days; - return this; - } - - /** - * Gets a flag indicating whether a retention policy is enabled. - * - * @return - * A flag value of true if a retention policy is enabled; otherwise, false. - */ - @XmlElement(name = "Enabled") - public boolean isEnabled() { - return enabled; - } - - /** - * Sets a flag indicating whether to enable a retention policy. - * - * @param enabled - * Set a flag value of true to enable a retention policy; otherwise, false. - * @return - * A reference to this {@link RetentionPolicy} instance. - */ - public RetentionPolicy setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataOptions.java deleted file mode 100644 index 4baca8d1dc342..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataOptions.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#setBlobMetadata(String, String, java.util.HashMap, SetBlobMetadataOptions) setBlobMetadata} - * request. These options include an optional server timeout for the operation, a blob lease ID, and any access - * conditions for the operation. - */ -public class SetBlobMetadataOptions extends BlobServiceOptions { - private String leaseId; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link SetBlobMetadataOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link SetBlobMetadataOptions} instance - * is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link SetBlobMetadataOptions} instance. - */ - @Override - public SetBlobMetadataOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link SetBlobMetadataOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets an optional lease ID value to match when setting metadata of the blob. If set, the lease must be active - * and the value must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobMetadataOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link SetBlobMetadataOptions} instance. - */ - public SetBlobMetadataOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the access conditions set in this {@link SetBlobMetadataOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions for setting the metadata of a blob. By default, the set blob metadata operation - * will set the metadata unconditionally. Use this method to specify conditions on the ETag or last modified time - * value for performing the operation. - *

- * The accessCondition value only affects calls made on methods where this {@link SetBlobMetadataOptions} - * instance is passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link SetBlobMetadataOptions} instance. - */ - public SetBlobMetadataOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataResult.java deleted file mode 100644 index 4fe30c077d1e6..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobMetadataResult.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Set Blob Metadata operation. This is - * returned by calls to implementations of - * {@link BlobContract#setBlobMetadata(String, String, java.util.HashMap, SetBlobMetadataOptions)}. - *

- * See the Set Blob Metadata - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -public class SetBlobMetadataResult { - private String etag; - private Date lastModified; - - /** - * Gets the ETag of the blob. - *

- * This value can be used in an access condition when updating or deleting a blob to prevent the client from - * modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the blob from the ETag element returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modified time of the blob. - *

- * Any operation that modifies the blob, including updates to the blob's metadata or properties, changes the last - * modified time of the blob. This value can be used in an access condition when updating or deleting a blob to - * prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the page blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the blob from the Last-Modified - * element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesOptions.java deleted file mode 100644 index c002057c15a70..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesOptions.java +++ /dev/null @@ -1,359 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.core.ServiceException; - -/** - * Represents the options that may be set on a - * {@link BlobContract#setBlobProperties(String, String, SetBlobPropertiesOptions) setBlobProperties} request. - * These options include an optional server timeout for the operation, the MIME content type and content encoding for - * the blob, the content length, the content language, the MD5 hash, a cache control value, a blob lease ID, a sequence - * number and sequence number action value, and any access conditions for the operation. - */ -public class SetBlobPropertiesOptions extends BlobServiceOptions { - private String leaseId; - private String contentType; - private Long contentLength; - private String contentEncoding; - private String contentLanguage; - private String contentMD5; - private String cacheControl; - private String sequenceNumberAction; - private Long sequenceNumber; - private AccessCondition accessCondition; - - /** - * Sets the optional server request timeout value associated with this {@link SetBlobPropertiesOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link SetBlobPropertiesOptions} - * instance is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - @Override - public SetBlobPropertiesOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the MIME content type value set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the MIME content type value set, if any. - */ - public String getContentType() { - return contentType; - } - - /** - * Sets the optional MIME content type for the blob content. This value will be returned to clients in the - * Content-Type header of the response when the blob data or blob properties are requested. If no - * content type is specified, the default content type is application/octet-stream. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param contentType - * A {@link String} containing the MIME content type value to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * Gets the new page blob size set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * The new size to set for a page blob. - */ - public Long getContentLength() { - return contentLength; - } - - /** - * Sets the size of a page blob to the specified size. If the specified contentLength value is less than - * the current size of the blob, then all pages above the specified value are cleared. - *

- * This property cannot be used to change the size of a block blob. Setting this property for a block blob causes a - * {@link ServiceException} to be thrown. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param contentLength - * The new size to set for a page blob. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setContentLength(Long contentLength) { - this.contentLength = contentLength; - return this; - } - - /** - * Gets the HTTP content encoding value set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the HTTP content encoding value set, if any. - */ - public String getContentEncoding() { - return contentEncoding; - } - - /** - * Sets the optional HTML content encoding value for the blob content. Use this value to specify any HTTP content - * encodings applied to the blob, passed as a x-ms-blob-content-encoding header value to the server. - * This value will be returned to clients in the headers of the response when the blob data or blob properties are - * requested. Pass an empty value to update a blob to the default value, which will cause no content encoding header - * to be returned with the blob. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param contentEncoding - * A {@link String} containing the x-ms-blob-content-encoding header value to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setContentEncoding(String contentEncoding) { - this.contentEncoding = contentEncoding; - return this; - } - - /** - * Gets the HTTP content language header value set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the HTTP content language header value set, if any. - */ - public String getContentLanguage() { - return contentLanguage; - } - - /** - * Sets the optional HTTP content language header value for the blob content. Use this value to - * specify the content language of the blob. This value will be returned to clients in the - * x-ms-blob-content-language header of the response when the blob data or blob properties are - * requested. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param contentLanguage - * A {@link String} containing the x-ms-blob-content-language header value to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setContentLanguage(String contentLanguage) { - this.contentLanguage = contentLanguage; - return this; - } - - /** - * Gets the MD5 hash value for the blob content set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the MD5 hash value for the blob content set, if any. - */ - public String getContentMD5() { - return contentMD5; - } - - /** - * Sets the optional MD5 hash value for the blob content. This value will be returned to clients in the - * x-ms-blob-content-md5 header value of the response when the blob data or blob properties are - * requested. This hash is used to verify the integrity of the blob during transport. When this header is specified, - * the storage service checks the hash of the content that has arrived with the one that was sent. If the two hashes - * do not match, the operation will fail with error code 400 (Bad Request), which will cause a ServiceException to - * be thrown. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param contentMD5 - * A {@link String} containing the MD5 hash value for the blob content to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setContentMD5(String contentMD5) { - this.contentMD5 = contentMD5; - return this; - } - - /** - * Gets the HTTP cache control value set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the HTTP cache control value set, if any. - */ - public String getCacheControl() { - return cacheControl; - } - - /** - * Sets the optional HTTP cache control value for the blob content. The Blob service stores - * this value but does not use or modify it. This value will be returned to clients in the headers of the response - * when the blob data or blob properties are requested. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param cacheControl - * A {@link String} containing the HTTP cache control value to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setCacheControl(String cacheControl) { - this.cacheControl = cacheControl; - return this; - } - - /** - * Gets the sequence number value set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * The sequence number to set, if any. - */ - public Long getSequenceNumber() { - return sequenceNumber; - } - - /** - * Sets the page blob sequence number. The sequence number is a user-controlled property that you can use to track - * requests and manage concurrency issues. This value is optional, but is required if the sequence number action - * value is set to max or update. - *

- * Use the sequenceNumber parameter together with the sequence number action to update the blob's sequence - * number, either to the specified value or to the higher of the values specified with the request or currently - * stored with the blob. This header should not be specified if the sequence number action is set to - * increment; in this case the service automatically increments the sequence number by one. - *

- * To set the sequence number to a value of your choosing, this property must be specified on the request together - * with a sequence number action value of update. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param sequenceNumber - * The sequence number to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setSequenceNumber(Long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - return this; - } - - /** - * Gets the lease ID to match for the blob set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the lease ID set, if any. - */ - public String getLeaseId() { - return leaseId; - } - - /** - * Sets an optional lease ID value to match when setting properties of the blob. If set, the lease must be active - * and the value must match the lease ID set on the leased blob for the operation to succeed. - *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param leaseId - * A {@link String} containing the lease ID to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setLeaseId(String leaseId) { - this.leaseId = leaseId; - return this; - } - - /** - * Gets the sequence number action set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * A {@link String} containing the sequence number action set, if any. - */ - public String getSequenceNumberAction() { - return sequenceNumberAction; - } - - /** - * Sets an optional sequence number action for a page blob. This value is required if a sequence number is set for - * the request. - *

- * The sequenceNumberAction parameter indicates how the service should modify the page blob's sequence - * number. Specify one of the following strings for this parameter: - *

    - *
  • max - Sets the sequence number to be the higher of the value included with the request and the - * value currently stored for the blob.
  • - *
  • update - Sets the sequence number to the value included with the request.
  • - *
  • increment - Increments the value of the sequence number by 1. If specifying this option, do not - * set the sequence number value; doing so will cause a {@link ServiceException} to be thrown.
  • - *
- *

- * Note that this value only affects calls made on methods where this {@link SetBlobPropertiesOptions} instance is - * passed as a parameter. - * - * @param sequenceNumberAction - * A {@link String} containing the sequence number action to set on the page blob. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setSequenceNumberAction(String sequenceNumberAction) { - this.sequenceNumberAction = sequenceNumberAction; - return this; - } - - /** - * Gets the access conditions set in this {@link SetBlobPropertiesOptions} instance. - * - * @return - * An {@link AccessCondition} containing the access conditions set, if any. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions for setting the properties of a blob. By default, the set blob properties operation - * will set the properties unconditionally. Use this method to specify conditions on the ETag or last modified time - * value for performing the operation. - *

- * The accessCondition value only affects calls made on methods where this {@link SetBlobPropertiesOptions} - * instance is passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} containing the access conditions to set. - * @return - * A reference to this {@link SetBlobPropertiesOptions} instance. - */ - public SetBlobPropertiesOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesResult.java deleted file mode 100644 index 8180dd21db398..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetBlobPropertiesResult.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * A wrapper class for the response returned from a Blob Service REST API Set Blob Properties operation. This is - * returned by calls to implementations of - * {@link BlobContract#setBlobProperties(String, String, SetBlobPropertiesOptions)}. - *

- * See the Set Blob Properties - * documentation on MSDN for details of the underlying Blob Service REST API operation. - */ -public class SetBlobPropertiesResult { - private String etag; - private Date lastModified; - private Long sequenceNumber; - - /** - * Gets the ETag of the blob. - *

- * This value can be used in an access condition when updating or deleting a blob to prevent the client from - * modifying data that has been changed by another client. - * - * @return - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag of the blob from the ETag element returned in the - * response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the server-assigned ETag value for the blob. - */ - public void setEtag(String etag) { - this.etag = etag; - } - - /** - * Gets the last modified time of the blob. - *

- * Any operation that modifies the blob, including updates to the blob's metadata or properties, changes the last - * modified time of the blob. This value can be used in an access condition when updating or deleting a blob to - * prevent the client from modifying data that has been changed by another client. - * - * @return - * A {@link java.util.Date} containing the last modified time of the page blob. - */ - public Date getLastModified() { - return lastModified; - } - - /** - * Reserved for internal use. Sets the last modified time of the blob from the Last-Modified - * element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param lastModified - * A {@link java.util.Date} containing the last modified time of the blob. - */ - public void setLastModified(Date lastModified) { - this.lastModified = lastModified; - } - - /** - * Gets the sequence number of the page blob. This value can be used when updating or deleting a page blob using an - * optimistic concurrency model to prevent the client from modifying data that has been changed by another - * client. - * - * @return - * A {@link String} containing the client-assigned sequence number value for the page blob. - */ - public Long getSequenceNumber() { - return sequenceNumber; - } - - /** - * Reserved for internal use. Sets the sequence number of the page blob from the - * x-ms-blob-sequence-number element returned in the response. - *

- * This method is invoked by the API to set the value from the Blob Service REST API operation response returned by - * the server. - * - * @param sequenceNumber - * A {@link String} containing the client-assigned sequence number value for the page blob. - */ - public void setSequenceNumber(Long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetContainerMetadataOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetContainerMetadataOptions.java deleted file mode 100644 index 25933e8a3e6f7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/models/SetContainerMetadataOptions.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.models; - -import com.microsoft.windowsazure.services.blob.BlobContract; - -/** - * Represents the options that may be set on a - * {@link BlobContract#setContainerMetadata(String, java.util.HashMap, SetContainerMetadataOptions)} request. These - * options include a server response timeout for the request and access conditions that specify whether to perform the - * operation or not depending on the values of the Etag or last modified time of the container. Options that are not set - * will not be passed to the server with a request. - */ -public class SetContainerMetadataOptions extends BlobServiceOptions { - private AccessCondition accessCondition; - - /** - * Sets the server request timeout value associated with this {@link SetContainerMetadataOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link SetContainerMetadataOptions} - * instance is passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link SetContainerMetadataOptions} instance. - */ - @Override - public SetContainerMetadataOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the access conditions associated with this {@link SetContainerMetadataOptions} instance. - * - * @return - * An {@link AccessCondition} reference containing the Etag and last modified time conditions for performing - * the set container metadata operation, or null if not set. - */ - public AccessCondition getAccessCondition() { - return accessCondition; - } - - /** - * Sets the access conditions associated with this {@link SetContainerMetadataOptions} instance. By default, the set - * container metadata operation will set the container metadata unconditionally. Use this method to specify - * conditions on the Etag or last modified time value for performing the set container metadata operation. - *

- * The accessCondition value only affects calls made on methods where this - * {@link SetContainerMetadataOptions} instance is passed as a parameter. - * - * @param accessCondition - * An {@link AccessCondition} reference containing the Etag and last modified time conditions for - * performing the set container metadata operation. Specify null to make the operation - * unconditional. - * @return - * A reference to this {@link SetContainerMetadataOptions} instance. - */ - public SetContainerMetadataOptions setAccessCondition(AccessCondition accessCondition) { - this.accessCondition = accessCondition; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/Builder.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/Builder.java deleted file mode 100644 index 5f25c2bb67b34..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/Builder.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.util.Map; - -public interface Builder { - - public abstract T build(String profile, Class service, Class instance, Map properties); - - public interface Factory { - T create(String profile, Class service, Builder builder, Map properties); - } - - public interface Alteration { - T alter(String profile, T instance, Builder builder, Map properties); - } - - public interface Registry { - Registry add(Class service); - - Registry add(Class service, Class implementation); - - Registry add(Factory factory); - - void alter(Class service, Class instance, Alteration alteration); - } - - public interface Exports { - void register(Registry registry); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/Configuration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/Configuration.java deleted file mode 100644 index 34c58ff4142d1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/Configuration.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class Configuration { - - /** - * Property name for socket connection timeout used by services created with this configuration. - */ - public static final String PROPERTY_CONNECT_TIMEOUT = "com.microsoft.windowsazure.services.core.Configuration.connectTimeout"; - - /** - * Property name for socket read timeout used by services created with this configuration. - */ - public static final String PROPERTY_READ_TIMEOUT = "com.microsoft.windowsazure.services.core.Configuration.readTimeout"; - - /** - * Property name to control if HTTP logging to console is on or off. If property is set, logging is on, regardless - * of value. - */ - public static final String PROPERTY_LOG_HTTP_REQUESTS = "com.microsoft.windowsazure.services.core.Configuration.logHttpRequests"; - - private static Configuration instance; - Map properties; - Builder builder; - - static Log log = LogFactory.getLog(Configuration.class); - - public Configuration() { - this.properties = new HashMap(); - this.builder = DefaultBuilder.create(); - } - - public Configuration(Builder builder) { - this.properties = new HashMap(); - this.builder = builder; - } - - public static Configuration getInstance() { - if (instance == null) { - try { - instance = Configuration.load(); - } - catch (IOException e) { - log.error("Unable to load META-INF/com.microsoft.windowsazure.properties", e); - instance = new Configuration(); - } - } - return instance; - } - - public static void setInstance(Configuration instance) { - Configuration.instance = instance; - } - - public static Configuration load() throws IOException { - Configuration config = new Configuration(); - - InputStream stream = Configuration.class.getClassLoader().getResourceAsStream( - "META-INF/com.microsoft.windowsazure.properties"); - if (stream != null) { - Properties properties = new Properties(); - properties.load(stream); - for (Object key : properties.keySet()) { - config.setProperty(key.toString(), properties.get(key)); - } - } - - return config; - } - - public T create(Class service) { - return builder.build("", service, service, properties); - } - - public T create(String profile, Class service) { - return builder.build(profile, service, service, properties); - } - - public Builder getBuilder() { - return builder; - } - - public Object getProperty(String name) { - return properties.get(name); - } - - public void setProperty(String name, Object value) { - properties.put(name, value); - } - - public Map getProperties() { - return properties; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/DefaultBuilder.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/DefaultBuilder.java deleted file mode 100644 index ad045e85da2e2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/DefaultBuilder.java +++ /dev/null @@ -1,207 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.ServiceLoader; - -import javax.inject.Inject; -import javax.inject.Named; - -public class DefaultBuilder implements Builder, Builder.Registry { - Map, Factory> factories; - Map, Map, List>>> alterations; - - public DefaultBuilder() { - factories = new HashMap, Factory>(); - alterations = new HashMap, Map, List>>>(); - } - - public static DefaultBuilder create() { - DefaultBuilder builder = new DefaultBuilder(); - - for (Builder.Exports exports : ServiceLoader.load(Builder.Exports.class)) { - exports.register(builder); - } - - return builder; - } - - void addFactory(Class service, Factory factory) { - factories.put(service, factory); - } - - @Override - public Builder.Registry add(Class service) { - return add(service, service); - } - - Constructor findInjectConstructor(Class implementation) { - - Constructor withInject = null; - Constructor withoutInject = null; - int count = 0; - - for (Constructor ctor : implementation.getConstructors()) { - if (ctor.getAnnotation(Inject.class) != null) { - if (withInject != null) { - throw new RuntimeException("Class must not have multple @Inject annotations: " - + implementation.getName()); - } - withInject = ctor; - } - else { - ++count; - withoutInject = ctor; - } - } - if (withInject != null) { - return withInject; - } - if (count != 1) { - throw new RuntimeException("Class without @Inject annotation must have one constructor: " - + implementation.getName()); - } - return withoutInject; - } - - @Override - public Builder.Registry add(Class service, final Class implementation) { - final Constructor ctor = findInjectConstructor(implementation); - final Class[] parameterTypes = ctor.getParameterTypes(); - final Annotation[][] parameterAnnotations = ctor.getParameterAnnotations(); - - addFactory(service, new Builder.Factory() { - @Override - @SuppressWarnings("unchecked") - public T create(String profile, Class service, Builder builder, Map properties) { - Object[] initializationArguments = new Object[parameterTypes.length]; - for (int i = 0; i != parameterTypes.length; ++i) { - - boolean located = false; - - String named = findNamedAnnotation(parameterAnnotations[i]); - String fullName = dotCombine(profile, named); - - boolean probeProperties = fullName != null && fullName != ""; - int startingIndex = 0; - while (!located && probeProperties) { - String nameProbe = fullName.substring(startingIndex); - if (!located && named != null && properties.containsKey(nameProbe)) { - located = true; - initializationArguments[i] = properties.get(nameProbe); - } - else { - startingIndex = fullName.indexOf('.', startingIndex) + 1; - if (startingIndex == 0) { - probeProperties = false; - } - } - } - - if (!located) { - located = true; - initializationArguments[i] = builder.build(fullName, service, parameterTypes[i], properties); - } - } - - try { - return (T) ctor.newInstance(initializationArguments); - } - catch (InstantiationException e) { - throw new ConfigurationException(e); - } - catch (IllegalAccessException e) { - throw new ConfigurationException(e); - } - catch (InvocationTargetException e) { - throw new ConfigurationException(e); - } - } - }); - return this; - } - - protected String dotCombine(String profile, String named) { - boolean noProfile = profile == null || profile == ""; - boolean noName = named == null || named == ""; - if (noName) - return profile; - if (noProfile) - return named; - return profile + "." + named; - } - - protected String findNamedAnnotation(Annotation[] annotations) { - for (Annotation annotation : annotations) { - if (Named.class.isAssignableFrom(annotation.getClass())) { - return ((Named) annotation).value(); - } - } - return null; - } - - @Override - public Registry add(Factory factory) { - for (Type genericInterface : factory.getClass().getGenericInterfaces()) { - ParameterizedType parameterizedType = (ParameterizedType) genericInterface; - if (parameterizedType.getRawType().equals(Builder.Factory.class)) { - Type typeArgument = parameterizedType.getActualTypeArguments()[0]; - addFactory((Class) typeArgument, factory); - } - } - return this; - } - - @Override - @SuppressWarnings("unchecked") - public T build(String profile, Class service, Class instanceClass, Map properties) { - Factory factory = (Factory) factories.get(instanceClass); - if (factory == null) { - throw new RuntimeException("Service or property not registered: " + profile + " " + service.getName()); - } - T instance = factory.create(profile, service, this, properties); - Map, List>> alterationMap = alterations.get(service); - if (alterationMap != null) { - List> alterationList = alterationMap.get(instanceClass); - if (alterationList != null) { - for (Alteration alteration : alterationList) { - instance = ((Alteration) alteration).alter(profile, instance, this, properties); - } - } - } - return instance; - } - - @Override - public void alter(Class service, Class instance, Alteration alteration) { - if (!this.alterations.containsKey(service)) { - this.alterations.put(service, new HashMap, List>>()); - } - if (!this.alterations.get(service).containsKey(instance)) { - this.alterations.get(service).put(instance, new ArrayList>()); - } - this.alterations.get(service).get(instance).add(alteration); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ExponentialRetryPolicy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ExponentialRetryPolicy.java deleted file mode 100644 index a03c811eaf47d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ExponentialRetryPolicy.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.util.Arrays; -import java.util.Random; - -import com.microsoft.windowsazure.services.core.ServiceFilter.Response; - -public class ExponentialRetryPolicy extends RetryPolicy { - private final int deltaBackoffIntervalInMs; - private final int maximumAttempts; - private final Random randRef = new Random(); - private final int resolvedMaxBackoff = DEFAULT_MAX_BACKOFF; - private final int resolvedMinBackoff = DEFAULT_MIN_BACKOFF; - private final int[] retryableStatusCodes; - - public ExponentialRetryPolicy(int[] retryableStatusCodes) { - this(DEFAULT_CLIENT_BACKOFF, DEFAULT_CLIENT_RETRY_COUNT, retryableStatusCodes); - } - - public ExponentialRetryPolicy(int deltaBackoff, int maximumAttempts, int[] retryableStatusCodes) { - this.deltaBackoffIntervalInMs = deltaBackoff; - this.maximumAttempts = maximumAttempts; - this.retryableStatusCodes = Arrays.copyOf(retryableStatusCodes, retryableStatusCodes.length); - Arrays.sort(this.retryableStatusCodes); - } - - @Override - public boolean shouldRetry(int retryCount, Response response, Exception error) { - if (response == null) - return false; - - if (retryCount >= this.maximumAttempts) - return false; - - // Don't retry if not retryable status code - if (Arrays.binarySearch(this.retryableStatusCodes, response.getStatus()) < 0) - return false; - - return true; - } - - @Override - public int calculateBackoff(int currentRetryCount, Response response, Exception error) { - // Calculate backoff Interval between 80% and 120% of the desired - // backoff, multiply by 2^n -1 for - // exponential - int incrementDelta = (int) (Math.pow(2, currentRetryCount) - 1); - int boundedRandDelta = (int) (this.deltaBackoffIntervalInMs * 0.8) - + this.randRef.nextInt((int) (this.deltaBackoffIntervalInMs * 1.2) - - (int) (this.deltaBackoffIntervalInMs * 0.8)); - incrementDelta *= boundedRandDelta; - - // Enforce max / min backoffs - return Math.min(this.resolvedMinBackoff + incrementDelta, this.resolvedMaxBackoff); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/FilterableService.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/FilterableService.java deleted file mode 100644 index 53f8efe2d1fd5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/FilterableService.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -public interface FilterableService { - T withFilter(ServiceFilter filter); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/IdempotentClientFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/IdempotentClientFilter.java deleted file mode 100644 index f929716eec169..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/IdempotentClientFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.core; - -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; - -/** - * Base class for filters that enforces idempotency - the filter - * will only be applied once for a particular request, even - * if the request passes through this filter more than once. - * - */ -public abstract class IdempotentClientFilter extends ClientFilter { - /* (non-Javadoc) - * @see com.sun.jersey.api.client.filter.ClientFilter#handle(com.sun.jersey.api.client.ClientRequest) - */ - @Override - public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { - String key = getKey(); - - if (cr.getProperties().containsKey(key)) { - return this.getNext().handle(cr); - } - cr.getProperties().put(key, this); - return doHandle(cr); - } - - /** - * Implemented by derived classes to provide the actual implementation for filtering. - * - * @param cr - * The ClientRequest being processed - * @return The returned ClientResponse - * @throws ClientHandlerException - */ - protected abstract ClientResponse doHandle(ClientRequest cr) throws ClientHandlerException; - - /** - * Get the key value used to detect multiple runs. By default, - * defaults to the class name for the filter. - * - * @return Key name as a string - */ - protected String getKey() { - return this.getClass().getName(); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RetryPolicy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RetryPolicy.java deleted file mode 100644 index a3e1a6ac74187..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RetryPolicy.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import com.microsoft.windowsazure.services.core.ServiceFilter.Response; - -public abstract class RetryPolicy { - public static final int DEFAULT_CLIENT_BACKOFF = 1000 * 30; - public static final int DEFAULT_CLIENT_RETRY_COUNT = 3; - public static final int DEFAULT_MAX_BACKOFF = 1000 * 90; - public static final int DEFAULT_MIN_BACKOFF = 100 * 3; - - public abstract boolean shouldRetry(int retryCount, Response response, Exception error); - - public abstract int calculateBackoff(int retryCount, Response response, Exception error); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RetryPolicyFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RetryPolicyFilter.java deleted file mode 100644 index 7c0a56a69ff40..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/RetryPolicyFilter.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.io.InputStream; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class RetryPolicyFilter implements ServiceFilter { - private static final Log log = LogFactory.getLog(RetryPolicyFilter.class); - private final RetryPolicy retryPolicy; - - public RetryPolicyFilter(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - } - - @Override - public Response handle(Request request, Next next) throws Exception { - // Only the last added retry policy should be active - if (request.getProperties().containsKey("RetryPolicy")) - return next.handle(request); - request.getProperties().put("RetryPolicy", this); - - // Retry the operation as long as retry policy tells us to do so - for (int retryCount = 0;; ++retryCount) { - // Mark the stream before passing the request through - if (getEntityStream(request) != null) { - getEntityStream(request).mark(Integer.MAX_VALUE); - } - - // Pass the request to the next handler - Response response = null; - Exception error = null; - try { - response = next.handle(request); - } - catch (Exception e) { - error = e; - } - - // Determine if we should retry according to retry policy - boolean shouldRetry = retryPolicy.shouldRetry(retryCount, response, error); - if (!shouldRetry) { - if (error != null) - throw error; - return response; - } - - // Reset the stream before retrying - if (getEntityStream(request) != null) { - getEntityStream(request).reset(); - } - - // Backoff for some time according to retry policy - int backoffTime = retryPolicy.calculateBackoff(retryCount, response, error); - log.info(String.format("Request failed. Backing off for %1s milliseconds before retrying (retryCount=%2d)", - backoffTime, retryCount)); - backoff(backoffTime); - } - } - - private InputStream getEntityStream(Request request) { - if (request.getEntity() == null) - return null; - - if (!(request.getEntity() instanceof InputStream)) - return null; - - InputStream entityStream = (InputStream) request.getEntity(); - - // If the entity is an InputStream that doesn't support "mark/reset", we can't - // implement a retry logic, so we simply throw. - if (!entityStream.markSupported()) { - throw new IllegalArgumentException("The input stream for the request entity must support 'mark' and " - + "'reset' to be compatible with a retry policy filter."); - } - - return entityStream; - } - - private void backoff(int milliseconds) { - try { - Thread.sleep(milliseconds); - } - catch (InterruptedException e) { - // Restore the interrupted status - Thread.currentThread().interrupt(); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceException.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceException.java deleted file mode 100644 index 2ea554ad89d17..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceException.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.util.HashMap; -import java.util.Map; - -public class ServiceException extends Exception { - - private static final long serialVersionUID = -4942076377009150131L; - - int httpStatusCode; - String httpReasonPhrase; - String serviceName; - - String errorCode; - String errorMessage; - Map errorValues; - String rawResponseBody; - - public ServiceException() { - init(); - } - - public ServiceException(String message) { - super(message); - init(); - } - - public ServiceException(String message, Throwable cause) { - super(message, cause); - init(); - } - - public ServiceException(Throwable cause) { - super(cause); - init(); - } - - private void init() { - errorValues = new HashMap(); - } - - @Override - public String getMessage() { - if (this.rawResponseBody == null) - return super.getMessage(); - else - return super.getMessage() + "\nResponse Body: " + this.rawResponseBody; - } - - public int getHttpStatusCode() { - return httpStatusCode; - } - - public void setHttpStatusCode(int httpStatusCode) { - this.httpStatusCode = httpStatusCode; - } - - public String getHttpReasonPhrase() { - return httpReasonPhrase; - } - - public void setHttpReasonPhrase(String httpReasonPhrase) { - this.httpReasonPhrase = httpReasonPhrase; - } - - public String getErrorCode() { - return errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public Map getErrorValues() { - return errorValues; - } - - public void setErrorValues(Map errorValues) { - this.errorValues = errorValues; - } - - public String getErrorValue(String name) { - return errorValues.get(name); - } - - public void setErrorValue(String name, String value) { - this.errorValues.put(name, value); - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public void setRawResponseBody(String body) { - this.rawResponseBody = body; - } - - public String getRawResponseBody() { - return rawResponseBody; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceFilter.java deleted file mode 100644 index b1e0029f567e0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/ServiceFilter.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.io.InputStream; -import java.net.URI; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; - -public interface ServiceFilter { - Response handle(Request request, Next next) throws Exception; - - public interface Next { - Response handle(Request request) throws Exception; - } - - public interface Request { - public String getMethod(); - - public void setMethod(String method); - - public URI getURI(); - - public void setURI(URI uri); - - public MultivaluedMap getHeaders(); - - public Object getEntity(); - - public void setEntity(Object entity); - - public Map getProperties(); - - public void setProperties(Map properties); - } - - public interface Response { - int getStatus(); - - void setStatus(int status); - - MultivaluedMap getHeaders(); - - boolean hasEntity(); - - InputStream getEntityInputStream(); - - void setEntityInputStream(InputStream entity); - - Map getProperties(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/UserAgentFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/UserAgentFilter.java deleted file mode 100644 index 19de5d41d4ae5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/UserAgentFilter.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; - -/** - * The Class UserAgentFilter. - */ -public class UserAgentFilter extends ClientFilter { - - /** The azure sdk product token. */ - private static String azureSDKProductToken; - - /** - * Instantiates a new user agent filter. - */ - public UserAgentFilter() { - if ((azureSDKProductToken == null) || azureSDKProductToken.isEmpty()) { - azureSDKProductToken = createAzureSDKProductToken(); - } - - } - - /* (non-Javadoc) - * @see com.sun.jersey.api.client.filter.ClientFilter#handle(com.sun.jersey.api.client.ClientRequest) - */ - @Override - public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException { - String userAgent; - - if (clientRequest.getHeaders().containsKey("User-Agent")) { - String currentUserAgent = (String) clientRequest.getHeaders().getFirst("User-Agent"); - userAgent = azureSDKProductToken + " " + currentUserAgent; - clientRequest.getHeaders().remove("User-Agent"); - } - else { - userAgent = azureSDKProductToken; - } - - clientRequest.getHeaders().add("User-Agent", userAgent); - - return this.getNext().handle(clientRequest); - } - - /** - * Creates the azure sdk product token. - * - * @return the string - */ - private String createAzureSDKProductToken() { - String version = getVersionFromResources(); - String productToken; - if ((version != null) && (!version.isEmpty())) { - productToken = "Azure-SDK-For-Java/" + version; - } - else { - productToken = "Azure-SDK-For-Java"; - } - - return productToken; - } - - /** - * Gets the version of the SDK from resources. - * - * @return the version from resources - */ - private String getVersionFromResources() { - String version = "unknown"; - Properties properties = new Properties(); - try { - InputStream inputStream = getClass().getClassLoader().getResourceAsStream( - "META-INF/maven/com.microsoft.windowsazure/microsoft-windowsazure-api/pom.properties"); - if (inputStream != null) { - properties.load(inputStream); - version = properties.getProperty("version"); - inputStream.close(); - } - } - catch (IOException e) { - } - - return version; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AccessCondition.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AccessCondition.java deleted file mode 100644 index 47397ee0ac676..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AccessCondition.java +++ /dev/null @@ -1,386 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.HttpURLConnection; -import java.util.Date; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseRequest; - -/** - * Represents a set of access conditions to be used for operations against the storage services. - */ -public final class AccessCondition { - /** - * Generates a new empty AccessCondition. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @return An AccessCondition object that has no conditions set. - */ - public static AccessCondition generateEmptyCondition() { - return new AccessCondition(); - } - - /** - * Returns an access condition such that an operation will be performed only if the resource's ETag value matches - * the specified ETag value. - *

- * Setting this access condition modifies the request to include the HTTP If-Match conditional header. If this - * access condition is set, the operation is performed only if the ETag of the resource matches the specified ETag. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param etag - * A String that represents the ETag value to check. - * - * @return An AccessCondition object that represents the If-Match condition. - */ - public static AccessCondition generateIfMatchCondition(final String etag) { - AccessCondition retCondition = new AccessCondition(); - retCondition.setIfMatch(etag); - return retCondition; - } - - /** - * Returns an access condition such that an operation will be performed only if the resource has been modified since - * the specified time. - *

- * Setting this access condition modifies the request to include the HTTP If-Modified-Since conditional - * header. If this access condition is set, the operation is performed only if the resource has been modified since - * the specified time. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param lastMotified - * A java.util.Date object that represents the last-modified time to check for the resource. - * - * @return An AccessCondition object that represents the If-Modified-Since condition. - */ - public static AccessCondition generateIfModifiedSinceCondition(final Date lastMotified) { - AccessCondition retCondition = new AccessCondition(); - retCondition.ifModifiedSinceDate = lastMotified; - return retCondition; - } - - /** - * Returns an access condition such that an operation will be performed only if the resource's ETag value does not - * match the specified ETag value. - *

- * Setting this access condition modifies the request to include the HTTP If-None-Match conditional header. If - * this access condition is set, the operation is performed only if the ETag of the resource does not match the - * specified ETag. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param etag - * A String that represents the ETag value to check. - * - * @return An AccessCondition object that represents the If-None-Match condition. - */ - public static AccessCondition generateIfNoneMatchCondition(final String etag) { - AccessCondition retCondition = new AccessCondition(); - retCondition.setIfNoneMatch(etag); - return retCondition; - } - - /** - * Returns an access condition such that an operation will be performed only if the resource has not been modified - * since the specified time. - *

- * Setting this access condition modifies the request to include the HTTP If-Unmodified-Since conditional - * header. If this access condition is set, the operation is performed only if the resource has not been modified - * since the specified time. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param lastMotified - * A java.util.Date object that represents the last-modified time to check for the resource. - * - * @return An AccessCondition object that represents the If-Unmodified-Since condition. - */ - public static AccessCondition generateIfNotModifiedSinceCondition(final Date lastMotified) { - AccessCondition retCondition = new AccessCondition(); - retCondition.ifUnmodifiedSinceDate = lastMotified; - return retCondition; - } - - /** - * Returns an access condition such that an operation will be performed only if the resource is accessible under the - * specified lease id. - *

- * Setting this access condition modifies the request to include the HTTP If-Unmodified-Since conditional - * header. If this access condition is set, the operation is performed only if the resource has not been modified - * since the specified time. - *

- * For more information, see Specifying - * Conditional Headers for Blob Service Operations. - * - * @param leaseID - * The lease id to specify. - * - */ - public static AccessCondition generateLeaseCondition(final String leaseID) { - AccessCondition retCondition = new AccessCondition(); - retCondition.leaseID = leaseID; - return retCondition; - } - - private String leaseID = null; - - /** - * Represents the etag of the resource for if [none] match conditions - */ - private String etag = null; - - /** - * Represents the date for IfModifiedSince conditions. - */ - private Date ifModifiedSinceDate = null; - - /** - * Represents the date for IfUn,odifiedSince conditions. - */ - private Date ifUnmodifiedSinceDate = null; - - /** - * Represents the ifMatchHeaderType type. - */ - private String ifMatchHeaderType = null; - - /** - * Creates an instance of the AccessCondition class. - */ - public AccessCondition() { - // Empty Default Ctor - } - - /** - * RESERVED FOR INTERNAL USE. Applies the access condition to the request. - * - * @param request - * A java.net.HttpURLConnection object that represents the request to which the condition is - * being applied. - * - * @throws StorageException - * If there is an error parsing the date value of the access condition. - */ - public void applyConditionToRequest(final HttpURLConnection request) { - applyConditionToRequest(request, false); - } - - /** - * RESERVED FOR INTERNAL USE. Applies the access condition to the request. - * - * @param request - * A java.net.HttpURLConnection object that represents the request to which the condition is - * being applied. - * @param useSourceAccessHeaders - * If true will use the Source_ headers for the conditions, otherwise standard headers are used. - * @throws StorageException - * If there is an error parsing the date value of the access condition. - */ - public void applyConditionToRequest(final HttpURLConnection request, boolean useSourceAccessHeaders) { - // When used as a source access condition - if (useSourceAccessHeaders) { - if (!Utility.isNullOrEmpty(this.leaseID)) { - request.setRequestProperty(Constants.HeaderConstants.SOURCE_LEASE_ID_HEADER, this.leaseID); - } - - if (this.ifModifiedSinceDate != null) { - request.setRequestProperty(Constants.HeaderConstants.SOURCE_IF_MODIFIED_SINCE_HEADER, - Utility.getGMTTime(this.ifModifiedSinceDate)); - } - - if (this.ifUnmodifiedSinceDate != null) { - request.setRequestProperty(Constants.HeaderConstants.SOURCE_IF_UNMODIFIED_SINCE_HEADER, - Utility.getGMTTime(this.ifUnmodifiedSinceDate)); - } - - if (!Utility.isNullOrEmpty(this.etag)) { - if (this.ifMatchHeaderType.equals(Constants.HeaderConstants.IF_MATCH)) { - request.setRequestProperty(Constants.HeaderConstants.SOURCE_IF_MATCH_HEADER, this.etag); - } - else if (this.ifMatchHeaderType.equals(Constants.HeaderConstants.IF_NONE_MATCH)) { - request.setRequestProperty(Constants.HeaderConstants.SOURCE_IF_NONE_MATCH_HEADER, this.etag); - } - } - } - else { - if (!Utility.isNullOrEmpty(this.leaseID)) { - BaseRequest.addLeaseId(request, this.leaseID); - } - - if (this.ifModifiedSinceDate != null) { - // The IfModifiedSince has a special helper in HttpURLConnection, use it instead of manually setting the - // header. - request.setIfModifiedSince(this.ifModifiedSinceDate.getTime()); - } - - if (this.ifUnmodifiedSinceDate != null) { - request.setRequestProperty(Constants.HeaderConstants.IF_UNMODIFIED_SINCE, - Utility.getGMTTime(this.ifUnmodifiedSinceDate)); - } - - if (!Utility.isNullOrEmpty(this.etag)) { - request.setRequestProperty(this.ifMatchHeaderType, this.etag); - } - } - } - - /** - * @return the etag when the If-Match condition is set. - */ - public String getIfMatch() { - return this.ifMatchHeaderType.equals(Constants.HeaderConstants.IF_MATCH) ? this.etag : null; - } - - /** - * @return the ifModifiedSinceDate - */ - public Date getIfModifiedSinceDate() { - return this.ifModifiedSinceDate; - } - - /** - * @return the etag when the If-None-Match condition is set. - */ - public String getIfNoneMatch() { - return this.ifMatchHeaderType.equals(Constants.HeaderConstants.IF_NONE_MATCH) ? this.etag : null; - } - - /** - * @return the ifUnmodifiedSinceDate - */ - public Date getIfUnmodifiedSinceDate() { - return this.ifUnmodifiedSinceDate; - } - - /** - * @return the leaseID - */ - public String getLeaseID() { - return this.leaseID; - } - - /** - * @param etag - * the etag to set - */ - public void setIfMatch(String etag) { - this.etag = normalizeEtag(etag); - this.ifMatchHeaderType = Constants.HeaderConstants.IF_MATCH; - } - - /** - * @param ifModifiedSinceDate - * the ifModifiedSinceDate to set - */ - public void setIfModifiedSinceDate(Date ifModifiedSinceDate) { - this.ifModifiedSinceDate = ifModifiedSinceDate; - } - - /** - * @param etag - * the etag to set - */ - public void setIfNoneMatch(String etag) { - this.etag = normalizeEtag(etag); - this.ifMatchHeaderType = Constants.HeaderConstants.IF_NONE_MATCH; - } - - /** - * @param ifUnmodifiedSinceDate - * the ifUnmodifiedSinceDate to set - */ - public void setIfUnmodifiedSinceDate(Date ifUnmodifiedSinceDate) { - this.ifUnmodifiedSinceDate = ifUnmodifiedSinceDate; - } - - /** - * @param leaseID - * the leaseID to set - */ - public void setLeaseID(String leaseID) { - this.leaseID = leaseID; - } - - /** - * Reserved for internal use. Verifies the condition is satisfied. - * - * @param etag - * A String that represents the ETag to check. - * @param lastModified - * A java.util.Date object that represents the last modified date/time. - * - * @return true if the condition is satisfied; otherwise, false. - * - */ - public boolean verifyConditional(final String etag, final Date lastModified) { - if (this.ifModifiedSinceDate != null) { - // The IfModifiedSince has a special helper in HttpURLConnection, use it instead of manually setting the - // header. - if (!lastModified.after(this.ifModifiedSinceDate)) { - return false; - } - } - - if (this.ifUnmodifiedSinceDate != null) { - if (lastModified.after(this.ifUnmodifiedSinceDate)) { - return false; - } - } - - if (!Utility.isNullOrEmpty(this.etag)) { - if (this.ifMatchHeaderType.equals(Constants.HeaderConstants.IF_MATCH)) { - if (!this.etag.equals(etag) && !this.etag.equals("*")) { - return false; - } - } - else if (this.ifMatchHeaderType.equals(Constants.HeaderConstants.IF_NONE_MATCH)) { - if (this.etag.equals(etag)) { - return false; - } - } - } - - return true; - } - - /** - * Normalizes an Etag to be quoted, unless it is * - * - * @param inTag - * the etag to normalize - * @return the quoted etag - */ - private static String normalizeEtag(String inTag) { - if (Utility.isNullOrEmpty(inTag) || inTag.equals("*")) { - return inTag; - } - else if (inTag.startsWith("\"") && inTag.endsWith("\"")) { - return inTag; - } - else { - return String.format("\"%s\"", inTag); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AccessPolicyResponseBase.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AccessPolicyResponseBase.java deleted file mode 100644 index a1c748afcad10..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AccessPolicyResponseBase.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.io.InputStream; -import java.text.ParseException; -import java.util.HashMap; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse SharedAccessPolicies from an input stream. - */ -public abstract class AccessPolicyResponseBase { - /** - * Holds a flag indicating if the response has been parsed or not. - */ - private boolean isParsed; - - /** - * Holds the Hashmap of policies parsed from the stream - */ - private final HashMap policies = new HashMap(); - - /** - * Holds a reference to the input stream to read from. - */ - private final InputStream streamRef; - - /** - * Initializes the AccessPolicyResponse object - * - * @param stream - * the input stream to read error details from. - */ - public AccessPolicyResponseBase(final InputStream stream) { - this.streamRef = stream; - } - - /** - * Gets the HashMap of SharedAccessPolicies from the response - * - * @return the HashMap of SharedAccessPolicies from the response - * @throws XMLStreamException - * if an XMLStreamException occurs. - * @throws ParseException - * if a date is incorrectly encoded in the stream - */ - public HashMap getAccessIdentifiers() throws XMLStreamException, ParseException { - if (!this.isParsed) { - this.parseResponse(); - } - - return this.policies; - } - - /** - * Parses the response for the Shared Access Policies - * - * @throws XMLStreamException - * if an XMLStreamException occurs. - * @throws ParseException - * if a date is incorrectly encoded in the stream - */ - public void parseResponse() throws XMLStreamException, ParseException { - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(this.streamRef); - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.SIGNED_IDENTIFIERS_ELEMENT)) { - this.readPolicies(xmlr); - break; - } - } - } - - this.isParsed = true; - } - - /** - * Reads all the policies from the XMLStreamReader - * - * @param xmlr - * the XMLStreamReader to read from - * @throws XMLStreamException - * if an XMLStreamException occurs. - * @throws ParseException - * if a date is incorrectly encoded in the stream - */ - private void readPolicies(final XMLStreamReader xmlr) throws XMLStreamException, ParseException { - int eventType = xmlr.getEventType(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.SIGNED_IDENTIFIERS_ELEMENT); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.SIGNED_IDENTIFIER_ELEMENT)) { - this.readSignedIdentifier(xmlr); - } - else if (eventType == XMLStreamConstants.END_ELEMENT - && name.equals(Constants.SIGNED_IDENTIFIERS_ELEMENT)) { - break; - } - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.SIGNED_IDENTIFIERS_ELEMENT); - } - - /** - * Reads a policy identifier / Shared Access Policy pair from the stream - * - * @param xmlr - * the XMLStreamReader to read from - * @throws XMLStreamException - * if an XMLStreamException occurs. - * @throws ParseException - * if a date is incorrectly encoded in the stream - */ - private void readSignedIdentifier(final XMLStreamReader xmlr) throws XMLStreamException, ParseException { - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.SIGNED_IDENTIFIER_ELEMENT); - - String id = null; - T policy = null; - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.ID)) { - id = Utility.readElementFromXMLReader(xmlr, Constants.ID); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.ACCESS_POLICY)) { - policy = this.readPolicyFromXML(xmlr); - } - else if (eventType == XMLStreamConstants.END_ELEMENT - && name.equals(Constants.SIGNED_IDENTIFIER_ELEMENT)) { - this.policies.put(id, policy); - break; - } - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.SIGNED_IDENTIFIER_ELEMENT); - } - - /** - * Populates the object from the XMLStreamReader, reader must be at Start element of AccessPolicy. - * - * @param xmlr - * the XMLStreamReader object - * @throws XMLStreamException - * if there is a parsing exception - * @throws ParseException - * if a date value is not correctly encoded - */ - protected abstract T readPolicyFromXML(final XMLStreamReader xmlr) throws XMLStreamException, ParseException; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AuthenticationScheme.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AuthenticationScheme.java deleted file mode 100644 index b2b8980550469..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/AuthenticationScheme.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Specifies the authentication scheme used to sign HTTP requests. - */ -public enum AuthenticationScheme { - /** - * Signs HTTP requests using the Shared Key Lite authentication scheme. - */ - SHAREDKEYLITE, - - /** - * Signs HTTP requests using the Shared Key authentication scheme. - */ - SHAREDKEYFULL; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/CloudStorageAccount.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/CloudStorageAccount.java deleted file mode 100644 index 7cd92741ca6a2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/CloudStorageAccount.java +++ /dev/null @@ -1,712 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map.Entry; - -import com.microsoft.windowsazure.services.blob.client.CloudBlobClient; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.queue.client.CloudQueueClient; -import com.microsoft.windowsazure.services.table.client.CloudTableClient; - -/** - * Represents a Windows Azure storage account. - */ -public final class CloudStorageAccount { - /** - * Represents the setting name for the account key. - */ - protected static final String ACCOUNT_KEY_NAME = "AccountKey"; - - /** - * Represents the setting name for the account name. - */ - protected static final String ACCOUNT_NAME_NAME = "AccountName"; - - /** - * The root blob storage DNS name. - */ - private static final String BLOB_BASE_DNS_NAME = "blob.core.windows.net"; - - /** - * Represents the setting name for a custom blob storage endpoint. - */ - protected static final String BLOB_ENDPOINT_NAME = "BlobEndpoint"; - - /** - * The setting name for using the default storage endpoints with the specified protocol. - */ - private static final String DEFAULT_ENDPOINTS_PROTOCOL_NAME = "DefaultEndpointsProtocol"; - - /** - * The setting name for specifying a development storage proxy Uri. - */ - private static final String DEVELOPMENT_STORAGE_PROXY_URI_NAME = "DevelopmentStorageProxyUri"; - /** - * The default account key for the development storage. - */ - private static final String DEVSTORE_ACCOUNT_KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; - - /** - * The default account name for the development storage. - */ - private static final String DEVSTORE_ACCOUNT_NAME = "devstoreaccount1"; - - /** - * The credentials string used to test for the development storage credentials. - */ - private static final String DEVSTORE_CREDENTIALS_IN_STRING = CloudStorageAccount.ACCOUNT_NAME_NAME + "=" - + CloudStorageAccount.DEVSTORE_ACCOUNT_NAME + ";" + CloudStorageAccount.ACCOUNT_KEY_NAME + "=" - + CloudStorageAccount.DEVSTORE_ACCOUNT_KEY; - - /** - * A CloudStorageAccount that represents the development storage account. - */ - private static CloudStorageAccount devStoreAccount; - - /** - * Represents the root queue DNS name. - */ - protected static final String QUEUE_BASE_DNS_NAME = "queue.core.windows.net"; - - /** - * Represents the setting name for a custom queue endpoint. - */ - protected static final String QUEUE_ENDPOINT_NAME = "QueueEndpoint"; - - /** - * Represents the setting name for a shared access key. - */ - protected static final String SHARED_ACCESS_SIGNATURE_NAME = "SharedAccessSignature"; - - /** - * Represents the root table storage DNS name. - */ - protected static final String TABLE_BASE_DNS_NAME = "table.core.windows.net"; - - /** - * Represents the setting name for a custom table storage endpoint. - */ - protected static final String TABLE_ENDPOINT_NAME = "TableEndpoint"; - - /** - * The setting name for using the development storage. - */ - private static final String USE_DEVELOPMENT_STORAGE_NAME = "UseDevelopmentStorage"; - - /** - * Gets the default blob endpoint using specified settings. - * - * @param settings - * The settings to use - * @return The default blob endpoint. - */ - private static String getDefaultBlobEndpoint(final HashMap settings) { - final String scheme = settings.get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME) != null ? settings - .get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME) : Constants.HTTP; - final String accountName = settings.get(CloudStorageAccount.ACCOUNT_NAME_NAME) != null ? settings - .get(CloudStorageAccount.ACCOUNT_NAME_NAME) : null; - - return getDefaultBlobEndpoint(scheme, accountName); - } - - /** - * Gets the default blob endpoint using the specified protocol and account name. - * - * @param scheme - * The protocol to use. - * @param accountName - * The name of the storage account. - * @return The default blob endpoint. - */ - private static String getDefaultBlobEndpoint(final String scheme, final String accountName) { - return String.format("%s://%s.%s", scheme, accountName, BLOB_BASE_DNS_NAME); - } - - /** - * Gets the default queue endpoint using the specified settings. - * - * @param settings - * The settings. - * @return The default queue endpoint. - */ - private static String getDefaultQueueEndpoint(final HashMap settings) { - final String scheme = settings.get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME) != null ? settings - .get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME) : Constants.HTTP; - - final String accountName = settings.get(CloudStorageAccount.ACCOUNT_NAME_NAME) != null ? settings - .get(CloudStorageAccount.ACCOUNT_NAME_NAME) : null; - - return getDefaultQueueEndpoint(scheme, accountName); - } - - /** - * Gets the default queue endpoint using the specified protocol and account name. - * - * @param scheme - * The protocol to use. - * @param accountName - * The name of the storage account. - * @return The default queue endpoint. - */ - private static String getDefaultQueueEndpoint(final String scheme, final String accountName) { - return String.format("%s://%s.%s", scheme, accountName, QUEUE_BASE_DNS_NAME); - } - - /** - * Gets the default table endpoint using the specified settings. - * - * @param settings - * The settings. - * @return The default table endpoint. - */ - private static String getDefaultTableEndpoint(final HashMap settings) { - final String scheme = settings.get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME) != null ? settings - .get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME) : Constants.HTTP; - final String accountName = settings.get(CloudStorageAccount.ACCOUNT_NAME_NAME) != null ? settings - .get(CloudStorageAccount.ACCOUNT_NAME_NAME) : null; - - return getDefaultTableEndpoint(scheme, accountName); - } - - /** - * Gets the default table endpoint using the specified protocol and account name. - * - * @param scheme - * The protocol to use. - * @param accountName - * The name of the storage account. - * @return The default table endpoint, - */ - private static String getDefaultTableEndpoint(final String scheme, final String accountName) { - return String.format("%s://%s.%s", scheme, accountName, TABLE_BASE_DNS_NAME); - } - - /** - * Returns a {@link CloudStorageAccount} object that represents the development storage credentials. - * - * @return A {@link CloudStorageAccount} object for the development storage credentials. - */ - public static CloudStorageAccount getDevelopmentStorageAccount() { - if (devStoreAccount == null) { - try { - devStoreAccount = getDevelopmentStorageAccount(new URI("http://127.0.0.1")); - } - catch (final URISyntaxException e) { - // this wont happen since we know the uri above. - } - } - return devStoreAccount; - } - - /** - * Returns a {@link CloudStorageAccount} object that represents the development storage credentials, using the - * specified proxy URI. - * - * @param proxyUri - * A java.net.URI object that represents the proxy endpoint to use. - * - * @return A {@link CloudStorageAccount} object for the development storage credentials. - * - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public static CloudStorageAccount getDevelopmentStorageAccount(final URI proxyUri) throws URISyntaxException { - if (proxyUri == null) { - return getDevelopmentStorageAccount(); - } - - String prefix = proxyUri.getScheme().concat("://"); - prefix = prefix.concat(proxyUri.getHost()); - - return new CloudStorageAccount( - new StorageCredentialsAccountAndKey(DEVSTORE_ACCOUNT_NAME, DEVSTORE_ACCOUNT_KEY), new URI( - prefix.concat(":10000/devstoreaccount1")), new URI(prefix.concat(":10001/devstoreaccount1")), - new URI(prefix.concat(":10002/devstoreaccount1"))); - - } - - /** - * Parses a connection string and returns a cloud storage account created from the connection string. - *

- * Note this method is not supported for shared access signature credentials as they do not contain the required - * endpoint configuration parameters. - * - * @param connectionString - * A String that represents the connection string to parse. - * - * @return A {@link CloudStorageAccount} object that represents the cloud storage account constructed from the - * values provided in the connection string. - * - * @throws InvalidKeyException - * If credentials in the connection string contain an invalid key. - * @throws URISyntaxException - * If the connection string specifies an invalid URI. - */ - public static CloudStorageAccount parse(final String connectionString) throws URISyntaxException, - InvalidKeyException { - if (connectionString == null || connectionString.length() == 0) { - throw new IllegalArgumentException("Invalid Connection String"); - } - - // 1. Parse connection string in to key / value pairs - final HashMap settings = Utility.parseAccountString(connectionString); - - // 2 Validate General Settings rules, - // - only setting value per key - // - setting must have value - for (final Entry entry : settings.entrySet()) { - if (entry.getValue() == null || entry.getValue().equals(Constants.EMPTY_STRING)) { - throw new IllegalArgumentException("Invalid Connection String"); - } - } - - // 3. Validate scenario specific constraints - CloudStorageAccount retVal = tryConfigureDevStore(settings); - if (retVal != null) { - return retVal; - } - - retVal = tryConfigureServiceAccount(settings); - if (retVal != null) { - return retVal; - } - - throw new IllegalArgumentException("Invalid Connection String"); - } - - /** - * Evaluates connection settings and returns a CloudStorageAccount representing Development Storage. - * - * @param settings - * A Hashmap of key value pairs representing the connection. - * @return A CloudStorageAccount object constructed from the values provided in the connection settings, or null if - * one cannot be constructed. - * @throws URISyntaxException - * if the connection settings contains an invalid URI - */ - private static CloudStorageAccount tryConfigureDevStore(final HashMap settings) - throws URISyntaxException { - if (settings.containsKey(USE_DEVELOPMENT_STORAGE_NAME)) { - final String useDevStoreSetting = settings.get(USE_DEVELOPMENT_STORAGE_NAME); - URI devStoreProxyUri = null; - - if (!Boolean.parseBoolean(useDevStoreSetting)) { - return null; - } - - if (settings.containsKey(DEVELOPMENT_STORAGE_PROXY_URI_NAME)) { - devStoreProxyUri = new URI(settings.get(DEVELOPMENT_STORAGE_PROXY_URI_NAME)); - } - - return getDevelopmentStorageAccount(devStoreProxyUri); - - } - else { - return null; - } - } - - /** - * Evaluates connection settings and configures a CloudStorageAccount accordingly. - * - * @param settings - * A Hashmap of key value pairs representing the connection. - * @return A CloudStorageAccount represented by the settings. - * @throws URISyntaxException - * if the connectionString specifies an invalid URI. - * @throws InvalidKeyException - * if credentials in the connection settings contain an invalid key. - */ - private static CloudStorageAccount tryConfigureServiceAccount(final HashMap settings) - throws URISyntaxException, InvalidKeyException { - - final String defaultEndpointSetting = settings.get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME) != null ? settings - .get(CloudStorageAccount.DEFAULT_ENDPOINTS_PROTOCOL_NAME).toLowerCase() : null; - - if (defaultEndpointSetting != null && !defaultEndpointSetting.equals(Constants.HTTP) - && !defaultEndpointSetting.equals(Constants.HTTPS)) { - return null; - } - - final StorageCredentials credentials = StorageCredentials.tryParseCredentials(settings); - final URI blobURI = settings.containsKey(CloudStorageAccount.BLOB_ENDPOINT_NAME) ? new URI( - settings.get(CloudStorageAccount.BLOB_ENDPOINT_NAME)) : null; - final URI queueURI = settings.containsKey(CloudStorageAccount.QUEUE_ENDPOINT_NAME) ? new URI( - settings.get(CloudStorageAccount.QUEUE_ENDPOINT_NAME)) : null; - final URI tableURI = settings.containsKey(CloudStorageAccount.TABLE_ENDPOINT_NAME) ? new URI( - settings.get(CloudStorageAccount.TABLE_ENDPOINT_NAME)) : null; - - if (credentials != null) { - // Automatic endpoint Case - if (defaultEndpointSetting != null && settings.containsKey(CloudStorageAccount.ACCOUNT_NAME_NAME) - && settings.containsKey(CloudStorageAccount.ACCOUNT_KEY_NAME)) { - return new CloudStorageAccount(credentials, blobURI == null ? new URI(getDefaultBlobEndpoint(settings)) - : blobURI, queueURI == null ? new URI(getDefaultQueueEndpoint(settings)) : queueURI, - tableURI == null ? new URI(getDefaultTableEndpoint(settings)) : tableURI); - } - - // Explicit endpoint Case - if (settings.containsKey(CloudStorageAccount.BLOB_ENDPOINT_NAME) - || settings.containsKey(CloudStorageAccount.QUEUE_ENDPOINT_NAME) - || settings.containsKey(CloudStorageAccount.TABLE_ENDPOINT_NAME)) { - return new CloudStorageAccount(credentials, blobURI, queueURI, tableURI); - } - } - - return null; - } - - /** - * The internal Blob endpoint. - */ - private final URI blobEndpoint; - - /** - * The internal Storage Credentials. - */ - private StorageCredentials credentials; - - /** - * The internal Queue endpoint. - */ - private final URI queueEndpoint; - - /** - * The internal Table endpoint. - */ - private final URI tableEndpoint; - - /** - * Creates an instance of the CloudStorageAccount class using the specified account credentials. - *

- * With this constructor, the CloudStorageAccount object is constructed using the default HTTP storage - * service endpoints. The default HTTP storage service endpoints are - * http://myaccount.blob.core.windows.net, - * http://myaccount.queue.core.windows.net, and - * http://myaccount.table.core.windows.net, where myaccount is the name of - * your storage account. - *

- * The credentials provided when constructing the CloudStorageAccount object are used to authenticate - * all further requests against resources that are accessed via the CloudStorageAccount object or a - * client object created from it. A client object may be a {@link CloudBlobClient} object. - * - * @param storageCredentials - * A {@link StorageCredentials} object that represents the storage credentials to use to authenticate - * this account. - * - * @throws URISyntaxException - * If storageCredentials specify an invalid account name. - */ - public CloudStorageAccount(final StorageCredentials storageCredentials) throws URISyntaxException { - this.credentials = storageCredentials; - - this.blobEndpoint = new URI(getDefaultBlobEndpoint(Constants.HTTP, this.credentials.getAccountName())); - - this.queueEndpoint = new URI(getDefaultQueueEndpoint(Constants.HTTP, this.credentials.getAccountName())); - - this.tableEndpoint = new URI(getDefaultTableEndpoint(Constants.HTTP, this.credentials.getAccountName())); - } - - /** - * Creates an instance of the CloudStorageAccount class using the specified account credentials and - * service endpoints. - *

- * Use this constructor to construct a CloudStorageAccount object using custom endpoints, in the case - * where you've configured a custom domain name for your storage account. - *

- * The credentials provided when constructing the CloudStorageAccount object are used to authenticate - * all further requests against resources that are accessed via the CloudStorageAccount object or a - * client object created from it. A client object may be a {@link CloudBlobClient} object. - * - * @param storageCredentials - * A {@link StorageCredentials} object that represents the storage credentials to use to authenticate - * this account. - * @param blobEndpoint - * A java.net.URI object that represents the Blob service endpoint. - * @param queueEndpoint - * A java.net.URI object that represents the Queue service endpoint. - * @param tableEndpoint - * A java.net.URI object that represents the Table service endpoint. - */ - public CloudStorageAccount(final StorageCredentials storageCredentials, final URI blobEndpoint, - final URI queueEndpoint, final URI tableEndpoint) { - this.credentials = storageCredentials; - this.blobEndpoint = blobEndpoint; - this.queueEndpoint = queueEndpoint; - this.tableEndpoint = tableEndpoint; - } - - /** - * Creates an instance of the CloudStorageAccount class using the specified account credentials and the - * default service endpoints, using HTTP or HTTPS as specified. - *

- * With this constructor, the CloudStorageAccount object is constructed using the default storage - * service endpoints. The default storage service endpoints are - * [http|https]://myaccount.blob.core.windows.net; - * [http|https]://myaccount.queue.core.windows.net; and - * [http|https]://myaccount.table.core.windows.net, where myaccount is the - * name of your storage account. Access to the cloud storage account may be via HTTP or HTTPS, as specified by the - * useHttps parameter. - *

- * The credentials provided when constructing the CloudStorageAccount object are used to authenticate - * all further requests against resources that are accessed via the CloudStorageAccount object or a - * client object created from it. A client object may be a {@link CloudBlobClient} object. - * - * @param storageCredentials - * A {@link StorageCredentialsAccountAndKey} object that represents the storage credentials to use to - * authenticate this account. - * @param useHttps - * true to use HTTPS to connect to the storage service endpoints; otherwise, - * false. - * - * @throws URISyntaxException - * If storageCredentials specify an invalid account name. - */ - - // In order to call another constructor the this() must be the first - // statement and cannot be wrapped with a try catch - // as such, the URI constructors could technically throw a - // URISyntaxException, but wont since we are using our internal default - // endpoints. - // We are forced to document the URISyntaxException as a throws, but it - // won't ever really happen. - - // Also eclipse's auto formatting below is horrible - public CloudStorageAccount(final StorageCredentialsAccountAndKey storageCredentials, final boolean useHttps) - throws URISyntaxException { - this(storageCredentials, new URI(getDefaultBlobEndpoint(useHttps ? Constants.HTTPS : Constants.HTTP, - storageCredentials.getAccountName())), new URI(getDefaultQueueEndpoint(useHttps ? Constants.HTTPS - : Constants.HTTP, storageCredentials.getAccountName())), new URI(getDefaultTableEndpoint( - useHttps ? Constants.HTTPS : Constants.HTTP, storageCredentials.getAccountName()))); - } - - /** - * Creates a new Blob service client. - * - * @return A {@link CloudBlobClient} that represents the cloud blob client. - * - */ - public CloudBlobClient createCloudBlobClient() { - if (this.getBlobEndpoint() == null) { - throw new IllegalArgumentException("No blob endpoint configured."); - } - - if (this.credentials == null) { - throw new IllegalArgumentException("No credentials provided."); - } - - if (!this.credentials.canCredentialsSignRequest()) { - throw new IllegalArgumentException("CloudBlobClient requires a credential that can sign request"); - } - return new CloudBlobClient(this.getBlobEndpoint(), this.getCredentials()); - } - - /** - * Creates a new queue service client. - * - * @return A client object that uses the Queue service endpoint. - */ - public CloudQueueClient createCloudQueueClient() { - if (this.getQueueEndpoint() == null) { - throw new IllegalArgumentException("No queue endpoint configured."); - } - - if (this.credentials == null) { - throw new IllegalArgumentException("No credentials provided."); - } - - if (!this.credentials.canCredentialsSignRequest()) { - throw new IllegalArgumentException("CloudQueueClient requires a credential that can sign request"); - } - return new CloudQueueClient(this.getQueueEndpoint(), this.getCredentials()); - } - - /** - * Creates a new table service client. - * - * @return A client object that uses the Table service endpoint. - */ - public CloudTableClient createCloudTableClient() { - if (this.getTableEndpoint() == null) { - throw new IllegalArgumentException("No table endpoint configured."); - } - - if (this.credentials == null) { - throw new IllegalArgumentException("No credentials provided."); - } - - if (!this.credentials.canCredentialsSignRequest()) { - throw new IllegalArgumentException("CloudTableClient requires a credential that can sign request"); - } - return new CloudTableClient(this.getTableEndpoint(), this.getCredentials()); - } - - /** - * Returns the endpoint for the Blob service, as configured for the storage account. This method is not supported - * when using shared access signature credentials. - * - * @return A java.net.URI object that represents the blob endpoint associated with this account. - */ - public URI getBlobEndpoint() { - if (this.getCredentials() instanceof StorageCredentialsSharedAccessSignature) { - throw new IllegalArgumentException( - "Endpoint information not available for Account using Shared Access Credentials."); - } - - return this.blobEndpoint; - } - - /** - * Returns the credentials for the Blob service, as configured for the storage account. - * - * @return A {@link StorageCredentials} object that represents the credentials for this storage account. - */ - public StorageCredentials getCredentials() { - return this.credentials; - } - - /** - * Returns the endpoint for the Queue service, as configured for the storage account. - * - * @return A java.net.URI object that represents the queue endpoint associated with this account. - */ - public URI getQueueEndpoint() { - if (this.getCredentials() instanceof StorageCredentialsSharedAccessSignature) { - throw new IllegalArgumentException( - "Endpoint information not available for Account using Shared Access Credentials."); - } - - return this.queueEndpoint; - } - - /** - * Returns the endpoint for the table service, as configured for the storage account. - * - * @return A java.net.URI object that represents the table endpoint associated with this account. - */ - public URI getTableEndpoint() { - if (this.getCredentials() instanceof StorageCredentialsSharedAccessSignature) { - throw new IllegalArgumentException( - "Endpoint information not available for Account using Shared Access Credentials."); - } - - return this.tableEndpoint; - } - - // - // Sets the StorageCredentials to use with this account. Warning internal - // use only, updating the credentials to a new account can potentially - // invalidate a bunch of pre-existingobjects. - // - // @param credentials - // the credentials to set - // - /** - * Reserved for internal use. - * - * @param credentials - * Reserved. - */ - protected void setCredentials(final StorageCredentials credentials) { - this.credentials = credentials; - } - - /** - * Returns a connection string for this storage account, without sensitive data. - * - * @return A String that represents the connection string for this storage account, without sensitive - * data. - */ - @Override - public String toString() { - return this.toString(false); - } - - /** - * Returns a connection string for this storage account, optionally with sensitive data. - * - * @return A String that represents the connection string for this storage account, optionally with - * sensitive data. - * @param exportSecrets - * true to include sensitive data in the string; otherwise, false. - */ - public String toString(final boolean exportSecrets) { - if (this.credentials != null && Utility.isNullOrEmpty(this.credentials.getAccountName())) { - return this.credentials.toString(exportSecrets); - } - - final ArrayList retVals = new ArrayList(); - if (this == devStoreAccount) { - retVals.add(String.format("%s=true", USE_DEVELOPMENT_STORAGE_NAME)); - } - else if (this.credentials != null && DEVSTORE_ACCOUNT_NAME.equals(this.credentials.getAccountName()) - && this.credentials.toString(true).equals(CloudStorageAccount.DEVSTORE_CREDENTIALS_IN_STRING) - && this.blobEndpoint != null - && this.getBlobEndpoint().getHost().equals(this.getQueueEndpoint().getHost()) - && this.getQueueEndpoint().getHost().equals(this.getTableEndpoint().getHost()) - && this.getBlobEndpoint().getScheme().equals(this.getQueueEndpoint().getScheme()) - && this.getQueueEndpoint().getScheme().equals(this.getTableEndpoint().getScheme())) { - retVals.add(String.format("%s=true", USE_DEVELOPMENT_STORAGE_NAME)); - retVals.add(String.format("%s=%s://%s", DEVELOPMENT_STORAGE_PROXY_URI_NAME, this.getBlobEndpoint() - .getScheme(), this.getBlobEndpoint().getHost())); - } - else if (this.getBlobEndpoint().getHost().endsWith(BLOB_BASE_DNS_NAME) - && this.getQueueEndpoint().getHost().endsWith(QUEUE_BASE_DNS_NAME) - && this.getTableEndpoint().getHost().endsWith(TABLE_BASE_DNS_NAME) - && this.getBlobEndpoint().getScheme().equals(this.getQueueEndpoint().getScheme()) - && this.getQueueEndpoint().getScheme().equals(this.getTableEndpoint().getScheme())) { - retVals.add(String.format("%s=%s", DEFAULT_ENDPOINTS_PROTOCOL_NAME, this.getBlobEndpoint().getScheme())); - if (this.getCredentials() != null) { - retVals.add(this.getCredentials().toString(exportSecrets)); - } - } - else { - if (this.getBlobEndpoint() != null) { - retVals.add(String.format("%s=%s", BLOB_ENDPOINT_NAME, this.getBlobEndpoint())); - } - - if (this.getQueueEndpoint() != null) { - retVals.add(String.format("%s=%s", QUEUE_ENDPOINT_NAME, this.getQueueEndpoint())); - } - - if (this.getTableEndpoint() != null) { - retVals.add(String.format("%s=%s", TABLE_ENDPOINT_NAME, this.getTableEndpoint())); - } - - if (this.getCredentials() != null) { - retVals.add(this.getCredentials().toString(exportSecrets)); - } - } - - final StringBuilder returnString = new StringBuilder(); - for (final String val : retVals) { - returnString.append(val); - returnString.append(';'); - } - - // Remove trailing ';' - if (retVals.size() > 0) { - returnString.deleteCharAt(returnString.length() - 1); - } - - return returnString.toString(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/Constants.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/Constants.java deleted file mode 100644 index a1454cf02d81a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/Constants.java +++ /dev/null @@ -1,670 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Defines constants for use with blob operations, HTTP headers, and query strings. - */ -public final class Constants { - /** - * Defines constants for use Analytics requests. - */ - public static class AnalyticsConstants { - /** - * The XML element for the Analytics RetentionPolicy Days. - */ - public static final String DAYS_ELEMENT = "Days"; - - /** - * The XML element for the Default Service Version. - */ - public static final String DEFAULT_SERVICE_VERSION = "DefaultServiceVersion"; - - /** - * The XML element for the Analytics Logging Delete type. - */ - public static final String DELETE_ELEMENT = "Delete"; - - /** - * The XML element for the Analytics RetentionPolicy Enabled. - */ - public static final String ENABLED_ELEMENT = "Enabled"; - - /** - * The XML element for the Analytics Metrics IncludeAPIs. - */ - public static final String INCLUDE_APIS_ELEMENT = "IncludeAPIs"; - - /** - * The XML element for the Analytics Logging - */ - public static final String LOGGING_ELEMENT = "Logging"; - - /** - * The XML element for the Analytics Metrics - */ - public static final String METRICS_ELEMENT = "Metrics"; - - /** - * The XML element for the Analytics Logging Read type. - */ - public static final String READ_ELEMENT = "Read"; - - /** - * The XML element for the Analytics RetentionPolicy. - */ - public static final String RETENTION_POLICY_ELEMENT = "RetentionPolicy"; - - /** - * The XML element for the StorageServiceProperties - */ - public static final String STORAGE_SERVICE_PROPERTIES_ELEMENT = "StorageServiceProperties"; - - /** - * The XML element for the Analytics Version - */ - public static final String VERSION_ELEMENT = "Version"; - - /** - * The XML element for the Analytics Logging Write type. - */ - public static final String WRITE_ELEMENT = "Write"; - } - - /** - * Defines constants for use with HTTP headers. - */ - public static class HeaderConstants { - /** - * The Accept header. - */ - public static final String ACCEPT = "Accept"; - - /** - * The Accept header. - */ - public static final String ACCEPT_CHARSET = "Accept-Charset"; - - /** - * The Authorization header. - */ - public static final String AUTHORIZATION = "Authorization"; - - /** - * The CacheControl header. - */ - public static final String CACHE_CONTROL = "Cache-Control"; - - /** - * The header that specifies blob caching control. - */ - public static final String CACHE_CONTROL_HEADER = PREFIX_FOR_STORAGE_HEADER + "blob-cache-control"; - - /** - * The Comp value. - */ - public static final String COMP = "comp"; - - /** - * The ContentEncoding header. - */ - public static final String CONTENT_ENCODING = "Content-Encoding"; - - /** - * The ContentLangauge header. - */ - public static final String CONTENT_LANGUAGE = "Content-Language"; - - /** - * The ContentLength header. - */ - public static final String CONTENT_LENGTH = "Content-Length"; - - /** - * The ContentMD5 header. - */ - public static final String CONTENT_MD5 = "Content-MD5"; - - /** - * The ContentRange header. - */ - public static final String CONTENT_RANGE = "Cache-Range"; - - /** - * The ContentType header. - */ - public static final String CONTENT_TYPE = "Content-Type"; - - /** - * The header for copy source. - */ - public static final String COPY_SOURCE_HEADER = PREFIX_FOR_STORAGE_HEADER + "copy-source"; - - /** - * The header that specifies the date. - */ - public static final String DATE = PREFIX_FOR_STORAGE_HEADER + "date"; - - /** - * The header to delete snapshots. - */ - public static final String DELETE_SNAPSHOT_HEADER = PREFIX_FOR_STORAGE_HEADER + "delete-snapshots"; - - /** - * The ETag header. - */ - public static final String ETAG = "ETag"; - - /** - * Buffer width used to copy data to output streams. - */ - public static final int HTTP_UNUSED_306 = 306; - - /** - * The IfMatch header. - */ - public static final String IF_MATCH = "If-Match"; - - /** - * The IfModifiedSince header. - */ - public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; - - /** - * The IfNoneMatch header. - */ - public static final String IF_NONE_MATCH = "If-None-Match"; - - /** - * The IfUnmodifiedSince header. - */ - public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; - - /** - * The header that specifies lease ID. - */ - public static final String LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + "lease-id"; - - /** - * The header that specifies lease status. - */ - public static final String LEASE_STATUS = PREFIX_FOR_STORAGE_HEADER + "lease-status"; - - /** - * The header that specifies lease state. - */ - public static final String LEASE_STATE = PREFIX_FOR_STORAGE_HEADER + "lease-state"; - - /** - * The header that specifies lease duration. - */ - public static final String LEASE_DURATION = PREFIX_FOR_STORAGE_HEADER + "lease-duration"; - - /** - * The header that specifies copy status. - */ - public static final String COPY_STATUS = PREFIX_FOR_STORAGE_HEADER + "copy-status"; - - /** - * The header that specifies copy progress. - */ - public static final String COPY_PROGRESS = PREFIX_FOR_STORAGE_HEADER + "copy-progress"; - - /** - * The header that specifies copy status description. - */ - public static final String COPY_STATUS_DESCRIPTION = PREFIX_FOR_STORAGE_HEADER + "copy-status-description"; - - /** - * The header that specifies copy id. - */ - public static final String COPY_ID = PREFIX_FOR_STORAGE_HEADER + "copy-id"; - - /** - * The header that specifies copy source. - */ - public static final String COPY_SOURCE = PREFIX_FOR_STORAGE_HEADER + "copy-source"; - - /** - * The header that specifies copy completion time. - */ - public static final String COPY_COMPLETION_TIME = PREFIX_FOR_STORAGE_HEADER + "copy-completion-time"; - - /** - * The header prefix for metadata. - */ - public static final String PREFIX_FOR_STORAGE_METADATA = "x-ms-meta-"; - - /** - * The header prefix for properties. - */ - public static final String PREFIX_FOR_STORAGE_PROPERTIES = "x-ms-prop-"; - - /** - * The Range header. - */ - public static final String RANGE = "Range"; - - /** - * The header that specifies if the request will populate the ContentMD5 header for range gets. - */ - public static final String RANGE_GET_CONTENT_MD5 = PREFIX_FOR_STORAGE_HEADER + "range-get-content-md5"; - - /** - * The format string for specifying ranges. - */ - public static final String RANGE_HEADER_FORMAT = "bytes=%d-%d"; - - /** - * The header that indicates the request ID. - */ - public static final String REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + "request-id"; - - /** - * The header that indicates the client request ID. - */ - public static final String CLIENT_REQUEST_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + "client-request-id"; - - /** - * The header for the If-Match condition. - */ - public static final String SOURCE_IF_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + "source-if-match"; - - /** - * The header for the If-Modified-Since condition. - */ - public static final String SOURCE_IF_MODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER - + "source-if-modified-since"; - - /** - * The header for the If-None-Match condition. - */ - public static final String SOURCE_IF_NONE_MATCH_HEADER = PREFIX_FOR_STORAGE_HEADER + "source-if-none-match"; - - /** - * The header for the If-Unmodified-Since condition. - */ - public static final String SOURCE_IF_UNMODIFIED_SINCE_HEADER = PREFIX_FOR_STORAGE_HEADER - + "source-if-unmodified-since"; - - /** - * The header for the source lease id. - */ - public static final String SOURCE_LEASE_ID_HEADER = PREFIX_FOR_STORAGE_HEADER + "source-lease-id"; - - /** - * The header for data ranges. - */ - public static final String STORAGE_RANGE_HEADER = PREFIX_FOR_STORAGE_HEADER + "range"; - - /** - * The header for storage version. - */ - public static final String STORAGE_VERSION_HEADER = PREFIX_FOR_STORAGE_HEADER + "version"; - - /** - * The current storage version header value. - */ - public static final String TARGET_STORAGE_VERSION = "2012-02-12"; - - /** - * The UserAgent header. - */ - public static final String USER_AGENT = "User-Agent"; - - /** - * Specifies the value to use for UserAgent header. - */ - public static final String USER_AGENT_PREFIX = "WA-Storage"; - - /** - * Specifies the value to use for UserAgent header. - */ - public static final String USER_AGENT_VERSION = "Client v0.1.3.2"; - } - - /** - * Defines constants for use with query strings. - */ - public static class QueryConstants { - /** - * The query component for the SAS signature. - */ - public static final String SIGNATURE = "sig"; - - /** - * The query component for the signed SAS expiry time. - */ - public static final String SIGNED_EXPIRY = "se"; - - /** - * The query component for the signed SAS identifier. - */ - public static final String SIGNED_IDENTIFIER = "si"; - - /** - * The query component for the signed SAS permissions. - */ - public static final String SIGNED_PERMISSIONS = "sp"; - - /** - * The query component for the signed SAS resource. - */ - public static final String SIGNED_RESOURCE = "sr"; - - /** - * The query component for the signed SAS start time. - */ - public static final String SIGNED_START = "st"; - - /** - * The query component for the SAS start partition key. - */ - public static final String START_PARTITION_KEY = "spk"; - - /** - * The query component for the SAS start row key. - */ - public static final String START_ROW_KEY = "srk"; - - /** - * The query component for the SAS end partition key. - */ - public static final String END_PARTITION_KEY = "epk"; - - /** - * The query component for the SAS end row key. - */ - public static final String END_ROW_KEY = "erk"; - - /** - * The query component for the SAS table name. - */ - public static final String SAS_TABLE_NAME = "tn"; - - /** - * The query component for the signing SAS key. - */ - public static final String SIGNED_KEY = "sk"; - - /** - * The query component for the signed SAS version. - */ - public static final String SIGNED_VERSION = "sv"; - - /** - * The query component for snapshot time. - */ - public static final String SNAPSHOT = "snapshot"; - } - - /** - * The master Windows Azure Storage header prefix. - */ - public static final String PREFIX_FOR_STORAGE_HEADER = "x-ms-"; - - /** - * Constant representing a kilobyte (Non-SI version). - */ - public static final int KB = 1024; - - /** - * Constant representing a megabyte (Non-SI version). - */ - public static final int MB = 1024 * KB; - - /** - * Constant representing a gigabyte (Non-SI version). - */ - public static final int GB = 1024 * MB; - - /** - * Buffer width used to copy data to output streams. - */ - public static final int BUFFER_COPY_LENGTH = 8 * KB; - - /** - * Default client side timeout, in milliseconds, for all service clients. - */ - public static final int DEFAULT_TIMEOUT_IN_MS = 90 * 1000; - - /** - * XML element for delimiters. - */ - public static final String DELIMITER_ELEMENT = "Delimiter"; - - /** - * An empty String to use for comparison. - */ - public static final String EMPTY_STRING = ""; - - /** - * XML element for page range end elements. - */ - public static final String END_ELEMENT = "End"; - - /** - * XML element for error codes. - */ - public static final String ERROR_CODE = "Code"; - - /** - * XML element for exception details. - */ - public static final String ERROR_EXCEPTION = "ExceptionDetails"; - - /** - * XML element for exception messages. - */ - public static final String ERROR_EXCEPTION_MESSAGE = "ExceptionMessage"; - - /** - * XML element for stack traces. - */ - public static final String ERROR_EXCEPTION_STACK_TRACE = "StackTrace"; - - /** - * XML element for error messages. - */ - public static final String ERROR_MESSAGE = "Message"; - - /** - * XML root element for errors. - */ - public static final String ERROR_ROOT_ELEMENT = "Error"; - - /** - * XML element for the ETag. - */ - public static final String ETAG_ELEMENT = "Etag"; - - /** - * Constant for False. - */ - public static final String FALSE = "false"; - - /** - * Specifies HTTP. - */ - public static final String HTTP = "http"; - - /** - * Specifies HTTPS. - */ - public static final String HTTPS = "https"; - - /** - * XML attribute for IDs. - */ - public static final String ID = "Id"; - - /** - * XML element for an invalid metadata name. - */ - public static final String INVALID_METADATA_NAME = "x-ms-invalid-name"; - - /** - * XML element for the last modified date. - */ - public static final String LAST_MODIFIED_ELEMENT = "Last-Modified"; - - /** - * XML element for the lease status. - */ - public static final String LEASE_STATUS_ELEMENT = "LeaseStatus"; - - /** - * XML element for the lease state. - */ - public static final String LEASE_STATE_ELEMENT = "LeaseState"; - - /** - * XML element for the lease duration. - */ - public static final String LEASE_DURATION_ELEMENT = "LeaseDuration"; - - /** - * XML element for the copy id. - */ - public static final String COPY_ID_ELEMENT = "CopyId"; - - /** - * XML element for the copy status. - */ - public static final String COPY_STATUS_ELEMENT = "CopyStatus"; - - /** - * XML element for the copy source . - */ - public static final String COPY_SOURCE_ELEMENT = "CopySource"; - - /** - * XML element for the copy progress. - */ - public static final String COPY_PROGRESS_ELEMENT = "CopyProgress"; - - /** - * XML element for the copy completion time. - */ - public static final String COPY_COMPLETION_TIME_ELEMENT = "CopyCompletionTime"; - - /** - * XML element for the copy status description. - */ - public static final String COPY_STATUS_DESCRIPTION_ELEMENT = "CopyStatusDescription"; - - /** - * Constant signaling the resource is locked. - */ - public static final String LOCKED_VALUE = "Locked"; - - /** - * XML element for a marker. - */ - public static final String MARKER_ELEMENT = "Marker"; - - /** - * XML element for maximum results. - */ - public static final String MAX_RESULTS_ELEMENT = "MaxResults"; - - /** - * Number of default concurrent requests for parallel operation. - */ - public static final int MAXIMUM_SEGMENTED_RESULTS = 5000; - - /** - * The maximum size, in bytes, of a given stream mark operation. - */ - // Note if BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES is updated then this needs to be as well. - public static final int MAX_MARK_LENGTH = 64 * MB; - - /** - * XML element for the metadata. - */ - public static final String METADATA_ELEMENT = "Metadata"; - - /** - * XML element for names. - */ - public static final String NAME_ELEMENT = "Name"; - - /** - * XML element for the next marker. - */ - public static final String NEXT_MARKER_ELEMENT = "NextMarker"; - - /** - * XML element for a prefix. - */ - public static final String PREFIX_ELEMENT = "Prefix"; - - /** - * Constant for True. - */ - public static final String TRUE = "true"; - - /** - * Constant signaling the resource is unlocked. - */ - public static final String UNLOCKED_VALUE = "Unlocked"; - - /** - * XML element for the URL. - */ - public static final String URL_ELEMENT = "Url"; - - /** - * XML element for a signed identifier. - */ - public static final String SIGNED_IDENTIFIER_ELEMENT = "SignedIdentifier"; - - /** - * XML element for signed identifiers. - */ - public static final String SIGNED_IDENTIFIERS_ELEMENT = "SignedIdentifiers"; - - /** - * XML element for an access policy. - */ - public static final String ACCESS_POLICY = "AccessPolicy"; - - /** - * Maximum number of shared access policy identifiers supported by server. - */ - public static final int MAX_SHARED_ACCESS_POLICY_IDENTIFIERS = 5; - - /** - * XML element for the start time of an access policy. - */ - public static final String START = "Start"; - - /** - * XML element for the end time of an access policy. - */ - public static final String EXPIRY = "Expiry"; - - /** - * XML element for the permission of an access policy. - */ - public static final String PERMISSION = "Permission"; - - /** - * Private Default Ctor - */ - private Constants() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/Credentials.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/Credentials.java deleted file mode 100644 index db537f5414f7b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/Credentials.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.core.storage; - -import com.microsoft.windowsazure.services.core.storage.utils.Base64; - -/** - * Represents the credentials used to sign a request against the storage services. - */ -public final class Credentials { - /** - * Stores the Account name for the credentials. - */ - private String accountName; - - /** - * Stores the StorageKey for the credentials. - */ - private final StorageKey key; - - /** - * Stores the name of the access key to be used when signing the request. - */ - private String keyName; - - /** - * Stores the account name whose key is used to sign requests. - */ - private String signingAccountName; - - /** - * Creates an instance of the Credentials class, using the specified storage account name and access - * key; the specified access key is in the form of a byte array. - * - * @param accountName - * A String that represents the name of the storage account. - * @param key - * An array of bytes that represent the account access key. - * - */ - public Credentials(final String accountName, final byte[] key) { - if (accountName == null || accountName.length() == 0) { - throw new IllegalArgumentException("Invalid accountName"); - } - - if (key == null) { - throw new IllegalArgumentException("Invalid key"); - } - - this.accountName = accountName; - this.key = new StorageKey(key); - this.signingAccountName = accountName; - } - - /** - * Creates an instance of the Credentials class, using the specified storage account name and access - * key; the specified access key is stored as a String. - * - * @param accountName - * A String that represents the name of the storage account. - * @param key - * A String that represents the Base-64-encoded account access key. - * - */ - public Credentials(final String accountName, final String key) { - this(accountName, Base64.decode(key)); - } - - /** - * Exports the value of the access key to a Base64-encoded string. - * - * @return A String that represents the Base64-encoded access key. - */ - public String exportBase64EncodedKey() { - return this.getKey().getBase64EncodedKey(); - } - - /** - * Exports the value of the access key to an array of bytes. - * - * @return A byte array that represents the access key. - */ - public byte[] exportKey() { - return this.getKey().getKey(); - } - - /** - * Returns the account name to be used in signing the request. - * - * @return A String that represents the account name to be used in signing the request. - */ - public String getAccountName() { - return this.accountName; - } - - /** - * Returns the account name whose key is used to sign requests. - * Internal use only. - */ - public String getSigningAccountName() { - return this.signingAccountName; - } - - /** - * Returns the name of the access key to be used when signing the request. - * Internal use only. - */ - public String getKeyName() { - return this.keyName; - } - - /** - * Returns the access key to be used in signing the request. - * - * @return A String that represents the access key to be used in signing the request. - */ - public StorageKey getKey() { - return this.key; - } - - /** - * Sets the account name to be used in signing the request. - * - * @param accountName - * A String that represents the account name being set. - */ - protected void setAccountName(final String accountName) { - this.accountName = accountName; - } - - /** - * Sets the account name whose key is used to sign requests. - * - * @param signingAccountName - * A String that represents the account name whose key is used to sign requests. - */ - protected void setSigningAccountName(final String signingAccountName) { - this.signingAccountName = signingAccountName; - } - - /** - * Sets the name of the access key to be used when signing the request. - * - * @param keyName - * A String that represents the name of the access key to be used when signing the request. - */ - protected void setKeyName(final String keyName) { - this.keyName = keyName; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/DoesServiceRequest.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/DoesServiceRequest.java deleted file mode 100644 index 5bdcef196e7b3..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/DoesServiceRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.core.storage; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * An attribute used to describe a method that will make a request to the storage service. - */ -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface DoesServiceRequest { - // No attributes -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseDuration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseDuration.java deleted file mode 100644 index aef43c07da4b9..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseDuration.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.util.Locale; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * The lease duration of a resource. - */ -public enum LeaseDuration { - /** - * The lease duration is not specified. - */ - UNSPECIFIED, - - /** - * The lease duration is finite. - */ - FIXED, - - /** - * The lease duration is infinite. - */ - INFINITE; - - /** - * Parses a lease duration from the specified string. - * - * @param typeString - * The string to parse. - * - * @return A LeaseStatus value that represents the lease status. - */ - public static LeaseDuration parse(final String typeString) { - if (Utility.isNullOrEmpty(typeString)) { - return UNSPECIFIED; - } - else if ("fixed".equals(typeString.toLowerCase(Locale.US))) { - return FIXED; - } - else if ("infinite".equals(typeString.toLowerCase(Locale.US))) { - return INFINITE; - } - else { - return UNSPECIFIED; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseState.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseState.java deleted file mode 100644 index 39d192bffaffa..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseState.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.util.Locale; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * The lease state of a resource. - */ -public enum LeaseState { - /** - * The lease state is not specified. - */ - UNSPECIFIED, - - /** - * The lease is in the Available state. - */ - AVAILABLE, - - /** - * The lease is in the Leased state. - */ - LEASED, - - /** - * The lease is in the Expired state. - */ - EXPIRED, - - /** - * The lease is in the Breaking state. - */ - BREAKING, - - /** - * The lease is in the Broken state. - */ - BROKEN; - - /** - * Parses a lease status from the given string. - * - * @param typeString - * The string to parse. - * - * @return A LeaseStatus value that represents the lease status. - */ - public static LeaseState parse(final String typeString) { - if (Utility.isNullOrEmpty(typeString)) { - return UNSPECIFIED; - } - else if ("available".equals(typeString.toLowerCase(Locale.US))) { - return AVAILABLE; - } - else if ("locked".equals(typeString.toLowerCase(Locale.US))) { - return LEASED; - } - else if ("expired".equals(typeString.toLowerCase(Locale.US))) { - return EXPIRED; - } - else if ("breaking".equals(typeString.toLowerCase(Locale.US))) { - return BREAKING; - } - else if ("broken".equals(typeString.toLowerCase(Locale.US))) { - return BROKEN; - } - else { - return UNSPECIFIED; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseStatus.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseStatus.java deleted file mode 100644 index 15907a936e628..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LeaseStatus.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.util.Locale; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Specifies the lease status of a blob. - *

- * You can check the lease status of a blob to determine whether it currently has an active lease (locked for - * exclusive-write access), or whether it is available for exclusive-write access. - */ -public enum LeaseStatus { - /** - * Specifies the lease status is not specified. - */ - UNSPECIFIED, - - /** - * Specifies the blob is locked for exclusive-write access. - */ - LOCKED, - - /** - * Specifies the blob is available to be locked for exclusive-write access. - */ - UNLOCKED; - - /** - * Parses a lease status from the given string. - * - * @param typeString - * A String that represents the string to parse. - * - * @return A LeaseStatus value that represents the lease status. - */ - public static LeaseStatus parse(final String typeString) { - if (Utility.isNullOrEmpty(typeString)) { - return UNSPECIFIED; - } - else if ("unlocked".equals(typeString.toLowerCase(Locale.US))) { - return UNLOCKED; - } - else if ("locked".equals(typeString.toLowerCase(Locale.US))) { - return LOCKED; - } - else { - return UNSPECIFIED; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LoggingOperations.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LoggingOperations.java deleted file mode 100644 index c862b68985185..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LoggingOperations.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * - * Specifies which types of operations the service should log. - */ -public enum LoggingOperations { - /** - * Log Read Operations . - */ - READ, - - /** - * Log Write Operations. - */ - WRITE, - - /** - * Log Delete Operations. - */ - DELETE; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LoggingProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LoggingProperties.java deleted file mode 100644 index 5051456009104..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/LoggingProperties.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.util.EnumSet; - -/** - * Represents the logging properties for the analytics service. - */ -public final class LoggingProperties { - - /** - * The analytics version to use. - */ - private String version = "1.0"; - - /** - * A EnumSet of LoggingOperationTypes that represent which storage operations should be logged. - */ - private EnumSet logOperationTypes = EnumSet.noneOf(LoggingOperations.class); - - /** - * The Retention policy for the logging data. - */ - private Integer retentionIntervalInDays; - - /** - * @return the logOperationTypes - */ - public EnumSet getLogOperationTypes() { - return this.logOperationTypes; - } - - /** - * @return the retentionIntervalInDays - */ - public Integer getRetentionIntervalInDays() { - return this.retentionIntervalInDays; - } - - /** - * @return the version - */ - public String getVersion() { - return this.version; - } - - /** - * @param logOperationTypes - * the logOperationTypes to set - */ - public void setLogOperationTypes(final EnumSet logOperationTypes) { - this.logOperationTypes = logOperationTypes; - } - - /** - * @param retentionIntervalInDays - * the retentionIntervalInDays to set - */ - public void setRetentionIntervalInDays(final Integer retentionIntervalInDays) { - this.retentionIntervalInDays = retentionIntervalInDays; - } - - /** - * @param version - * the version to set - */ - public void setVersion(final String version) { - this.version = version; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/MetricsLevel.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/MetricsLevel.java deleted file mode 100644 index b702b05e4f0c1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/MetricsLevel.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Enumeration representing the state of metrics collection in a service. - */ -public enum MetricsLevel { - /** - * Metrics collection is disabled. - */ - DISABLED, - - /** - * Service-level metrics collection is enabled. - */ - SERVICE, - - /** - * Service-level and API metrics collection are enabled. - */ - SERVICE_AND_API; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/MetricsProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/MetricsProperties.java deleted file mode 100644 index e703379a73c0e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/MetricsProperties.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents the metrics properties for the analytics service. - */ -public final class MetricsProperties { - /** - * The analytics version to use. - */ - private String version = "1.0"; - - /** - * A {@link MetricsLevel} level used to enable Metric and API logging - */ - private MetricsLevel metricsLevel = com.microsoft.windowsazure.services.core.storage.MetricsLevel.DISABLED; - - /** - * The Retention policy for the Metrics data. - */ - private Integer retentionIntervalInDays; - - /** - * @return the metricsLevel - */ - public MetricsLevel getMetricsLevel() { - return this.metricsLevel; - } - - /** - * @return the retentionIntervalInDays - */ - public Integer getRetentionIntervalInDays() { - return this.retentionIntervalInDays; - } - - /** - * @return the version - */ - public String getVersion() { - return this.version; - } - - /** - * @param metricsLevel - * the metricsLevel to set - */ - public void setMetricsLevel(final MetricsLevel metricsLevel) { - this.metricsLevel = metricsLevel; - } - - /** - * @param retentionIntervalInDays - * the retentionIntervalInDays to set - */ - public void setRetentionIntervalInDays(final Integer retentionIntervalInDays) { - this.retentionIntervalInDays = retentionIntervalInDays; - } - - /** - * @param version - * the version to set - */ - public void setVersion(final String version) { - this.version = version; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/OperationContext.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/OperationContext.java deleted file mode 100644 index f502cf36229b6..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/OperationContext.java +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.HttpURLConnection; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.UUID; -import java.util.logging.Logger; - -/** - * Represents the current logical operation. A logical operation has potentially a one-to-many relationship with - * individual physical requests. - */ -public final class OperationContext { - - /** - * Represents the operation latency, in milliseconds, from the client's perspective. This may include any potential - * retries. - */ - private long clientTimeInMs; - - /** - * The UUID representing the client side trace ID. - */ - private String clientRequestID; - - /** - * The Logger object associated with this operation. - */ - private Logger logger; - - /** - * Represents request results, in the form of an ArrayList object that contains the - * {@link RequestResult} objects, for each physical request that is made. - */ - private final ArrayList requestResults; - - /** - * Represents an event that is triggered before sending a request. - * - * @see StorageEvent - * @see StorageEventMultiCaster - * @see SendingRequestEvent - */ - private StorageEventMultiCaster> sendingRequestEventHandler = new StorageEventMultiCaster>(); - - /** - * Represents an event that is triggered when a response is received from the storage service while processing a - * request. - * - * @see StorageEvent - * @see StorageEventMultiCaster - * @see ResponseReceivedEvent - */ - private StorageEventMultiCaster> responseReceivedEventHandler = new StorageEventMultiCaster>(); - - /** - * Reserved for internal use. - */ - // Represents the intermediate MD5 value, which is used in resuming downloads. - private MessageDigest intermediateMD5; - - /** - * Reserved for internal use. Represents the current request object, which is used in continuation. - */ - private HttpURLConnection currentRequestObject; - - /** - * Represents the current operation state object. - */ - protected Object operationState; - - /** - * Reserved for internal use. - */ - // Used internally for download resume. - private volatile long currentOperationByteCount; - - /** - * Creates an instance of the OperationContext class. - */ - public OperationContext() { - this.clientRequestID = UUID.randomUUID().toString(); - this.requestResults = new ArrayList(); - } - - /** - * @return the clientRequestID - */ - public String getClientRequestID() { - return this.clientRequestID; - } - - /** - * @return the clientTimeInMs - */ - public long getClientTimeInMs() { - return this.clientTimeInMs; - } - - /** - * @return the currentOperationByteCount - */ - public long getCurrentOperationByteCount() { - return this.currentOperationByteCount; - } - - /** - * @return the currentRequestObject - */ - public HttpURLConnection getCurrentRequestObject() { - return this.currentRequestObject; - } - - /** - * @return the intermediateMD5 - */ - public MessageDigest getIntermediateMD5() { - return this.intermediateMD5; - } - - /** - * Returns the last request result encountered for the operation. - * - * @return A {@link RequestResult} object that represents the last request result. - */ - public synchronized RequestResult getLastResult() { - if (this.requestResults == null || this.requestResults.size() == 0) { - return null; - } - else { - return this.requestResults.get(this.requestResults.size() - 1); - } - } - - /** - * Gets the Logger associated with this operation. - * - * @return the Logger associated with this operation - */ - @SuppressWarnings("unused") - private Logger getLogger() { - // V2 throw on null logger reference , use default dummy logger. - return this.logger; - } - - /** - * Returns the set of request results that the current operation has created. - * - * @return An ArrayList object that contains {@link RequestResult} objects that represent the request - * results created by the current operation. - */ - public ArrayList getRequestResults() { - return this.requestResults; - } - - /** - * Reserved for internal use. appends a {@link RequestResult} object to the internal collection in a synchronized - * manner. - * - * @param requestResult - */ - public synchronized void appendRequestResult(RequestResult requestResult) { - this.requestResults.add(requestResult); - } - - /** - * @return the SendingRequestEvent - */ - public StorageEventMultiCaster> getSendingRequestEventHandler() { - return this.sendingRequestEventHandler; - } - - /** - * @return the responseReceivedEventHandler - */ - public StorageEventMultiCaster> getResponseReceivedEventHandler() { - return this.responseReceivedEventHandler; - } - - /** - * Initializes the OperationContext in order to begin processing a new operation. All operation specific information - * is erased. - */ - public void initialize() { - this.setClientTimeInMs(0); - this.requestResults.clear(); - this.setIntermediateMD5(null); - this.operationState = null; - this.setCurrentRequestObject(null); - } - - /** - * @param clientRequestID - * the clientRequestID to set - */ - public void setClientRequestID(final String clientRequestID) { - this.clientRequestID = clientRequestID; - } - - /** - * @param clientTimeInMs - * the clientTimeInMs to set - */ - public void setClientTimeInMs(final long clientTimeInMs) { - this.clientTimeInMs = clientTimeInMs; - } - - /** - * @param currentOperationByteCount - * the currentOperationByteCount to set - */ - public void setCurrentOperationByteCount(final long currentOperationByteCount) { - this.currentOperationByteCount = currentOperationByteCount; - } - - /** - * @param currentRequestObject - * the currentRequestObject to set - */ - public void setCurrentRequestObject(final HttpURLConnection currentRequestObject) { - this.currentRequestObject = currentRequestObject; - } - - /** - * @param intermediateMD5 - * the intermediateMD5 to set - */ - public void setIntermediateMD5(final MessageDigest intermediateMD5) { - this.intermediateMD5 = intermediateMD5; - } - - /** - * Sets the Logger for this operation. - * - * @param logger - * the Logger to use for this operation - */ - @SuppressWarnings("unused") - private void setLogger(final Logger logger) { - this.logger = logger; - } - - /** - * @param sendingRequestEventHandler - * the sendingRequestEventHandler to set - */ - public void setSendingRequestEventHandler( - final StorageEventMultiCaster> sendingRequestEventHandler) { - this.sendingRequestEventHandler = sendingRequestEventHandler; - } - - /** - * @param responseReceivedEventHandler - * the responseReceivedEventHandler to set - */ - public void setResponseReceivedEventHandler( - final StorageEventMultiCaster> responseReceivedEventHandler) { - this.responseReceivedEventHandler = responseReceivedEventHandler; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RequestOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RequestOptions.java deleted file mode 100644 index 3dab216190a70..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RequestOptions.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents the options to use while processing a given request. - */ -public class RequestOptions { - - /** - * The instance of the {@link RetryPolicyFactory} interface to use for the request. - */ - private RetryPolicyFactory retryPolicyFactory; - - /** - * The timeout interval, in milliseconds, to use for the request. - */ - private Integer timeoutIntervalInMs; - - /** - * Creates an instance of the RequestOptions class. - */ - public RequestOptions() { - // Empty Default Ctor - } - - /** - * Creates an instance of the RequestOptions class by copying values from another - * RequestOptions instance. - * - * @param other - * A RequestOptions object that represents the request options to copy. - */ - public RequestOptions(final RequestOptions other) { - this.setTimeoutIntervalInMs(other.getTimeoutIntervalInMs()); - this.setRetryPolicyFactory(other.getRetryPolicyFactory()); - } - - /** - * Populates the default timeout and retry policy from client if they are null. - * - * @param client - * the service client to populate from - */ - protected final void applyBaseDefaults(final ServiceClient client) { - if (this.getRetryPolicyFactory() == null) { - this.setRetryPolicyFactory(client.getRetryPolicyFactory()); - } - - if (this.getTimeoutIntervalInMs() == null) { - this.setTimeoutIntervalInMs(client.getTimeoutInMs()); - } - } - - /** - * @return the retryPolicyFactory - */ - public final RetryPolicyFactory getRetryPolicyFactory() { - return this.retryPolicyFactory; - } - - /** - * @return the timeoutIntervalInMs - */ - public final Integer getTimeoutIntervalInMs() { - return this.timeoutIntervalInMs; - } - - /** - * @param retryPolicyFactory - * the retryPolicyFactory to set - */ - public final void setRetryPolicyFactory(final RetryPolicyFactory retryPolicyFactory) { - this.retryPolicyFactory = retryPolicyFactory; - } - - /** - * @param timeoutIntervalInMs - * the timeoutIntervalInMs to set - */ - public final void setTimeoutIntervalInMs(final Integer timeoutIntervalInMs) { - this.timeoutIntervalInMs = timeoutIntervalInMs; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RequestResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RequestResult.java deleted file mode 100644 index a6da602f8f4da..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RequestResult.java +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.core.storage; - -import java.util.Date; - -/** - * Represents the result of a physical request. - */ -public final class RequestResult { - - /** - * Represents an exception that occurred while processing the request. This field may be null. - */ - private Exception exception; - - /** - * Represents the request ID supplied by the storage service. - */ - private String serviceRequestID; - - /** - * Represents the ContentMD5 header returned by the storage service. - */ - private String contentMD5; - - /** - * Represents the date header returned by the storage service. - */ - private String requestDate; - - /** - * Represents the ETag header returned by the storage service. - */ - private String etag; - - /** - * Represents the start date of the operation. - */ - private Date startDate; - - /** - * Represents the HTTP status code for the request. - */ - private int statusCode = -1; - - /** - * Represents the HTTP status message for the request. - */ - private String statusMessage; - - /** - * Represents the stop date of the operation. - */ - private Date stopDate; - - /** - * @return the contentMD5 - */ - public String getContentMD5() { - return this.contentMD5; - } - - /** - * @return the etag - */ - public String getEtag() { - return this.etag; - } - - /** - * @return the exception - */ - public Exception getException() { - return this.exception; - } - - /** - * @return the requestDate - */ - public String getRequestDate() { - return this.requestDate; - } - - /** - * @return the serviceRequestID - */ - public String getServiceRequestID() { - return this.serviceRequestID; - } - - /** - * @return the startDate - */ - public Date getStartDate() { - return this.startDate; - } - - /** - * @return the statusCode - */ - public int getStatusCode() { - return this.statusCode; - } - - /** - * @return the statusMessage - */ - public String getStatusMessage() { - return this.statusMessage; - } - - /** - * @return the stopDate - */ - public Date getStopDate() { - return this.stopDate; - } - - /** - * @param contentMD5 - * the contentMD5 to set - */ - public void setContentMD5(final String contentMD5) { - this.contentMD5 = contentMD5; - } - - /** - * @param etag - * the etag to set - */ - public void setEtag(final String etag) { - this.etag = etag; - } - - /** - * @param exception - * the exception to set - */ - public void setException(final Exception exception) { - this.exception = exception; - } - - /** - * @param requestDate - * the date to set - */ - public void setRequestDate(final String requestDate) { - this.requestDate = requestDate; - } - - /** - * @param serviceRequestID - * the serviceRequestID to set - */ - public void setServiceRequestID(final String serviceRequestID) { - this.serviceRequestID = serviceRequestID; - } - - /** - * @param startDate - * the startDate to set - */ - public void setStartDate(final Date startDate) { - this.startDate = startDate; - } - - /** - * @param statusCode - * the statusCode to set - */ - public void setStatusCode(final int statusCode) { - this.statusCode = statusCode; - } - - /** - * @param statusMessage - * the statusMessage to set - */ - public void setStatusMessage(final String statusMessage) { - this.statusMessage = statusMessage; - } - - /** - * @param stopDate - * the stopDate to set - */ - public void setStopDate(final Date stopDate) { - this.stopDate = stopDate; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResponseReceivedEvent.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResponseReceivedEvent.java deleted file mode 100644 index bf1506495a5db..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResponseReceivedEvent.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents an event that is fired when a response is received. - */ -public final class ResponseReceivedEvent { - - /** - * Represents a connection object. Currently only java.net.HttpURLConnection is supported as a - * connection object. - */ - private final Object connectionObject; - - /** - * Represents a context for the current operation. This object is used to track requests to the storage service, and - * to provide additional runtime information about the operation. - */ - private final OperationContext opContext; - - /** - * A {@link RequestResult} object that represents the last request result. - */ - private final RequestResult requestResult; - - /** - * Creates an instance of the ResponseReceivedEvent class. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * @param connectionObject - * Represents a connection object. Currently only java.net.HttpURLConnection is supported as - * a connection object. - * @param requestResult - * A {@link RequestResult} object that represents the current request result. - */ - public ResponseReceivedEvent(final OperationContext opContext, final Object connectionObject, - final RequestResult requestResult) { - this.opContext = opContext; - this.connectionObject = connectionObject; - this.requestResult = requestResult; - } - - /** - * @return the connectionObject - */ - public Object getConnectionObject() { - return this.connectionObject; - } - - /** - * @return the opContext - */ - public OperationContext getOpContext() { - return this.opContext; - } - - /** - * @return A {@link RequestResult} object that represents the current request result. - */ - public RequestResult getRequestResult() { - return this.requestResult; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultContinuation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultContinuation.java deleted file mode 100644 index 13f4119312e29..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultContinuation.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import com.microsoft.windowsazure.services.blob.client.CloudBlobDirectory; - -/** - * Represents a continuation token for listing operations. Continuation tokens are used in methods that return a - * {@link ResultSegment} object, such as {@link CloudBlobDirectory#listBlobsSegmented}. - */ -public final class ResultContinuation { - /** - * Represents the next marker for continuing results of listing operations. - */ - private String nextMarker; - - /** - * Gets or sets the NextPartitionKey for TableServiceEntity enumeration operations. - */ - private String nextPartitionKey; - - /** - * Gets or sets the NextRowKey for TableServiceEntity enumeration operations. - */ - private String nextRowKey; - - /** - * Gets or sets the NextTableName for Table enumeration operations. - */ - private String nextTableName; - - /** - * Gets or sets the type of the continuation token. - */ - private ResultContinuationType continuationType; - - /** - * Creates an instance of the ResultContinuation class. - */ - public ResultContinuation() { - // Empty Default Ctor - } - - /** - * @return the continuationType - */ - public ResultContinuationType getContinuationType() { - return this.continuationType; - } - - /** - * @return the nextMarker - */ - public String getNextMarker() { - return this.nextMarker; - } - - /** - * @return the nextPartitionKey - */ - public String getNextPartitionKey() { - return this.nextPartitionKey; - } - - /** - * @return the nextRowKey - */ - public String getNextRowKey() { - return this.nextRowKey; - } - - /** - * @return the nextTableName - */ - public String getNextTableName() { - return this.nextTableName; - } - - /** - * Returns a value that indicates whether continuation information is available. - * - * @return true if any continuation information is available; otherwise false. - */ - public boolean hasContinuation() { - return this.getNextMarker() != null || this.nextPartitionKey != null || this.nextRowKey != null - || this.nextTableName != null; - } - - /** - * @param continuationType - * the continuationType to set - */ - public void setContinuationType(final ResultContinuationType continuationType) { - this.continuationType = continuationType; - } - - /** - * @param nextMarker - * the nextMarker to set - */ - public void setNextMarker(final String nextMarker) { - this.nextMarker = nextMarker; - } - - /** - * @param nextPartitionKey - * the nextPartitionKey to set - */ - public void setNextPartitionKey(final String nextPartitionKey) { - this.nextPartitionKey = nextPartitionKey; - } - - /** - * @param nextRowKey - * the nextRowKey to set - */ - public void setNextRowKey(final String nextRowKey) { - this.nextRowKey = nextRowKey; - } - - /** - * @param nextTableName - * the nextTableName to set - */ - public void setNextTableName(final String nextTableName) { - this.nextTableName = nextTableName; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultContinuationType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultContinuationType.java deleted file mode 100644 index 02f564344f75d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultContinuationType.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Specifies the type of a continuation token. - */ -public enum ResultContinuationType { - /** - * Specifies no continuation. - */ - NONE, - - /** - * Specifies the token is a blob listing continuation token. - */ - BLOB, - - /** - * Specifies the token is a container listing continuation token. - */ - CONTAINER, - - /** - * Specifies the token is a queue listing continuation token (reserved for future use). - */ - QUEUE, - - /** - * Specifies the token is a table query continuation token (reserved for future use). - */ - TABLE -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultSegment.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultSegment.java deleted file mode 100644 index 47f9648dc8e8d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ResultSegment.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.util.ArrayList; - -/** - * Represents a segment of results and contains continuation and pagination information. - * - * @param - * The type of the result that the segment contains. - */ -public class ResultSegment { - /** - * Stores the continuation token used to retrieve the next segment of results. - */ - private final ResultContinuation continuationToken; - - /** - * Holds the number of the results. - */ - private final int length; - - /** - * Holds the size of the requested page. - */ - private final int pageSize; - - /** - * Holds the ArrayList of results. - */ - private final ArrayList results; - - /** - * Reserved for internal use. Creates an instance of the ResultSegment class. - * - * @param results - * An ArrayList object that represents the results for the segment. - * @param pageSize - * The number of elements in a page of results. - * @param token - * A {@link ResultContinuation} object that represents the continuation token. - */ - public ResultSegment(final ArrayList results, final int pageSize, final ResultContinuation token) { - this.results = results; - this.length = results.size(); - this.pageSize = pageSize; - this.continuationToken = token; - } - - /** - * Returns the continuation token for the result segment. - * - * @return A {@link ResultContinuation} object that represents the continuation token. - */ - public ResultContinuation getContinuationToken() { - return this.continuationToken; - } - - /** - * Returns a value that indicates whether there are more results available from the server. - * - * @return true if there are more results available from the server; otherwise, false. - */ - public boolean getHasMoreResults() { - return this.continuationToken != null; - } - - /** - * Returns a value that indicates whether the page has more results. - * - * @return true if the page has more results; otherwise, false. - */ - public boolean getIsPageComplete() { - return this.length == this.pageSize; - } - - /** - * Returns the number of results in the segment. - * - * @return The actual number of the results in the segment. - */ - public int getLength() { - return this.length; - } - - /** - * Returns the size of the requested page. - * - * @return The size of the requested page. - */ - public int getPageSize() { - return this.pageSize; - } - - /** - * Returns the count of remaining results needed to fulfill the requested page size. - * - * @return The count of remaining results needed to fulfill the requested page size. - */ - public int getRemainingPageResults() { - return this.pageSize - this.length; - } - - /** - * Returns an enumerable set of results from the service. - * - * @return The results retrieved from the service. - */ - public ArrayList getResults() { - return this.results; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryExponentialRetry.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryExponentialRetry.java deleted file mode 100644 index 8bdbf95473ead..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryExponentialRetry.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.HttpURLConnection; -import java.util.Random; - -/** - * Represents a retry policy that performs a specified number of retries, using a randomized exponential backoff scheme - * to determine the interval between retries. - * - * This class extends the {@link com.microsoft.windowsazure.services.core.storage.RetryPolicy} class and implements the - * {@link com.microsoft.windowsazure.services.core.storage.RetryPolicyFactory} interface. - */ -public final class RetryExponentialRetry extends RetryPolicy implements RetryPolicyFactory { - - /** - * Holds the random number generator used to calculate randomized backoff interavals. - */ - private final Random randRef = new Random(); - - /** - * Holds the actual maximum backoff interval to enforce. - */ - private int resolvedMaxBackoff = RetryPolicy.DEFAULT_MAX_BACKOFF; - - /** - * Holds the actual minimum backoff interval to enforce. - */ - private int resolvedMinBackoff = RetryPolicy.DEFAULT_MIN_BACKOFF; - - /** - * Creates an instance of the RetryExponentialRetry class. - */ - public RetryExponentialRetry() { - this(RetryPolicy.DEFAULT_CLIENT_BACKOFF, RetryPolicy.DEFAULT_CLIENT_RETRY_COUNT); - } - - /** - * Creates an instance of the RetryExponentialRetry class using the specified delta backoff and maximum - * retry attempts. - * - * @param deltaBackoff - * The backoff interval, in milliseconds, between retries. - * @param maxAttempts - * The maximum number of retry attempts. - */ - public RetryExponentialRetry(final int deltaBackoff, final int maxAttempts) { - super(deltaBackoff, maxAttempts); - } - - /** - * Creates an instance of the RetryExponentialRetry class using the specified minimum, maximum, and - * delta backoff amounts, and maximum number of retry attempts. - * - * @param minBackoff - * The minimum backoff interval, in milliseconds, between retries. - * @param deltaBackoff - * The backoff interval, in milliseconds, between retries. - * @param maxBackOff - * The maximum backoff interval, in milliseconds, between retries. - * @param maxAttempts - * The maximum retry attempts, in milliseconds, between retries. - */ - public RetryExponentialRetry(final int minBackoff, final int deltaBackoff, final int maxBackOff, - final int maxAttempts) { - super(deltaBackoff, maxAttempts); - this.resolvedMinBackoff = minBackoff; - this.resolvedMaxBackoff = maxBackOff; - } - - /** - * Generates a new retry policy for the current request attempt. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryPolicy} object that represents the retry policy for the current request attempt. - */ - @Override - public RetryPolicy createInstance(final OperationContext opContext) { - return new RetryExponentialRetry(this.resolvedMinBackoff, this.deltaBackoffIntervalInMs, - this.resolvedMaxBackoff, this.maximumAttempts); - } - - /** - * Determines if the operation should be retried and how long to wait until the next retry. - * - * @param currentRetryCount - * The number of retries for the given operation. A value of zero signifies this is the first error - * encountered. - * @param statusCode - * The status code for the last operation. - * @param lastException - * A Exception object that represents the last exception encountered. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryResult} object that represents the retry result, indicating whether the operation should be - * retried and how long to backoff. - */ - @Override - public RetryResult shouldRetry(final int currentRetryCount, final int statusCode, final Exception lastException, - final OperationContext opContext) { - if (statusCode >= 400 && statusCode < 500 || statusCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED - || statusCode == HttpURLConnection.HTTP_VERSION) { - return new RetryResult(-1, false); - } - - if (currentRetryCount < this.maximumAttempts) { - // Calculate backoff Interval between 80% and 120% of the desired - // backoff, multiply by 2^n -1 for exponential - double incrementDelta = (Math.pow(2, currentRetryCount) - 1); - final int boundedRandDelta = (int) (this.deltaBackoffIntervalInMs * 0.8) - + this.randRef.nextInt((int) (this.deltaBackoffIntervalInMs * 1.2) - - (int) (this.deltaBackoffIntervalInMs * 0.8)); - incrementDelta *= boundedRandDelta; - - // Enforce max / min backoffs - return new RetryResult((int) Math.round(Math.min(this.resolvedMinBackoff + incrementDelta, - this.resolvedMaxBackoff)), true); - } - else { - return new RetryResult(-1, false); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryLinearRetry.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryLinearRetry.java deleted file mode 100644 index 7f6a5f312dac5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryLinearRetry.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.HttpURLConnection; - -/** - * Represents a retry policy that performs a specified number of retries, using a specified fixed time interval between - * retries. - * - * This class extends the {@link RetryPolicy} class and implements the {@link RetryPolicyFactory} interface. - */ -public final class RetryLinearRetry extends RetryPolicy implements RetryPolicyFactory { - - /** - * Creates an instance of the RetryLinearRetry class. - */ - public RetryLinearRetry() { - this(RetryPolicy.DEFAULT_CLIENT_BACKOFF, RetryPolicy.DEFAULT_CLIENT_RETRY_COUNT); - } - - /** - * Creates an instance of the RetryLinearRetry class using the specified delta backoff and maximum - * retry attempts. - * - * @param deltaBackoff - * The backoff interval, in milliseconds, between retries. - * @param maxAttempts - * The maximum number of retry attempts. - */ - public RetryLinearRetry(final int deltaBackoff, final int maxAttempts) { - super(deltaBackoff, maxAttempts); - } - - /** - * Generates a new retry policy for the current request attempt. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryPolicy} object that represents the retry policy for the current request attempt. - */ - @Override - public RetryPolicy createInstance(final OperationContext opContext) { - return new RetryLinearRetry(this.deltaBackoffIntervalInMs, this.maximumAttempts); - } - - /** - * Determines if the operation should be retried and how long to wait until the next retry. - * - * @param currentRetryCount - * The number of retries for the given operation. A value of zero signifies this is the first error - * encountered. - * @param statusCode - * The status code for the last operation. - * @param lastException - * A Exception object that represents the last exception encountered. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryResult} object that represents the retry result, indicating whether the operation should be - * retried and how long to backoff. - */ - @Override - public RetryResult shouldRetry(final int currentRetryCount, final int statusCode, final Exception lastException, - final OperationContext opContext) { - if (statusCode >= 400 && statusCode < 500 || statusCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED - || statusCode == HttpURLConnection.HTTP_VERSION) { - return new RetryResult(0, false); - } - - final int backoff = Math.max(Math.min(this.deltaBackoffIntervalInMs, RetryPolicy.DEFAULT_MAX_BACKOFF), - RetryPolicy.DEFAULT_MIN_BACKOFF); - - return new RetryResult(backoff, currentRetryCount < this.maximumAttempts); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryNoRetry.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryNoRetry.java deleted file mode 100644 index b89c22e1aceee..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryNoRetry.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents a retry policy that performs no retries. - * - * This class extends the {@link com.microsoft.windowsazure.services.core.storage.RetryPolicy} class and implements the - * {@link com.microsoft.windowsazure.services.core.storage.RetryPolicyFactory} interface. - */ -public final class RetryNoRetry extends RetryPolicy implements RetryPolicyFactory { - - /** - * Holds the static instance of the no retry policy. - */ - private static RetryNoRetry instance = new RetryNoRetry(); - - /** - * Returns the static instance of a no retry policy. - * - * @return A RetryNoRetry object that represents a no retry policy. - */ - public static RetryNoRetry getInstance() { - return instance; - } - - /** - * Generates a new retry policy for the current request attempt. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryPolicy} object that represents the retry policy for the current request attempt. - */ - @Override - public RetryPolicy createInstance(final OperationContext opContext) { - return getInstance(); - } - - /** - * Determines if the operation should be retried and how long to wait until the next retry. - * - * @param currentRetryCount - * The number of retries for the given operation. A value of zero signifies this is the first error - * encountered. - * @param statusCode - * The status code for the last operation. - * @param lastException - * A Exception object that represents the last exception encountered. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryResult} object that represents the retry result, indicating whether the operation should be - * retried and how long to backoff. - * - */ - @Override - public RetryResult shouldRetry(final int currentRetryCount, final int statusCode, final Exception lastException, - final OperationContext opContext) { - return new RetryResult(0, false); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryPolicy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryPolicy.java deleted file mode 100644 index ade5dd23b56a8..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryPolicy.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Abstract class that represents a retry policy. - */ -public abstract class RetryPolicy { - - /** - * Represents the default client backoff interval, in milliseconds. - */ - public static final int DEFAULT_CLIENT_BACKOFF = 1000 * 30; - - /** - * Represents the default client retry count. - */ - public static final int DEFAULT_CLIENT_RETRY_COUNT = 3; - - /** - * Represents the default maximum backoff interval, in milliseconds. - */ - public static final int DEFAULT_MAX_BACKOFF = 1000 * 90; - - /** - * Represents the default minimum backoff interval, in milliseconds. - */ - public static final int DEFAULT_MIN_BACKOFF = 1000 * 3; - - /** - * Represents the realized backoff interval, in milliseconds. - */ - protected int deltaBackoffIntervalInMs; - - /** - * Represents the maximum retries that the retry policy should attempt. - */ - protected int maximumAttempts; - - /** - * Creates an instance of the RetryPolicy class. - */ - public RetryPolicy() { - // Empty Default Ctor - } - - /** - * Creates an instance of the RetryPolicy class using the specified delta backoff and maximum retry - * attempts. - * - * @param deltaBackoff - * The backoff interval, in milliseconds, between retries. - * @param maxAttempts - * The maximum number of retry attempts. - */ - public RetryPolicy(final int deltaBackoff, final int maxAttempts) { - this.deltaBackoffIntervalInMs = deltaBackoff; - this.maximumAttempts = maxAttempts; - } - - /** - * Determines if the operation should be retried and how long to wait until the next retry. - * - * @param currentRetryCount - * The number of retries for the given operation. A value of zero signifies this is the first error - * encountered. - * @param statusCode - * The status code for the last operation. - * @param lastException - * A Exception object that represents the last exception encountered. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryResult} object that indicates whether the operation should be retried and how long to - * backoff. - */ - public abstract RetryResult shouldRetry(int currentRetryCount, int statusCode, Exception lastException, - OperationContext opContext); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryPolicyFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryPolicyFactory.java deleted file mode 100644 index 919c04d35a836..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryPolicyFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents a retry policy factory that creates a new {@link RetryPolicy} object per transaction. - */ -public interface RetryPolicyFactory { - - /** - * Creates a new {@link RetryPolicy} object for the current request attempt. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link RetryPolicy} object that represents the new retry policy for the current request attempt. - */ - RetryPolicy createInstance(OperationContext opContext); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryResult.java deleted file mode 100644 index 92941950b3fa1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/RetryResult.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents the result of a retry policy evaluation. - */ -public final class RetryResult { - /** - * Represents the backoff interval in milliseconds. - */ - private int backOffIntervalInMs; - - /** - * @return the backOffIntervalInMs - */ - public int getBackOffIntervalInMs() { - return this.backOffIntervalInMs; - } - - /** - * Indicates whether to retry the operation. Set to true to retry; otherwise, false. - */ - private boolean shouldRetry; - - /** - * Creates an instance of the RetryResult class. - * - * @param backOff - * The backoff interval, in milliseconds, to wait before attempting the retry. - * @param shouldRetry - * true if the operation should be retried, otherwise, false. - * - */ - public RetryResult(final int backOff, final boolean shouldRetry) { - this.backOffIntervalInMs = backOff; - this.setShouldRetry(shouldRetry); - } - - /** - * Sleeps the amount of time specified by the backoff interval, if the retry policy indicates the operation should - * be retried. - */ - public void doSleep() { - if (this.isShouldRetry()) { - try { - Thread.sleep(this.backOffIntervalInMs); - } - catch (final InterruptedException e) { - // Restore the interrupted status - Thread.currentThread().interrupt(); - } - } - } - - /** - * @return the shouldRetry - */ - public boolean isShouldRetry() { - return this.shouldRetry; - } - - /** - * @param shouldRetry - * the shouldRetry to set - */ - public void setShouldRetry(final boolean shouldRetry) { - this.shouldRetry = shouldRetry; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/SendingRequestEvent.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/SendingRequestEvent.java deleted file mode 100644 index 8d0e6da594d66..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/SendingRequestEvent.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents an event that is fired when before sending a request. - */ -public final class SendingRequestEvent { - - /** - * Represents a connection object. Currently only java.net.HttpURLConnection is supported as a - * connection object. - */ - private final Object connectionObject; - - /** - * Represents a context for the current operation. This object is used to track requests to the storage service, and - * to provide additional runtime information about the operation. - */ - private final OperationContext opContext; - - /** - * A {@link RequestResult} object that represents the last request result. - */ - private final RequestResult requestResult; - - /** - * Creates an instance of the SendingRequestEvent class. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * @param connectionObject - * Represents a connection object. Currently only java.net.HttpURLConnection is supported as - * a connection object. - * @param requestResult - * A {@link RequestResult} object that represents the current request result. - */ - public SendingRequestEvent(final OperationContext opContext, final Object connectionObject, - final RequestResult requestResult) { - this.opContext = opContext; - this.connectionObject = connectionObject; - this.requestResult = requestResult; - } - - /** - * @return the connectionObject - */ - public Object getConnectionObject() { - return this.connectionObject; - } - - /** - * @return the opContext - */ - public OperationContext getOpContext() { - return this.opContext; - } - - /** - * @return A {@link RequestResult} object that represents the current request result. - */ - public RequestResult getRequestResult() { - return this.requestResult; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ServiceClient.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ServiceClient.java deleted file mode 100644 index 1360b9cedfb46..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ServiceClient.java +++ /dev/null @@ -1,377 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.io.ByteArrayInputStream; -import java.net.HttpURLConnection; -import java.net.URI; - -import com.microsoft.windowsazure.services.blob.client.CloudBlobClient; -import com.microsoft.windowsazure.services.core.storage.utils.StreamMd5AndLength; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseRequest; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseResponse; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; -import com.microsoft.windowsazure.services.queue.client.CloudQueueClient; - -/** - * Reserved for internal use. Provides a client for accessing the Windows Azure Storage service. - */ -public abstract class ServiceClient { - - /** - * Holds the base URI for the Service Client. - */ - protected URI endpoint; - - /** - * Holds the StorageCredentials associated with this Service Client. - */ - protected StorageCredentials credentials; - - /** - * Reserved for internal use. An internal flag which indicates if path style uris should be used. - */ - private boolean usePathStyleUris; - - /** - * Holds the default retry policy for requests made via the service client to set. - */ - protected RetryPolicyFactory retryPolicyFactory = new RetryExponentialRetry(); - - /** - * Holds the default server and client timeout for requests made by the service client. - */ - protected int timeoutInMs = Constants.DEFAULT_TIMEOUT_IN_MS; - - /** - * Holds the AuthenticationScheme associated with this Service Client. - */ - protected AuthenticationScheme authenticationScheme = AuthenticationScheme.SHAREDKEYFULL; - - /** - * Creates an instance of the ServiceClient class using the specified service endpoint. - * - * @param baseUri - * A java.net.URI object that represents the service endpoint used to create the client. - */ - public ServiceClient(final URI baseUri) { - this(baseUri, null); - } - - /** - * Creates an instance of the ServiceClient class using the specified service endpoint and account - * credentials. - * - * @param baseUri - * A java.net.URI object that represents the service endpoint used to create the client. - * - * @param credentials - * A {@link StorageCredentials} object that represents the account credentials. - */ - public ServiceClient(final URI baseUri, final StorageCredentials credentials) { - Utility.assertNotNull("baseUri", baseUri); - if (!baseUri.isAbsolute()) { - throw new IllegalArgumentException(String.format( - "Address '%s' is not an absolute address. Relative addresses are not permitted in here.", baseUri)); - } - - this.credentials = credentials == null ? StorageCredentialsAnonymous.ANONYMOUS : credentials; - - this.retryPolicyFactory = new RetryExponentialRetry(); - this.timeoutInMs = Constants.DEFAULT_TIMEOUT_IN_MS; - - this.usePathStyleUris = Utility.determinePathStyleFromUri(baseUri, this.credentials.getAccountName()); - this.endpoint = baseUri; - } - - /** - * Retrieves the current ServiceProperties for the given storage service. This includes Metrics and Logging - * Configurations. - * - * @return the ServiceProperties object representing the current configuration of the service. - * @throws StorageException - * If a storage service error occurred. - */ - public final ServiceProperties downloadServiceProperties() throws StorageException { - return this.downloadServiceProperties(null, null); - } - - /** - * Retrieves the current ServiceProperties for the given storage service. This includes Metrics and Logging - * Configurations. - * - * @param options - * A {@link RequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}{@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * @return the ServiceProperties object representing the current configuration of the service. - * @throws StorageException - * If a storage service error occurred. - */ - public final ServiceProperties downloadServiceProperties(RequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new RequestOptions(); - } - - opContext.initialize(); - options.applyBaseDefaults(this); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public ServiceProperties execute(final ServiceClient client, final Void v, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = BaseRequest.getServiceProperties(client.getEndpoint(), this - .getRequestOptions().getTimeoutIntervalInMs(), null, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - return BaseResponse.readServicePropertiesFromStream(request.getInputStream(), opContext); - } - }; - - return ExecutionEngine.executeWithRetry(this, null, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Returns the storage credentials associated with this service client. - * - * @return A {@link StorageCredentials} object that represents the storage credentials associated with this client. - */ - public final StorageCredentials getCredentials() { - return this.credentials; - } - - /** - * Returns the AuthenticationScheme associated with this service client. - * - * @return An {@link AuthenticationScheme} object that represents the authentication scheme associated with this - * client. - */ - public final AuthenticationScheme getAuthenticationScheme() { - return this.authenticationScheme; - } - - /** - * Returns the base URI for this service client. - * - * @return A java.net.URI object that represents the base URI for the service client. - */ - public final URI getEndpoint() { - return this.endpoint; - } - - /** - * Returns the retry policy currently in effect for this Blob service client. - * - * @return An {@link RetryPolicyFactory} object that represents the current retry policy. - * - * @see RetryPolicy - * @see RetryExponentialRetry - * @see RetryLinearRetry - * @see RetryNoRetry - */ - public final RetryPolicyFactory getRetryPolicyFactory() { - return this.retryPolicyFactory; - } - - /** - * Returns the timeout value for requests made to the service. For more information about the timeout, see - * {@link #setTimeoutInMs}. - * - * @return The current timeout value, in milliseconds, for requests made to the storage service. - */ - public final int getTimeoutInMs() { - return this.timeoutInMs; - } - - /** - * @return the usePathStyleUris - */ - public final boolean isUsePathStyleUris() { - return this.usePathStyleUris; - } - - /** - * Sets the base URI for the service client. - * - * @param baseUri - * A java.net.URI object that represents the base URI being assigned to the service client. - */ - protected final void setBaseURI(final URI baseUri) { - this.usePathStyleUris = Utility.determinePathStyleFromUri(baseUri, this.credentials.getAccountName()); - this.endpoint = baseUri; - } - - /** - * Sets the credentials to use with this service client. - * - * @param credentials - * A Credentials object that represents the credentials being assigned for the service - * client. - */ - protected final void setCredentials(final StorageCredentials credentials) { - this.credentials = credentials; - } - - /** - * Sets the Authentication Scheme to use with this service client. - * - * @param scheme - * An AuthenticationScheme object that represents the authentication scheme being assigned - * for the service - * client. - */ - public final void setAuthenticationScheme(final AuthenticationScheme scheme) { - this.authenticationScheme = scheme; - } - - /** - * Sets the RetryPolicyFactory object to use when making service requests. - * - * @param retryPolicyFactory - * the RetryPolicyFactory object to use when making service requests. - */ - public void setRetryPolicyFactory(final RetryPolicyFactory retryPolicyFactory) { - this.retryPolicyFactory = retryPolicyFactory; - } - - /** - * Sets the timeout to use when making requests to the storage service. - *

- * The server timeout interval begins at the time that the complete request has been received by the service, and - * the server begins processing the response. If the timeout interval elapses before the response is returned to the - * client, the operation times out. The timeout interval resets with each retry, if the request is retried. - * - * The default timeout interval for a request made via the service client is 90 seconds. You can change this value - * on the service client by setting this property, so that all subsequent requests made via the service client will - * use the new timeout interval. You can also change this value for an individual request, by setting the - * {@link RequestOptions#timeoutIntervalInMs} property. - * - * If you are downloading a large blob, you should increase the value of the timeout beyond the default value. - * - * @param timeoutInMs - * The timeout, in milliseconds, to use when making requests to the storage service. - */ - public final void setTimeoutInMs(final int timeoutInMs) { - this.timeoutInMs = timeoutInMs; - } - - /** - * Uploads a new configuration to the storage service. This includes Metrics and Logging Configuration. - * - * @param properties - * The ServiceProperties to upload. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadServiceProperties(final ServiceProperties properties) throws StorageException { - this.uploadServiceProperties(properties, null, null); - } - - /** - * Uploads a new configuration to the storage service. This includes Metrics and Logging Configuration. - * - * @param properties - * The ServiceProperties to upload. - * @param options - * A {@link RequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudBlobClient}{@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadServiceProperties(final ServiceProperties properties, RequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new RequestOptions(); - } - - opContext.initialize(); - options.applyBaseDefaults(this); - - Utility.assertNotNull("properties", properties); - Utility.assertNotNull("properties.Logging", properties.getLogging()); - Utility.assertNotNull("properties.Logging.LogOperationTypes", properties.getLogging().getLogOperationTypes()); - Utility.assertNotNull("properties.Merics", properties.getMetrics()); - Utility.assertNotNull("properties.Merics.Configuration", properties.getMetrics().getMetricsLevel()); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final ServiceClient client, final Void v, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = BaseRequest.setServiceProperties(client.getEndpoint(), this - .getRequestOptions().getTimeoutIntervalInMs(), null, opContext); - this.setConnection(request); - - final byte[] propertiesBytes = BaseRequest.serializeServicePropertiesToByteArray(properties, opContext); - - final ByteArrayInputStream dataInputStream = new ByteArrayInputStream(propertiesBytes); - - final StreamMd5AndLength descriptor = Utility.analyzeStream(dataInputStream, -1L, -1L, - true /* rewindSourceStream */, true /* calculateMD5 */); - request.setRequestProperty(Constants.HeaderConstants.CONTENT_MD5, descriptor.getMd5()); - - this.signRequest(client, request, descriptor.getLength(), null); - - Utility.writeToOutputStream(dataInputStream, request.getOutputStream(), descriptor.getLength(), - false /* rewindSourceStream */, false /* calculateMD5 */, null, opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this, null, impl, options.getRetryPolicyFactory(), opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ServiceProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ServiceProperties.java deleted file mode 100644 index 6325e1af75ca2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/ServiceProperties.java +++ /dev/null @@ -1,479 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.io.InputStream; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamWriter; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Represents the analytics properties for the service. - */ -public final class ServiceProperties { - /** - * Populates the Logging Properties form the xml reader. XmlStreamReader must be at start of Logging element. - * - * @param retProps - * the ServiceProperties to populate - * @param xmlr - * the XMLStreamReader to read from - * @throws XMLStreamException - * if the xml is invalid. - * @throws StorageException - * if unexpected xml is found. - */ - private static void readLoggingProperties(final ServiceProperties retProps, final XMLStreamReader xmlr) - throws XMLStreamException, StorageException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.AnalyticsConstants.LOGGING_ELEMENT); - - int eventType = xmlr.getEventType(); - String tempParseString = null; - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - final String name = xmlr.getName().toString(); - if (name.equals(Constants.AnalyticsConstants.VERSION_ELEMENT)) { - retProps.getLogging().setVersion( - Utility.readElementFromXMLReader(xmlr, Constants.AnalyticsConstants.VERSION_ELEMENT)); - } - else if (name.equals(Constants.AnalyticsConstants.DELETE_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, - Constants.AnalyticsConstants.DELETE_ELEMENT); - if (Boolean.parseBoolean(tempParseString)) { - retProps.getLogging().getLogOperationTypes().add(LoggingOperations.DELETE); - } - } - else if (name.equals(Constants.AnalyticsConstants.READ_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, Constants.AnalyticsConstants.READ_ELEMENT); - if (Boolean.parseBoolean(tempParseString)) { - retProps.getLogging().getLogOperationTypes().add(LoggingOperations.READ); - } - } - else if (name.equals(Constants.AnalyticsConstants.WRITE_ELEMENT)) { - tempParseString = Utility - .readElementFromXMLReader(xmlr, Constants.AnalyticsConstants.WRITE_ELEMENT); - if (Boolean.parseBoolean(tempParseString)) { - retProps.getLogging().getLogOperationTypes().add(LoggingOperations.WRITE); - } - } - else if (name.equals(Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT)) { - retProps.getLogging().setRetentionIntervalInDays(readRetentionPolicy(xmlr)); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else { - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.AnalyticsConstants.LOGGING_ELEMENT); - break; - } - } - } - - /** - * Populates the Metrics Properties form the xml reader. XmlStreamReader must be at start of Metrics element. - * - * @param retProps - * the ServiceProperties to populate - * @param xmlr - * the XMLStreamReader to read from - * @throws XMLStreamException - * if the xml is invalid. - * @throws StorageException - * if unexpected xml is found. - */ - private static void readMetricsProperties(final ServiceProperties retProps, final XMLStreamReader xmlr) - throws XMLStreamException, StorageException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.AnalyticsConstants.METRICS_ELEMENT); - - int eventType = xmlr.getEventType(); - String tempParseString = null; - retProps.getMetrics().setMetricsLevel(null); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - final String name = xmlr.getName().toString(); - if (name.equals(Constants.AnalyticsConstants.VERSION_ELEMENT)) { - retProps.getMetrics().setVersion( - Utility.readElementFromXMLReader(xmlr, Constants.AnalyticsConstants.VERSION_ELEMENT)); - } - else if (name.equals(Constants.AnalyticsConstants.ENABLED_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, - Constants.AnalyticsConstants.ENABLED_ELEMENT); - - if (Boolean.parseBoolean(tempParseString)) { - retProps.getMetrics() - .setMetricsLevel( - retProps.getMetrics().getMetricsLevel() != MetricsLevel.SERVICE_AND_API ? MetricsLevel.SERVICE - : MetricsLevel.SERVICE_AND_API); - } - else { - retProps.getMetrics().setMetricsLevel(MetricsLevel.DISABLED); - } - } - else if (name.equals(Constants.AnalyticsConstants.INCLUDE_APIS_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, - Constants.AnalyticsConstants.INCLUDE_APIS_ELEMENT); - if (Boolean.parseBoolean(tempParseString) - && retProps.getMetrics().getMetricsLevel() != MetricsLevel.DISABLED) { - retProps.getMetrics().setMetricsLevel(MetricsLevel.SERVICE_AND_API); - } - } - else if (name.equals(Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT)) { - retProps.getMetrics().setRetentionIntervalInDays(readRetentionPolicy(xmlr)); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else { - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.AnalyticsConstants.METRICS_ELEMENT); - break; - } - } - } - - /** - * Parses the retention policy from the xml reader. XmlStreamReader must be at start of retention policy element. - * - * @param xmlr - * the XMLStreamReader to read from - * @return a nullable Integer representing the retention policy - * @throws XMLStreamException - * if the xml is invalid. - * @throws StorageException - * if unexpected xml is found. - */ - private static Integer readRetentionPolicy(final XMLStreamReader xmlr) throws XMLStreamException, StorageException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT); - - Integer retVal = -1; - int eventType = xmlr.getEventType(); - String tempParseString = null; - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (name.equals(Constants.AnalyticsConstants.DAYS_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, Constants.AnalyticsConstants.DAYS_ELEMENT); - - // if we have already detected that the retention policy is disabled dont return a value; - if (retVal != null) { - retVal = Integer.parseInt(tempParseString); - } - } - else if (name.equals(Constants.AnalyticsConstants.ENABLED_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, - Constants.AnalyticsConstants.ENABLED_ELEMENT); - - if (!Boolean.parseBoolean(tempParseString)) { - retVal = null; - } - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else { - xmlr.require(XMLStreamConstants.END_ELEMENT, null, - Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT); - break; - } - } - - return retVal; - } - - /** - * Deserializes the ServiceProperties object from an input stream. - * - * @param inStream - * the stream to read from. - * @param opContext - * an object used to track the execution of the operation - * @return a ServiceProperties object representing the Analytics configuration for the client. - * @throws XMLStreamException - * if the xml is invalid. - * @throws StorageException - * if unexpected xml is found. - */ - public static ServiceProperties readServicePropertiesFromStream(final InputStream inStream, - final OperationContext opContext) throws XMLStreamException, StorageException { - final ServiceProperties retProps = new ServiceProperties(); - - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream); - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // 1. get StorageServiceProperties Header - eventType = xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, - Constants.AnalyticsConstants.STORAGE_SERVICE_PROPERTIES_ELEMENT); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.START_ELEMENT) { - final String name = xmlr.getName().toString(); - if (name.equals(Constants.AnalyticsConstants.LOGGING_ELEMENT)) { - readLoggingProperties(retProps, xmlr); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.AnalyticsConstants.LOGGING_ELEMENT); - } - else if (name.equals(Constants.AnalyticsConstants.METRICS_ELEMENT)) { - readMetricsProperties(retProps, xmlr); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.AnalyticsConstants.METRICS_ELEMENT); - } - else if (name.equals(Constants.AnalyticsConstants.DEFAULT_SERVICE_VERSION)) { - retProps.setDefaultServiceVersion(Utility.readElementFromXMLReader(xmlr, - Constants.AnalyticsConstants.DEFAULT_SERVICE_VERSION)); - } - else { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT) { - if (xmlr.getName().toString().equals(Constants.AnalyticsConstants.STORAGE_SERVICE_PROPERTIES_ELEMENT)) { - break; - } - } - } - - return retProps; - } - - /** - * Writes the retention policy to the XMLStreamWriter. - * - * @param xmlw - * the XMLStreamWriter to write to. - * @param val - * the nullable Integer indicating if the retention policy is enabled, and how long - * @throws XMLStreamException - */ - private static void writeRetentionPolicy(final XMLStreamWriter xmlw, final Integer val) throws XMLStreamException { - xmlw.writeStartElement(Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT); - - // Enabled - xmlw.writeStartElement(Constants.AnalyticsConstants.ENABLED_ELEMENT); - xmlw.writeCharacters(val != null ? Constants.TRUE : Constants.FALSE); - xmlw.writeEndElement(); - - if (val != null) { - // Days - xmlw.writeStartElement(Constants.AnalyticsConstants.DAYS_ELEMENT); - xmlw.writeCharacters(val.toString()); - xmlw.writeEndElement(); - } - - // End Retention Policy - xmlw.writeEndElement(); - } - - /** - * The service logging properties. This may not be null. - */ - private LoggingProperties logging; - - /** - * The service metrics properties. - */ - private MetricsProperties metrics; - - /** - * The default service version for the blob service, or null if no default is specified. This must be null for queue - * and table service properties. - */ - private String defaultServiceVersion; - - public ServiceProperties() { - this.setLogging(new LoggingProperties()); - this.setMetrics(new MetricsProperties()); - } - - /** - * @return the defaultServiceVersion - */ - public String getDefaultServiceVersion() { - return this.defaultServiceVersion; - } - - /** - * @return the logging - */ - public LoggingProperties getLogging() { - return this.logging; - } - - /** - * @return the metrics - */ - public MetricsProperties getMetrics() { - return this.metrics; - } - - /** - * Writes the contents of the ServiceProperties to the stream in xml format. - * - * @param opContext - * a tracking object for the request - * @return a byte array of the content to write to the stream. - * @throws XMLStreamException - * if there is an error writing content to the stream. - * @throws StorageException - */ - public byte[] serializeToByteArray(final OperationContext opContext) throws XMLStreamException, StorageException { - Utility.assertNotNull("Logging", this.getLogging()); - Utility.assertNotNull("Logging.LogOperationTypes", this.getLogging().getLogOperationTypes()); - Utility.assertNotNull("Merics", this.getMetrics()); - Utility.assertNotNull("Merics.Configuration", this.getMetrics().getMetricsLevel()); - - final StringWriter outWriter = new StringWriter(); - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outWriter); - - // default is UTF8 - xmlw.writeStartDocument(); - xmlw.writeStartElement(Constants.AnalyticsConstants.STORAGE_SERVICE_PROPERTIES_ELEMENT); - - // Logging - xmlw.writeStartElement(Constants.AnalyticsConstants.LOGGING_ELEMENT); - - // Version - xmlw.writeStartElement(Constants.AnalyticsConstants.VERSION_ELEMENT); - xmlw.writeCharacters(this.getLogging().getVersion()); - xmlw.writeEndElement(); - - // Delete - xmlw.writeStartElement(Constants.AnalyticsConstants.DELETE_ELEMENT); - xmlw.writeCharacters(this.getLogging().getLogOperationTypes().contains(LoggingOperations.DELETE) ? Constants.TRUE - : Constants.FALSE); - xmlw.writeEndElement(); - - // Read - xmlw.writeStartElement(Constants.AnalyticsConstants.READ_ELEMENT); - xmlw.writeCharacters(this.getLogging().getLogOperationTypes().contains(LoggingOperations.READ) ? Constants.TRUE - : Constants.FALSE); - xmlw.writeEndElement(); - - // Write - xmlw.writeStartElement(Constants.AnalyticsConstants.WRITE_ELEMENT); - xmlw.writeCharacters(this.getLogging().getLogOperationTypes().contains(LoggingOperations.WRITE) ? Constants.TRUE - : Constants.FALSE); - xmlw.writeEndElement(); - - // Retention Policy - writeRetentionPolicy(xmlw, this.getLogging().getRetentionIntervalInDays()); - - // end Logging - xmlw.writeEndElement(); - - // Metrics - xmlw.writeStartElement(Constants.AnalyticsConstants.METRICS_ELEMENT); - - // Version - xmlw.writeStartElement(Constants.AnalyticsConstants.VERSION_ELEMENT); - xmlw.writeCharacters(this.getMetrics().getVersion()); - xmlw.writeEndElement(); - - // Enabled - xmlw.writeStartElement(Constants.AnalyticsConstants.ENABLED_ELEMENT); - xmlw.writeCharacters(this.getMetrics().getMetricsLevel() != MetricsLevel.DISABLED ? Constants.TRUE - : Constants.FALSE); - xmlw.writeEndElement(); - - if (this.getMetrics().getMetricsLevel() != MetricsLevel.DISABLED) { - // Include APIs - xmlw.writeStartElement(Constants.AnalyticsConstants.INCLUDE_APIS_ELEMENT); - xmlw.writeCharacters(this.getMetrics().getMetricsLevel() == MetricsLevel.SERVICE_AND_API ? Constants.TRUE - : Constants.FALSE); - xmlw.writeEndElement(); - } - - // Retention Policy - writeRetentionPolicy(xmlw, this.getMetrics().getRetentionIntervalInDays()); - - // end Metrics - xmlw.writeEndElement(); - - // Default Service Version - if (this.getDefaultServiceVersion() != null) { - xmlw.writeStartElement(Constants.AnalyticsConstants.DEFAULT_SERVICE_VERSION); - xmlw.writeCharacters(this.getDefaultServiceVersion()); - xmlw.writeEndElement(); - } - - // end StorageServiceProperties - xmlw.writeEndElement(); - - // end doc - xmlw.writeEndDocument(); - - try { - return outWriter.toString().getBytes("UTF8"); - } - catch (final UnsupportedEncodingException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - /** - * @param defaultServiceVersion - * the defaultServiceVersion to set - */ - public void setDefaultServiceVersion(final String defaultServiceVersion) { - this.defaultServiceVersion = defaultServiceVersion; - } - - /** - * @param logging - * the logging to set - */ - public void setLogging(final LoggingProperties logging) { - this.logging = logging; - } - - /** - * @param metrics - * the metrics to set - */ - public void setMetrics(final MetricsProperties metrics) { - this.metrics = metrics; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentials.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentials.java deleted file mode 100644 index a766631e84b50..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentials.java +++ /dev/null @@ -1,497 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Represents a set of credentials used to authenticate access to a Windows Azure storage account. This is the base - * class for the {@link StorageCredentialsAccountAndKey} and {@link StorageCredentialsSharedAccessSignature} classes. - */ -public abstract class StorageCredentials { - - /** - * Tries to determine the storage credentials from a collection of name/value pairs. - * - * @param settings - * A HashMap object of the name/value pairs that represent the settings to use to configure - * the credentials. - *

- * Either include an account name with an account key (specifying values for - * {@link CloudStorageAccount#ACCOUNT_NAME_NAME} and {@link CloudStorageAccount#ACCOUNT_KEY_NAME} ), or a - * shared access signature (specifying a value for - * {@link CloudStorageAccount#SHARED_ACCESS_SIGNATURE_NAME} ). If you use an account name and account - * key, do not include a shared access signature, and vice versa. - * - * @return A {@link StorageCredentials} object representing the storage credentials determined from the name/value - * pairs. - * - * @throws InvalidKeyException - * If the key value specified for {@link CloudStorageAccount#ACCOUNT_KEY_NAME} is not a valid - * Base64-encoded string. - */ - protected static StorageCredentials tryParseCredentials(final HashMap settings) - throws InvalidKeyException { - final String accountName = settings.get(CloudStorageAccount.ACCOUNT_NAME_NAME) != null ? settings - .get(CloudStorageAccount.ACCOUNT_NAME_NAME) : null; - - final String accountKey = settings.get(CloudStorageAccount.ACCOUNT_KEY_NAME) != null ? settings - .get(CloudStorageAccount.ACCOUNT_KEY_NAME) : null; - - final String sasSignature = settings.get(CloudStorageAccount.SHARED_ACCESS_SIGNATURE_NAME) != null ? settings - .get(CloudStorageAccount.SHARED_ACCESS_SIGNATURE_NAME) : null; - - if (accountName != null && accountKey != null && sasSignature == null) { - if (Base64.validateIsBase64String(accountKey)) { - return new StorageCredentialsAccountAndKey(accountName, accountKey); - } - else { - throw new InvalidKeyException("Storage Key is not a valid base64 encoded string."); - } - } - if (accountName == null && accountKey == null && sasSignature != null) { - return new StorageCredentialsSharedAccessSignature(sasSignature); - } - - return null; - } - - /** - * Tries to determine the storage credentials from a connection string. - * - * @param connectionString - * A String that contains the key/value pairs that represent the storage credentials. - *

- * The format for the connection string is in the pattern "keyname=value". Multiple key/value - * pairs can be separated by a semi-colon, for example, "keyname1=value1;keyname2=value2". - * - * @return A {@link StorageCredentials} object representing the storage credentials determined from the connection - * string. - * - * @throws InvalidKeyException - * If the account key specified in connectionString is not valid. - * @throws StorageException - * If a storage service error occurred. - */ - public static StorageCredentials tryParseCredentials(final String connectionString) throws InvalidKeyException, - StorageException { - return tryParseCredentials(Utility.parseAccountString(connectionString)); - } - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // ComputeHmac method will return a valid HMAC-encoded - // signature string when called using the specified credentials. - // - // @return True if these credentials will yield a valid - // signature string; otherwise, false - // - /** Reserved. */ - public abstract boolean canCredentialsComputeHmac(); - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key authentication scheme using - // the specified credentials. - // - // @return True if a request can be signed with these - // credentials; otherwise, false - // - /** Reserved. */ - public abstract boolean canCredentialsSignRequest(); - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key Lite authentication scheme - // using the specified credentials. - // - // @return true if a request can be signed with these - // credentials; otherwise, false - // - /** Reserved. */ - public abstract boolean canCredentialsSignRequestLite(); - - /** - * Computes a signature for the specified string using the HMAC-SHA256 algorithm. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @return A String that contains the HMAC-SHA256-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - public abstract String computeHmac256(String value) throws InvalidKeyException; - - /** - * Computes a signature for the specified string using the HMAC-SHA256 algorithm with the specified operation - * context. - * - * @param value - * The UTF-8-encoded string to sign. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A String that contains the HMAC-SHA256-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - public abstract String computeHmac256(String value, OperationContext opContext) throws InvalidKeyException; - - /** - * Computes a signature for the specified string using the HMAC-SHA512 algorithm. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @return A String that contains the HMAC-SHA512-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - public abstract String computeHmac512(String value) throws InvalidKeyException; - - /** - * Computes a signature for the specified string using the HMAC-SHA512 algorithm with the specified operation - * context. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A String that contains the HMAC-SHA512-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - public abstract String computeHmac512(String value, OperationContext opContext) throws InvalidKeyException; - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // TransformUri method should be called to transform a resource - // URI to a URI that includes a token for a shared access signature. - // - // @return True if the URI must be transformed; otherwise, - // false - // - /** Reserved. */ - public abstract boolean doCredentialsNeedTransformUri(); - - /** - * Returns the associated account name for the credentials. - * - * @return A String that represents the associated account name for the credentials - */ - public abstract String getAccountName(); - - /** - * Signs a request under the Shared Key authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * - * @throws StorageException - * If a storage service error occurred. - */ - @Deprecated - public abstract void signRequest(HttpURLConnection request, long contentLength) throws InvalidKeyException, - StorageException; - - /** - * Signs a request using the specified operation context under the Shared Key authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Deprecated - public abstract void signRequest(HttpURLConnection request, long contentLength, OperationContext opContext) - throws InvalidKeyException, StorageException; - - /** - * Signs a table request under the Shared Key Lite authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If an unspecified storage exception occurs. - */ - @Deprecated - public abstract void signRequestLite(HttpURLConnection request, long contentLength) throws StorageException, - InvalidKeyException; - - /** - * Signs a table request using the specified operation context under the Shared Key Lite authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Deprecated - public abstract void signRequestLite(HttpURLConnection request, long contentLength, OperationContext opContext) - throws StorageException, InvalidKeyException; - - /** - * Signs a request under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * - * @throws StorageException - * If a storage service error occurred. - */ - public abstract void signBlobAndQueueRequest(HttpURLConnection request, long contentLength) - throws InvalidKeyException, StorageException; - - /** - * Signs a request using the specified operation context under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - public abstract void signBlobAndQueueRequest(HttpURLConnection request, long contentLength, - OperationContext opContext) throws InvalidKeyException, StorageException; - - /** - * Signs a request under the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If an unspecified storage exception occurs. - */ - public abstract void signBlobAndQueueRequestLite(HttpURLConnection request, long contentLength) - throws StorageException, InvalidKeyException; - - /** - * Signs a request using the specified operation context under the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - public abstract void signBlobAndQueueRequestLite(HttpURLConnection request, long contentLength, - OperationContext opContext) throws StorageException, InvalidKeyException; - - /** - * Signs a table request under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * - * @throws StorageException - * If a storage service error occurred. - */ - public abstract void signTableRequest(HttpURLConnection request, long contentLength) throws InvalidKeyException, - StorageException; - - /** - * Signs a table request using the specified operation context under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - public abstract void signTableRequest(HttpURLConnection request, long contentLength, OperationContext opContext) - throws InvalidKeyException, StorageException; - - /** - * Signs a table request under the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If an unspecified storage exception occurs. - */ - public abstract void signTableRequestLite(HttpURLConnection request, long contentLength) throws StorageException, - InvalidKeyException; - - /** - * Signs a table request using the specified operation context under the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - - public abstract void signTableRequestLite(HttpURLConnection request, long contentLength, OperationContext opContext) - throws StorageException, InvalidKeyException; - - /** - * Returns a String that represents this instance. - * - * @param exportSecrets - * true to include sensitive data in the return string; otherwise, false. - * @return A String that represents this object, optionally including sensitive data. - */ - public abstract String toString(boolean exportSecrets); - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token. - * - * @param resourceUri - * A java.net.URI object that represents the resource URI to be transformed. - * - * @return A java.net.URI object that represents the signature, including the resource URI and the - * shared access token. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is not properly formatted. - */ - public abstract URI transformUri(URI resourceUri) throws URISyntaxException, StorageException; - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token and using the - * specified operation context. - * - * @param resourceUri - * A java.net.URI object that represents the resource URI to be transformed. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A java.net.URI object that represents the signature, including the resource URI and the - * shared access token. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is not properly formatted. - */ - public abstract URI transformUri(URI resourceUri, OperationContext opContext) throws URISyntaxException, - StorageException; - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsAccountAndKey.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsAccountAndKey.java deleted file mode 100644 index 27fd4f9cac3f1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsAccountAndKey.java +++ /dev/null @@ -1,573 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; - -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseRequest; - -/** - * Represents storage account credentials, based on storage account and access key, for accessing the Windows Azure - * storage services. - */ -public final class StorageCredentialsAccountAndKey extends StorageCredentials { - - /** - * The internal Credentials associated with the StorageCredentials. - */ - private Credentials credentials; - - /** - * Creates an instance of the StorageCredentialsAccountAndKey class, using the specified storage - * account name and access key; the specified access key is in the form of a byte array. - * - * @param accountName - * A String that represents the name of the storage account. - * @param key - * An array of bytes that represent the account access key. - */ - public StorageCredentialsAccountAndKey(final String accountName, final byte[] key) { - this.credentials = new Credentials(accountName, key); - } - - /** - * Creates an instance of the StorageCredentialsAccountAndKey class, using the specified storage - * account name and access key; the specified access key is stored as a String. - * - * @param accountName - * A String that represents the name of the storage account. - * @param key - * A String that represents the Base-64-encoded account access key. - */ - public StorageCredentialsAccountAndKey(final String accountName, final String key) { - this(accountName, Base64.decode(key)); - } - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // ComputeHmac method will return a valid HMAC-encoded - // signature string when called using the specified credentials. - // - // @return True - // - /** Reserved. */ - @Override - public boolean canCredentialsComputeHmac() { - return true; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key authentication scheme using - // the specified credentials. - // - // @return True - // - /** Reserved. */ - @Override - public boolean canCredentialsSignRequest() { - return true; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key Lite authentication scheme - // using the specified credentials. - // - // @return True - // - /** Reserved. */ - @Override - public boolean canCredentialsSignRequestLite() { - return true; - } - - /** - * Computes a signature for the specified string using the HMAC-SHA256 algorithm. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @return A String that contains the HMAC-SHA256-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - @Override - public String computeHmac256(final String value) throws InvalidKeyException { - return this.computeHmac256(value, null); - } - - /** - * Computes a signature for the specified string using the HMAC-SHA256 algorithm with the specified operation - * context. - * - * @param value - * The UTF-8-encoded string to sign. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A String that contains the HMAC-SHA256-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - @Override - public String computeHmac256(final String value, final OperationContext opContext) throws InvalidKeyException { - return StorageKey.computeMacSha256(this.credentials.getKey(), value); - } - - /** - * Computes a signature for the specified string using the HMAC-SHA512 algorithm. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @return A String that contains the HMAC-SHA512-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - @Override - public String computeHmac512(final String value) throws InvalidKeyException { - return this.computeHmac512(value, null); - } - - /** - * Computes a signature for the specified string using the HMAC-SHA512 algorithm with the specified operation - * context. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A String that contains the HMAC-SHA512-encoded signature. - * - * @throws InvalidKeyException - * If the key is not a valid Base64-encoded string. - */ - @Override - public String computeHmac512(final String value, final OperationContext opContext) throws InvalidKeyException { - return StorageKey.computeMacSha512(this.credentials.getKey(), value); - } - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // TransformUri method should be called to transform a resource - // URI to a URI that includes a token for a shared access signature. - // - // @return False. - // - /** Reserved. */ - @Override - public boolean doCredentialsNeedTransformUri() { - return false; - } - - /** - * Returns the associated account name for the credentials. - * - * @return A String that contains the account name for the credentials. - */ - @Override - public String getAccountName() { - return this.credentials.getAccountName(); - } - - /** - * Internal usage. - * Gets the name of the key used by these credentials. - */ - public String getAccountKeyName() { - return this.credentials.getKeyName(); - } - - /** - * Internal usage. - * Sets the account name that owns the key to use when signing requests. - */ - public void setSigningAccountName(final String signingAccountName) { - this.credentials.setSigningAccountName(signingAccountName); - } - - /** - * Returns the Base64-encoded key for the credentials. - * - * @return A String that contains the Base64-encoded key. - */ - protected String getBase64EncodedKey() { - return this.credentials.getKey().getBase64EncodedKey(); - } - - /** - * Returns the internal credentials associated with the storage credentials. - * - * @return A Credentials object that contains the internal credentials associated with this instance of - * the StorageCredentialsAccountAndKey class. - */ - public Credentials getCredentials() { - return this.credentials; - } - - /** - * Sets the credentials. - * - * @param credentials - * A Credentials object that represents the credentials to set for this instance of the - * StorageCredentialsAccountAndKey class. - */ - public void setCredentials(final Credentials credentials) { - this.credentials = credentials; - } - - /** - * Signs a request under the Shared Key authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - @Deprecated - public void signRequest(final java.net.HttpURLConnection request, final long contentLength) - throws InvalidKeyException, StorageException { - this.signBlobAndQueueRequest(request, contentLength, null); - } - - /** - * Signs a request using the specified operation context under the Shared Key authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - @Deprecated - public void signRequest(final java.net.HttpURLConnection request, final long contentLength, - OperationContext opContext) throws InvalidKeyException, StorageException { - opContext = opContext == null ? new OperationContext() : opContext; - BaseRequest.signRequestForBlobAndQueue(request, this.credentials, contentLength, opContext); - } - - /** - * Signs a request using the Shared Key Lite authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If an unspecified storage exception occurs. - */ - @Override - @Deprecated - public void signRequestLite(final java.net.HttpURLConnection request, final long contentLength) - throws InvalidKeyException, StorageException { - this.signTableRequestLite(request, contentLength, null); - } - - /** - * Signs a request using the specified operation context under the Shared Key Lite authentication scheme. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - @Deprecated - public void signRequestLite(final java.net.HttpURLConnection request, final long contentLength, - OperationContext opContext) throws StorageException, InvalidKeyException { - opContext = opContext == null ? new OperationContext() : opContext; - BaseRequest.signRequestForTableSharedKeyLite(request, this.credentials, contentLength, opContext); - } - - /** - * Signs a request under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - public void signBlobAndQueueRequest(final java.net.HttpURLConnection request, final long contentLength) - throws InvalidKeyException, StorageException { - this.signBlobAndQueueRequest(request, contentLength, null); - } - - /** - * Signs a request using the specified operation context under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - public void signBlobAndQueueRequest(final java.net.HttpURLConnection request, final long contentLength, - OperationContext opContext) throws InvalidKeyException, StorageException { - opContext = opContext == null ? new OperationContext() : opContext; - BaseRequest.signRequestForBlobAndQueue(request, this.credentials, contentLength, opContext); - } - - /** - * Signs a request using the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If an unspecified storage exception occurs. - */ - @Override - public void signBlobAndQueueRequestLite(final java.net.HttpURLConnection request, final long contentLength) - throws InvalidKeyException, StorageException { - this.signBlobAndQueueRequestLite(request, contentLength, null); - } - - /** - * Signs a request using the specified operation context under the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - public void signBlobAndQueueRequestLite(final java.net.HttpURLConnection request, final long contentLength, - OperationContext opContext) throws StorageException, InvalidKeyException { - opContext = opContext == null ? new OperationContext() : opContext; - BaseRequest.signRequestForBlobAndQueueSharedKeyLite(request, this.credentials, contentLength, opContext); - } - - /** - * Signs a request under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - public void signTableRequest(final java.net.HttpURLConnection request, final long contentLength) - throws InvalidKeyException, StorageException { - this.signTableRequest(request, contentLength, null); - } - - /** - * Signs a request using the specified operation context under the Shared Key authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - public void signTableRequest(final java.net.HttpURLConnection request, final long contentLength, - OperationContext opContext) throws InvalidKeyException, StorageException { - opContext = opContext == null ? new OperationContext() : opContext; - BaseRequest.signRequestForTableSharedKey(request, this.credentials, contentLength, opContext); - } - - /** - * Signs a request using the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If an unspecified storage exception occurs. - */ - @Override - public void signTableRequestLite(final java.net.HttpURLConnection request, final long contentLength) - throws InvalidKeyException, StorageException { - this.signTableRequestLite(request, contentLength, null); - } - - /** - * Signs a request using the specified operation context under the Shared Key Lite authentication scheme. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws InvalidKeyException - * If the given key is invalid. - * @throws StorageException - * If a storage service error occurred. - */ - @Override - public void signTableRequestLite(final java.net.HttpURLConnection request, final long contentLength, - OperationContext opContext) throws StorageException, InvalidKeyException { - opContext = opContext == null ? new OperationContext() : opContext; - BaseRequest.signRequestForTableSharedKeyLite(request, this.credentials, contentLength, opContext); - } - - /** - * Returns a String that represents this instance, optionally including sensitive data. - * - * @param exportSecrets - * true to include sensitive data in the return string; otherwise, false. - * - * @return A String that represents this object, optionally including sensitive data. - */ - @Override - public String toString(final boolean exportSecrets) { - return String.format("%s=%s;%s=%s", CloudStorageAccount.ACCOUNT_NAME_NAME, this.getAccountName(), - CloudStorageAccount.ACCOUNT_KEY_NAME, exportSecrets ? this.credentials.getKey().getBase64EncodedKey() - : "[key hidden]"); - } - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token. - * - * @param resourceUri - * A java.net.URI object that represents the resource URI to be transformed. - * - * @return A java.net.URI object that represents the signature, including the resource URI and the - * shared access token. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is not properly formatted. - */ - @Override - public URI transformUri(final URI resourceUri) { - return this.transformUri(resourceUri, null); - } - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token and using the - * specified operation context. - * - * @param resourceUri - * A java.net.URI object that represents the resource URI to be transformed. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A java.net.URI object that represents the signature, including the resource URI and the - * shared access token. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is not properly formatted. - */ - @Override - public URI transformUri(final URI resourceUri, final OperationContext opContext) { - return resourceUri; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsAnonymous.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsAnonymous.java deleted file mode 100644 index 7ceb94a78675f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsAnonymous.java +++ /dev/null @@ -1,415 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.URI; - -/** - * *RESERVED FOR INTERNAL USE* Represents credentials for anonymous access. This class is used by the internal - * implementation (not a public class, so its comments are not built into the Javadoc output). - */ -public final class StorageCredentialsAnonymous extends StorageCredentials { - - /** - * Stores the singleton instance of this class. - */ - public static final StorageCredentials ANONYMOUS = new StorageCredentialsAnonymous(); - - /** - * Returns the singleton instance of the StorageCredentials class. - * - * @return the singleton instance of this class - */ - protected static StorageCredentials getInstance() { - return StorageCredentialsAnonymous.ANONYMOUS; - } - - /** - * Enforces the singleton pattern via a private constructor. - */ - protected StorageCredentialsAnonymous() { - // Empty Default Ctor - } - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // ComputeHmac method will return a valid HMAC-encoded - // signature string when called using the specified credentials. - // - // @return False - // - /** Reserved. */ - @Override - public boolean canCredentialsComputeHmac() { - return false; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key authentication scheme using - // the specified credentials. - // - // @return False - // - /** Reserved. */ - @Override - public boolean canCredentialsSignRequest() { - return false; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key Lite authentication scheme - // using the specified credentials. - // - // @return False - // - /** Reserved. */ - @Override - public boolean canCredentialsSignRequestLite() { - return false; - } - - /** - * Encodes a Shared Key or Shared Key Lite signature string by using the HMAC-SHA256 algorithm over a UTF-8-encoded - * string-to-sign. This is not a valid operation for objects of type StorageCredentialsAnonymous so the - * method merely returns null. - * - * @param value - * the UTF-8-encoded string-to-sign - * @return null for objects of type StorageCredentialsAnonymous - */ - @Override - public String computeHmac256(final String value) { - return null; - } - - /** - * Encodes a Shared Key or Shared Key Lite signature string by using the HMAC-SHA256 algorithm over a UTF-8-encoded - * string-to-sign and the specified operation context. This is not a valid operation for objects of type - * StorageCredentialsAnonymous so the method merely returns null. - * - * @param value - * the UTF-8-encoded string-to-sign - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - * @return null for objects of type StorageCredentialsAnonymous - */ - @Override - public String computeHmac256(final String value, final OperationContext opContext) { - return null; - } - - /** - * Encodes a Shared Key signature string by using the HMAC-SHA512 algorithm over a UTF-8-encoded string-to-sign. - * This is not a valid operation for objects of type StorageCredentialsAnonymous so the method merely - * returns null. - * - * @param value - * the UTF-8-encoded string-to-sign - * @return null for objects of type StorageCredentialsAnonymous - */ - @Override - public String computeHmac512(final String value) { - return null; - } - - /** - * Encodes a Shared Key signature string by using the HMAC-SHA256 algorithm over a UTF-8-encoded string-to-sign. - * This is not a valid operation for objects of type StorageCredentialsAnonymous so the method merely - * returns null. - * - * @param value - * the UTF-8-encoded string-to-sign - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - * - * @return null for objects of type StorageCredentialsAnonymous - */ - @Override - public String computeHmac512(final String value, final OperationContext opContext) { - return null; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // TransformUri method should be called to transform a resource - // URI to a URI that includes a token for a shared access signature. - // - // @return False. - // - /** Reserved. */ - @Override - public boolean doCredentialsNeedTransformUri() { - return false; - } - - /** - * Returns the associated account name for the credentials. This is null for anonymous credentials. - * - * @return null for anonymous credentials - */ - @Override - public String getAccountName() { - return null; - } - - /** - * Signs a request using the specified credentials under the Shared Key authentication scheme. This is not a valid - * operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - */ - @Override - @Deprecated - public void signRequest(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials and operation context under the Shared Key authentication scheme. - * This is not a valid operation for objects of type StorageCredentialsAnonymous so the method performs - * a no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - @Deprecated - public void signRequest(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - */ - @Override - @Deprecated - public void signRequestLite(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsSharedAccessSignature so the method performs a - * no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - @Deprecated - public void signRequestLite(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key authentication scheme. This is not a valid - * operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - */ - @Override - public void signBlobAndQueueRequest(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials and operation context under the Shared Key authentication scheme. - * This is not a valid operation for objects of type StorageCredentialsAnonymous so the method performs - * a no-op. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - public void signBlobAndQueueRequest(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - */ - @Override - public void signBlobAndQueueRequestLite(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsSharedAccessSignature so the method performs a - * no-op. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - public void signBlobAndQueueRequestLite(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key authentication scheme. This is not a valid - * operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - */ - @Override - public void signTableRequest(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials and operation context under the Shared Key authentication scheme. - * This is not a valid operation for objects of type StorageCredentialsAnonymous so the method performs - * a no-op. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - public void signTableRequest(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - */ - @Override - public void signTableRequestLite(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsSharedAccessSignature so the method performs a - * no-op. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - public void signTableRequestLite(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Returns a String object that represents this instance. - * - * @param exportSecrets - * true to include sensitive data in the string; otherwise, false - * @return a string representation of the credentials, optionally including sensitive data. - */ - @Override - public String toString(final boolean exportSecrets) { - return Constants.EMPTY_STRING; - } - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token. No transform - * occurs for anonymous credentials, so this method returns the same URI that is passed in. - * - * @param resourceUri - * the resource URI to be transformed - * @return the unmodified value passed in for the resourceUri parameter - */ - @Override - public URI transformUri(final URI resourceUri) { - return this.transformUri(resourceUri, null); - } - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token. No transform - * occurs for anonymous credentials, so this method returns the same URI that is passed in. - * - * @param resourceUri - * the resource URI to be transformed - * @param opContext - * the an operation context, as a - * {@link com.microsoft.windowsazure.services.core.storage.OperationContext} object, that represents the - * current operation - * - * @return the unmodified value passed in for the resourceUri parameter - */ - @Override - public URI transformUri(final URI resourceUri, final OperationContext opContext) { - return resourceUri; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsSharedAccessSignature.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsSharedAccessSignature.java deleted file mode 100644 index 8e0d609f5fe60..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageCredentialsSharedAccessSignature.java +++ /dev/null @@ -1,456 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.net.URI; -import java.net.URISyntaxException; - -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; - -/** - * Represents storage credentials for delegated access to Blob service resources via a shared access signature. - */ -public final class StorageCredentialsSharedAccessSignature extends StorageCredentials { - - /** - * Stores the shared access signature token. - */ - private final String token; - - /** - * Creates an instance of the StorageCredentialsSharedAccessSignature class using the specified shared - * access signature token. - * - * @param token - * A String that represents shared access signature token. - */ - public StorageCredentialsSharedAccessSignature(final String token) { - this.token = token; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // ComputeHmac method will return a valid HMAC-encoded - // signature string when called using the specified credentials. - // - // @return False - // - /** Reserved. */ - @Override - public boolean canCredentialsComputeHmac() { - return false; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key authentication scheme using - // the specified credentials. - // - // @return False - // - /** Reserved. */ - @Override - public boolean canCredentialsSignRequest() { - return false; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether a - // request can be signed under the Shared Key Lite authentication scheme - // using the specified credentials. - // - // @return False - // - /** Reserved. */ - @Override - public boolean canCredentialsSignRequestLite() { - return false; - } - - /** - * Computes a signature for the specified string using the HMAC-SHA256 algorithm. This is not a valid operation for - * objects of type StorageCredentialsSharedAccessSignature so the method merely returns - * null. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @return null for objects of type StorageCredentialsSharedAccessSignature. - */ - @Override - public String computeHmac256(final String value) { - return null; - } - - /** - * Computes a signature for the specified string using the HMAC-SHA256 algorithm with the specified operation - * context. This is not a valid operation for objects of type StorageCredentialsSharedAccessSignature - * so the method merely returns null. - * - * @param value - * The UTF-8-encoded string to sign. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return null for objects of type StorageCredentialsSharedAccessSignature. - */ - @Override - public String computeHmac256(final String value, final OperationContext opContext) { - return null; - } - - /** - * Computes a signature for the specified string using the HMAC-SHA512 algorithm. This is not a valid operation for - * objects of type StorageCredentialsSharedAccessSignature so the method merely returns - * null. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @return null for objects of type StorageCredentialsSharedAccessSignature. - */ - @Override - public String computeHmac512(final String value) { - return null; - } - - /** - * Computes a signature for the specified string using the HMAC-SHA512 algorithm with the specified operation - * context. This is not a valid operation for objects of type StorageCredentialsSharedAccessSignature - * so the method merely returns null. - * - * @param value - * The UTF-8-encoded string to sign. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return null for objects of type StorageCredentialsSharedAccessSignature. - */ - @Override - public String computeHmac512(final String value, final OperationContext opContext) { - return null; - } - - // - // RESERVED, for internal use only. Gets a value indicating whether the - // TransformUri method should be called to transform a resource - // URI to a URI that includes a token for a shared access signature. - // - // @return True. - // - /** Reserved. */ - @Override - public boolean doCredentialsNeedTransformUri() { - return true; - } - - /** - * Returns the associated account name for the credentials. This is not a valid operation for objects of type - * StorageCredentialsSharedAccessSignature so the method merely returns null. - * - * @return null for objects of type StorageCredentialsSharedAccessSignature. - */ - @Override - public String getAccountName() { - return null; - } - - /** - * Returns the shared access signature token. - * - * @return A String that contains the token. - */ - public String getToken() { - return this.token; - } - - /** - * Signs a request using the specified credentials under the Shared Key authentication scheme. This is not a valid - * operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - */ - @Override - @Deprecated - public void signRequest(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials and operation context under the Shared Key authentication scheme. - * This is not a valid operation for objects of type StorageCredentialsAnonymous so the method performs - * a no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signBlobAndQueueRequest} or - * {@link signBlobAndQueueRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param contentLength - * the length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - @Deprecated - public void signRequest(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsAnonymous so the method performs a no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param connection - * the request, as an HttpURLConnection object, to sign - */ - @Override - @Deprecated - public void signRequestLite(final java.net.HttpURLConnection connection, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified credentials under the Shared Key Lite authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsSharedAccessSignature so the method performs a - * no-op. - * - * @deprecated This method has been deprecated. Please use either {@link signTableRequest} or - * {@link signTableRequestLite}, depending on your desired shared key authentication scheme. - * - * @param request - * the request, as an HttpURLConnection object, to sign - * @param opContext - * an operation context, as a {@link com.microsoft.windowsazure.services.core.storage.OperationContext} - * object, that represents the current operation - */ - @Override - @Deprecated - public void signRequestLite(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request under the Shared Key authentication scheme. This is not a valid operation for objects of type - * StorageCredentialsSharedAccessSignature so the method performs a no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - */ - @Override - public void signBlobAndQueueRequest(final java.net.HttpURLConnection request, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified operation context under the Shared Key authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsSharedAccessSignature so the method performs a - * no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - */ - @Override - public void signBlobAndQueueRequest(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request under the Shared Key Lite authentication scheme. This is not a valid operation for objects of - * type StorageCredentialsSharedAccessSignature so the method performs a no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - */ - @Override - public void signBlobAndQueueRequestLite(final java.net.HttpURLConnection request, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified operation context under the Shared Key Lite authentication scheme. This is - * not a valid operation for objects of type StorageCredentialsSharedAccessSignature so the method - * performs a no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - */ - @Override - public void signBlobAndQueueRequestLite(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request under the Shared Key authentication scheme. This is not a valid operation for objects of type - * StorageCredentialsSharedAccessSignature so the method performs a no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - */ - @Override - public void signTableRequest(final java.net.HttpURLConnection request, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified operation context under the Shared Key authentication scheme. This is not a - * valid operation for objects of type StorageCredentialsSharedAccessSignature so the method performs a - * no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - */ - @Override - public void signTableRequest(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Signs a request under the Shared Key Lite authentication scheme. This is not a valid operation for objects of - * type StorageCredentialsSharedAccessSignature so the method performs a no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - */ - @Override - public void signTableRequestLite(final java.net.HttpURLConnection request, final long contentLength) { - // No op - } - - /** - * Signs a request using the specified operation context under the Shared Key Lite authentication scheme. This is - * not a valid operation for objects of type StorageCredentialsSharedAccessSignature so the method - * performs a no-op. - * - * @param request - * An HttpURLConnection object that represents the request to sign. - * @param contentLength - * The length of the content written to the output stream. If unknown, specify -1. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - */ - @Override - public void signTableRequestLite(final java.net.HttpURLConnection request, final long contentLength, - final OperationContext opContext) { - // No op - } - - /** - * Returns a String that represents this instance, optionally including sensitive data. - * - * @param exportSecrets - * true to include sensitive data in the return string; otherwise, false. - * @return A String that represents this object, optionally including sensitive data. - */ - @Override - public String toString(final boolean exportSecrets) { - return String.format("%s=%s", CloudStorageAccount.SHARED_ACCESS_SIGNATURE_NAME, exportSecrets ? this.token - : "[signature hidden]"); - } - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token. - * - * @param resourceUri - * A java.net.URI object that represents the resource URI to be transformed. - * - * @return A java.net.URI object that represents the signature, including the resource URI and the - * shared access token. - * - * @throws IllegalArgumentException - * If a parameter is invalid. - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is not properly formatted. - */ - @Override - public URI transformUri(final URI resourceUri) throws URISyntaxException, StorageException { - return this.transformUri(resourceUri, null); - } - - /** - * Transforms a resource URI into a shared access signature URI, by appending a shared access token and using the - * specified operation context. - * - * @param resourceUri - * A java.net.URI object that represents the resource URI to be transformed. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A java.net.URI object that represents the signature, including the resource URI and the - * shared access token. - * - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is not properly formatted. - */ - @Override - public URI transformUri(final URI resourceUri, final OperationContext opContext) throws URISyntaxException, - StorageException { - return PathUtility.addToQuery(resourceUri, this.token); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageErrorCode.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageErrorCode.java deleted file mode 100644 index dabdb60691078..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageErrorCode.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * - * Represents error codes that may be returned by the Windows Azure storage services or the storage client library. - */ -public enum StorageErrorCode { - /** - * Access was denied (client-side error). - */ - ACCESS_DENIED(12), - - /** - * The specified account was not found (client-side error). - */ - ACCOUNT_NOT_FOUND(8), - - /** - * An authentication error occurred (client-side error). - */ - AUTHENTICATION_FAILURE(11), - - /** - * There was an error with the gateway used for the request (client-side error). - */ - BAD_GATEWAY(18), - - /** - * The request was incorrect or badly formed (client-side error). - */ - BAD_REQUEST(16), - - /** - * The specified blob already exists (client-side error). - */ - BLOB_ALREADY_EXISTS(15), - - /** - * The specified blob was not found (client-side error). - */ - BLOB_NOT_FOUND(10), - - /** - * The specified condition failed (client-side error). - */ - CONDITION_FAILED(17), - - /** - * The specified container already exists (client-side error). - */ - CONTAINER_ALREADY_EXISTS(14), - - /** - * The specified container was not found (client-side error). - */ - CONTAINER_NOT_FOUND(9), - - /** - * The request version header is not supported (client-side error). - */ - HTTP_VERSION_NOT_SUPPORTED(20), - - /** - * No error specified. - */ - NONE(0), - - /** - * The requested operation is not implemented on the specified resource (client-side error). - */ - NOT_IMPLEMENTED(19), - - /** - * The specified resource already exists (client-side error). - */ - RESOURCE_ALREADY_EXISTS(13), - - /** - * The specified resource was not found (client-side error). - */ - RESOURCE_NOT_FOUND(7), - - /** - * The service returned a bad response (server-side error). - */ - SERVICE_BAD_REQUEST(6), - - /** - * A service integrity check failed (server-side error). - */ - SERVICE_INTEGRITY_CHECK_FAILED(4), - - /** - * An internal server error occurred (server-side error). - */ - SERVICE_INTERNAL_ERROR(1), - - /** - * The service timed out (server-side error). - */ - SERVICE_TIMEOUT(3), - - /** - * A transport error occurred (server-side error). - */ - TRANSPORT_ERROR(5), - - /** - * A lease is required to perform the operation. - */ - LEASE_ID_MISSING(21), - - /** - * The given lease ID does not match the current lease. - */ - LEASE_ID_MISMATCH(22), - - /** - * A lease ID was used when no lease currently is held. - */ - LEASE_NOT_PRESENT(23); - - /** - * Returns the value of this enum. - */ - public int value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - StorageErrorCode(final int val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageErrorCodeStrings.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageErrorCodeStrings.java deleted file mode 100644 index 3dee5cfadaea2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageErrorCodeStrings.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -/** - * Represents error code strings that are common to all storage services. - */ -public final class StorageErrorCodeStrings { - /** - * Authentication failed. - */ - public static final String AUTHENTICATION_FAILED = "AuthenticationFailed"; - - /** - * The specified condition was not met. - */ - public static final String CONDITION_NOT_MET = "ConditionNotMet"; - - /** - * The specified container already exists. - */ - public static final String CONTAINER_ALREADY_EXISTS = "ContainerAlreadyExists"; - - /** - * The specified queue already exists. - */ - public static final String QUEUE_ALREADY_EXISTS = "QueueAlreadyExists"; - - /** - * The specified container is being deleted. - */ - public static final String CONTAINER_BEING_DELETED = "ContainerBeingDeleted"; - - /** - * The specified queue is being deleted. - */ - public static final String QUEUE_BEING_DELETED = "QueueBeingDeleted"; - - /** - * The specified container is disabled. - */ - public static final String CONTAINER_DISABLED = "ContainerDisabled"; - - /** - * The specified container was not found. - */ - public static final String CONTAINER_NOT_FOUND = "ContainerNotFound"; - - /** - * An incorrect blob type was specified. - */ - public static final String INCORRECT_BLOB_TYPE = "IncorrectBlobType"; - - /** - * An incorrect blob type was specified. - */ - public static final String INVALID_BLOB_TYPE = "InvalidBlobType"; - - /** - * The metadata key is empty. - */ - public static final String EMPTY_METADATA_KEY = "EmptyMetadataKey"; - - /** - * An internal error occurred. - */ - public static final String INTERNAL_ERROR = "InternalError"; - - /** - * One or more header values are invalid. - */ - public static final String INVALID_HEADER_VALUE = "InvalidHeaderValue"; - - /** - * The HTTP verb is invalid. - */ - public static final String INVALID_HTTP_VERB = "InvalidHttpVerb"; - - /** - * The input is invalid. - */ - public static final String INVALID_INPUT = "InvalidInput"; - - /** - * The specified MD5 hash is invalid. - */ - public static final String INVALID_MD5 = "InvalidMd5"; - - /** - * The specified metadata is invalid. - */ - public static final String INVALID_METADATA = "InvalidMetadata"; - - /** - * One or more query parameters are invalid. - */ - public static final String INVALID_QUERY_PARAMETER_VALUE = "InvalidQueryParameterValue"; - - /** - * The specified range is invalid. - */ - public static final String INVALID_RANGE = "InvalidRange"; - - /** - * The URI is invalid. - */ - public static final String INVALID_URI = "InvalidUri"; - - /** - * The specified XML document is invalid. - */ - public static final String INVALID_XML_DOCUMENT = "InvalidXmlDocument"; - - /** - * One or more XML node values are invalid. - */ - public static final String INVALID_XML_NODE_VALUE = "InvalidXmlNodeValue"; - - /** - * The specified MD5 hash does not match the server value. - */ - public static final String MD5_MISMATCH = "Md5Mismatch"; - - /** - * The specified metadata is too large. - */ - public static final String METADATA_TOO_LARGE = "MetadataTooLarge"; - - /** - * The Content-Length header is required for this request. - */ - public static final String MISSING_CONTENT_LENGTH_HEADER = "MissingContentLengthHeader"; - - /** - * A required header was missing. - */ - public static final String MISSING_REQUIRED_HEADER = "MissingRequiredHeader"; - - /** - * A required query parameter is missing. - */ - public static final String MISSING_REQUIRED_QUERY_PARAMETER = "MissingRequiredQueryParameter"; - - /** - * A required XML node was missing. - */ - public static final String MISSING_REQUIRED_XML_NODE = "MissingRequiredXmlNode"; - - /** - * The operation timed out. - */ - public static final String OPERATION_TIMED_OUT = "OperationTimedOut"; - - /** - * The input is out of range. - */ - public static final String OUT_OF_RANGE_INPUT = "OutOfRangeInput"; - - /** - * One or more query parameters are out of range. - */ - public static final String OUT_OF_RANGE_QUERY_PARAMETER_VALUE = "OutOfRangeQueryParameterValue"; - - /** - * The request body is too large. - */ - public static final String REQUEST_BODY_TOO_LARGE = "RequestBodyTooLarge"; - - /** - * The specified resource was not found. - */ - public static final String RESOURCE_NOT_FOUND = "ResourceNotFound"; - - /** - * The server is busy. - */ - public static final String SERVER_BUSY = "ServerBusy"; - - /** - * Table Already Exists - */ - public static final String TABLE_ALREADY_EXISTS = "TableAlreadyExists"; - - /** - * One or more header values are not supported. - */ - public static final String UNSUPPORTED_HEADER = "UnsupportedHeader"; - - /** - * The specified HTTP verb is not supported. - */ - public static final String UNSUPPORTED_HTTP_VERB = "UnsupportedHttpVerb"; - - /** - * One or more query parameters is not supported. - */ - public static final String UNSUPPORTED_QUERY_PARAMETER = "UnsupportedQueryParameter"; - - /** - * One or more XML nodes are not supported. - */ - public static final String UNSUPPORTED_XML_NODE = "UnsupportedXmlNode"; - - /** - * The lease is already broken. - */ - public static final String LEASE_ALREADY_BROKEN = "LeaseAlreadyBroken"; - - /** - * The lease is already present. - */ - public static final String LEASE_ALREADY_PRESENT = "LeaseAlreadyPresent"; - - /** - * The lease ID is missing. - */ - public static final String LEASE_ID_MISSING = "LeaseIdMissing"; - - /** - * Private Default Ctor. - */ - private StorageErrorCodeStrings() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageEvent.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageEvent.java deleted file mode 100644 index e6ecffbedadff..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageEvent.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.util.EventListener; - -/** - * - * Abstract class that represents a generic event listener. - * - * @param - * The type of the event to be received. - */ -public abstract class StorageEvent implements EventListener { - /** - * Represents an event that occurred. - * - * @param eventArg - * The event object. - */ - public abstract void eventOccurred(T eventArg); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageEventMultiCaster.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageEventMultiCaster.java deleted file mode 100644 index f187a7ceb9c6d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageEventMultiCaster.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.util.ArrayList; - -/** - * Represents a generic event multi-caster that allows event listeners to be dynamically added and removed. - * - * @param - * An object that represents the type of the event. - * @param - * An object that represents the type of the event listener. - */ -public final class StorageEventMultiCaster> { - - /** - * Holds the list of listeners. - */ - private final ArrayList listeners = new ArrayList(); - - /** - * Adds a listener to the event chain. - * - * @param listener - * An EventListenerType object that represents the listener to add. - */ - public synchronized void addListener(final EVENT_LISTENTER_TYPE listener) { - this.listeners.add(listener); - } - - /** - * Fires the event to all subscribed event listeners. - * - * @param event - * An EVENTTYPEobject that represents the event being multi-casted. - */ - public synchronized void fireEvent(final EVENT_TYPE event) { - for (final StorageEvent listener : this.listeners) { - listener.eventOccurred(event); - } - } - - /** - * Returns a value that indicates whether any event listeners are registered for events. - * - * @return true if any event listeners are registered; otherwise, false. - */ - public synchronized boolean hasListeners() { - return this.listeners.size() > 0; - } - - /** - * Removes an event listener from the event chain. - * - * @param listener - * An EventListenerType object that represents the listener to remove. - */ - public synchronized void removeListener(final EVENT_LISTENTER_TYPE listener) { - this.listeners.remove(listener); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageException.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageException.java deleted file mode 100644 index f3a6a3ba8934e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageException.java +++ /dev/null @@ -1,265 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.SocketException; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageErrorResponse; - -/** - * Represents an exception for the Windows Azure storage service. - */ -public class StorageException extends Exception { - - /** - * Represents the serialization version number. - */ - private static final long serialVersionUID = 7972747254288274928L; - - /** - * Returns extended error information from the specified request and operation context. - * - * @param request - * An HttpURLConnection object that represents the request whose extended error information - * is being retrieved. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link StorageExtendedErrorInformation} object that represents the error details for the specified - * request. - */ - protected static StorageExtendedErrorInformation getErrorDetailsFromRequest(final HttpURLConnection request, - final OperationContext opContext) { - if (request == null) { - return null; - } - try { - final StorageErrorResponse response = new StorageErrorResponse(request.getErrorStream()); - return response.getExtendedErrorInformation(); - } - catch (final XMLStreamException e) { - return null; - } - } - - /** - * Translates the specified exception into a storage exception. - * - * @param request - * An HttpURLConnection object that represents the request whose exception is being - * translated. - * @param cause - * An Exception object that represents the exception to translate. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A StorageException object that represents translated exception. - */ - public static StorageException translateException(final HttpURLConnection request, final Exception cause, - final OperationContext opContext) { - if (request == null) { - return new StorageException("Client error", - "A Client side exception occurred, please check the inner exception for details", - Constants.HeaderConstants.HTTP_UNUSED_306, null, cause); - } - - final StorageExtendedErrorInformation extendedError = getErrorDetailsFromRequest(request, opContext); - StorageException translatedException = null; - - String responseMessage = Constants.EMPTY_STRING; - int responseCode = 0; - try { - responseCode = request.getResponseCode(); - - // When the exception is expected(IfNotExists) or we have already parsed the exception, we pass null as - // the cause. In such cases, we should just try to get the message from the request. - if (cause == null || cause instanceof SocketException) { - responseMessage = request.getResponseMessage(); - } - else if (cause != null) { - responseMessage = cause.getMessage(); - } - } - catch (final IOException e) { - // ignore errors - } - - if (responseMessage == null) { - responseMessage = Constants.EMPTY_STRING; - } - - // 1. If extended information is available use it - if (extendedError != null) { - translatedException = new StorageException(extendedError.getErrorCode(), responseMessage, responseCode, - extendedError, cause); - - if (translatedException != null) { - return translatedException; - } - } - - // 2. If extended information is unavailable, translate exception based - // on status code - translatedException = translateFromHttpStatus(responseCode, responseMessage, null, cause); - - if (translatedException != null) { - return translatedException; - } - - return new StorageException(StorageErrorCode.SERVICE_INTERNAL_ERROR.toString(), - "The server encountered an unknown failure: ".concat(responseMessage), - HttpURLConnection.HTTP_INTERNAL_ERROR, null, cause); - } - - /** - * Translates the specified HTTP status code into a storage exception. - * - * @param statusCode - * The HTTP status code returned by the operation. - * @param statusDescription - * A String that represents the status description. - * @param details - * A {@link StorageExtendedErrorInformation} object that represents the errror details returned by the - * operation. - * @param inner - * An Exception object that represents a reference to the initial exception, if one exists. - * - * @return A StorageException object that represents translated exception. - **/ - protected static StorageException translateFromHttpStatus(final int statusCode, final String statusDescription, - final StorageExtendedErrorInformation details, final Exception inner) { - switch (statusCode) { - case HttpURLConnection.HTTP_FORBIDDEN: - return new StorageException(StorageErrorCode.ACCESS_DENIED.toString(), statusDescription, statusCode, - details, inner); - - case HttpURLConnection.HTTP_GONE: - case HttpURLConnection.HTTP_NOT_FOUND: - return new StorageException(StorageErrorCode.RESOURCE_NOT_FOUND.toString(), statusDescription, - statusCode, details, inner); - - case HttpURLConnection.HTTP_BAD_REQUEST: - return new StorageException(StorageErrorCode.BAD_REQUEST.toString(), statusDescription, statusCode, - details, inner); - - case HttpURLConnection.HTTP_PRECON_FAILED: - case HttpURLConnection.HTTP_NOT_MODIFIED: - return new StorageException(StorageErrorCode.CONDITION_FAILED.toString(), statusDescription, - statusCode, details, inner); - - case HttpURLConnection.HTTP_CONFLICT: - return new StorageException(StorageErrorCode.RESOURCE_ALREADY_EXISTS.toString(), statusDescription, - statusCode, details, inner); - - case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: - return new StorageException(StorageErrorCode.SERVICE_TIMEOUT.toString(), statusDescription, statusCode, - details, inner); - - case 416: - // RequestedRangeNotSatisfiable - No corresponding enum in HttpURLConnection - return new StorageException(StorageErrorCode.BAD_REQUEST.toString(), statusDescription, statusCode, - details, inner); - - case HttpURLConnection.HTTP_INTERNAL_ERROR: - return new StorageException(StorageErrorCode.SERVICE_INTERNAL_ERROR.toString(), statusDescription, - statusCode, details, inner); - - case HttpURLConnection.HTTP_NOT_IMPLEMENTED: - return new StorageException(StorageErrorCode.NOT_IMPLEMENTED.toString(), statusDescription, statusCode, - details, inner); - - case HttpURLConnection.HTTP_BAD_GATEWAY: - return new StorageException(StorageErrorCode.BAD_GATEWAY.toString(), statusDescription, statusCode, - details, inner); - - case HttpURLConnection.HTTP_VERSION: - return new StorageException(StorageErrorCode.HTTP_VERSION_NOT_SUPPORTED.toString(), statusDescription, - statusCode, details, inner); - default: - return null; - } - } - - /** - * Represents the error code returned by the operation. - */ - protected String errorCode; - - /** - * Represents the extended error information returned by the operation. - * - * @see StorageExtendedErrorInformation - */ - protected StorageExtendedErrorInformation extendedErrorInformation; - - /** - * Represents the HTTP status code returned by the operation. - */ - private final int httpStatusCode; - - /** - * Creates an instance of the StorageException class using the specified parameters. - * - * @param errorCode - * A String that represents the error code returned by the operation. - * @param message - * A String that represents the error message returned by the operation. - * @param statusCode - * The HTTP status code returned by the operation. - * @param extendedErrorInfo - * A {@link StorageExtendedErrorInformation} object that represents the extended error information - * returned by the operation. - * @param innerException - * An Exception object that represents a reference to the initial exception, if one exists. - * - * @see StorageExtendedErrorInformation - */ - public StorageException(final String errorCode, final String message, final int statusCode, - final StorageExtendedErrorInformation extendedErrorInfo, final Exception innerException) { - super(message, innerException); - this.errorCode = errorCode; - this.httpStatusCode = statusCode; - this.extendedErrorInformation = extendedErrorInfo; - } - - /** - * @return the errorCode - */ - public String getErrorCode() { - return this.errorCode; - } - - /** - * @return the extendedErrorInformation - */ - public StorageExtendedErrorInformation getExtendedErrorInformation() { - return this.extendedErrorInformation; - } - - /** - * @return the httpStatusCode - */ - public int getHttpStatusCode() { - return this.httpStatusCode; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageExtendedErrorInformation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageExtendedErrorInformation.java deleted file mode 100644 index b70ced8c48a1e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageExtendedErrorInformation.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.io.Serializable; -import java.util.HashMap; - -/** - * Represents extended error information returned by the Windows Azure storage service. - */ -public final class StorageExtendedErrorInformation implements Serializable { - /** - * The serialization version number. - */ - private static final long serialVersionUID = 1527013626991334677L; - - /** - * Represents additional error details, as a java.util.HashMap object. - */ - private HashMap additionalDetails; - - /** - * Represents the storage service error code. - */ - private String errorCode; - - /** - * Represents the storage service error message. - */ - private String errorMessage; - - /** - * Creates an instance of the StorageExtendedErrorInformation class. - */ - public StorageExtendedErrorInformation() { - this.setAdditionalDetails(new HashMap()); - } - - /** - * @return the additionalDetails - */ - public HashMap getAdditionalDetails() { - return this.additionalDetails; - } - - /** - * @return the errorCode - */ - public String getErrorCode() { - return this.errorCode; - } - - /** - * @return the errorMessage - */ - public String getErrorMessage() { - return this.errorMessage; - } - - /** - * @param additionalDetails - * the additionalDetails to set - */ - protected void setAdditionalDetails(final HashMap additionalDetails) { - this.additionalDetails = additionalDetails; - } - - /** - * @param errorCode - * the errorCode to set - */ - public void setErrorCode(final String errorCode) { - this.errorCode = errorCode; - } - - /** - * @param errorMessage - * the errorMessage to set - */ - public void setErrorMessage(final String errorMessage) { - this.errorMessage = errorMessage; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageKey.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageKey.java deleted file mode 100644 index e2c2663069ebe..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/StorageKey.java +++ /dev/null @@ -1,213 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.microsoft.windowsazure.services.core.storage.utils.Base64; - -/** - * Represents a container for a storage key. - */ -public final class StorageKey { - /** - * Computes a signature for the specified string using the HMAC-SHA256 algorithm. - * - * @param storageKey - * A StorageKey object that represents the storage key to use. - * @param stringToSign - * The UTF-8-encoded string to sign. - * - * @return A String that contains the HMAC-SHA256-encoded signature. - * - * @throws IllegalArgumentException - * If the string to sign is not a valid Base64-encoded string. - * @throws InvalidKeyException - * If the key is not a valid storage key. - */ - public static synchronized String computeMacSha256(final StorageKey storageKey, final String stringToSign) - throws InvalidKeyException { - if (storageKey.hmacSha256 == null) { - storageKey.initHmacSha256(); - } - - byte[] utf8Bytes = null; - try { - utf8Bytes = stringToSign.getBytes("UTF8"); - } - catch (final UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } - - return Base64.encode(storageKey.hmacSha256.doFinal(utf8Bytes)); - } - - /** - * Computes a signature for the specified string using the HMAC-SHA512 algorithm. - * - * @param storageKey - * A StorageKey object that represents the storage key to use. - * @param stringToSign - * The UTF-8-encoded string to sign. - * - * @return A String that contains the HMAC-SHA512-encoded signature. - * - * @throws IllegalArgumentException - * If the string to sign is not a valid Base64-encoded string. - * @throws InvalidKeyException - * If the key is not a valid storage key. - */ - public static synchronized String computeMacSha512(final StorageKey storageKey, final String stringToSign) - throws InvalidKeyException { - if (storageKey.hmacSha512 == null) { - storageKey.initHmacSha512(); - } - - byte[] utf8Bytes = null; - try { - utf8Bytes = stringToSign.getBytes("UTF8"); - } - catch (final UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } - - return Base64.encode(storageKey.hmacSha512.doFinal(utf8Bytes)); - } - - /** - * Stores a reference to the hmacsha256 Mac. - */ - private Mac hmacSha256; - - /** - * Stores a reference to the hmacsha512 Mac. - */ - private Mac hmacSha512; - - /** - * Stores a reference to the hmacsha256 SecretKey. - */ - private SecretKey key256; - - /** - * Stores a reference to the hmacsha512 SecretKey. - */ - private SecretKey key512; - - /** - * Stores the key. - */ - private byte[] key; - - /** - * Creates an instance of the StorageKey class. - * - * @param key - * An array of bytes that represent the storage key. - */ - public StorageKey(final byte[] key) { - this.setKey(key); - } - - /** - * Returns the Base64-encoded key. - * - * @return A String that represents the Base64-encoded key. - */ - public String getBase64EncodedKey() { - return Base64.encode(this.key); - } - - /** - * Returns the key. - * - * @return A byte array that represents the key. - */ - public byte[] getKey() { - final byte[] copy = this.key.clone(); - return copy; - } - - /** - * Initializes the hmacsha256 Mac and SecretKey. - * - * @throws InvalidKeyException - * if the key is not a valid SecretKey according to spec. - */ - private void initHmacSha256() throws InvalidKeyException { - this.key256 = new SecretKeySpec(this.key, "HmacSHA256"); - try { - this.hmacSha256 = Mac.getInstance("HmacSHA256"); - } - catch (final NoSuchAlgorithmException e) { - throw new IllegalArgumentException(); - } - this.hmacSha256.init(this.key256); - } - - /** - * Initializes the hmacsha512 Mac and SecretKey. - * - * @throws InvalidKeyException - * if the key is not a valid SecretKey according to spec. - */ - private void initHmacSha512() throws InvalidKeyException { - this.key512 = new SecretKeySpec(this.key, "HmacSHA512"); - try { - this.hmacSha512 = Mac.getInstance("HmacSHA512"); - } - catch (final NoSuchAlgorithmException e) { - throw new IllegalArgumentException(); - } - this.hmacSha512.init(this.key512); - } - - /** - * Sets the key to be used, using the specified byte array as the key. - *

- * This method is provided to support key rotation. This method is not thread-safe. - * - * @param key - * A byte array that represents the key being assigned. - */ - public void setKey(final byte[] key) { - this.key = key; - this.hmacSha256 = null; - this.hmacSha512 = null; - this.key256 = null; - this.key512 = null; - } - - /** - * Sets the key to be used, using the specified String as the key. - *

- * This method is provided to support key rotation. This method is not thread-safe. - * - * @param key - * A String that represents the key being assigned. - * @throws IOException - * If the specified key is not a valid Base64-encoded string. - */ - public void setKey(final String key) throws IOException { - this.key = Base64.decode(key); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/package.html deleted file mode 100644 index b1450b0ca78a2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the blob service core class and interface, - - diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/PathUtility.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/PathUtility.java deleted file mode 100644 index b43d3144223c8..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/PathUtility.java +++ /dev/null @@ -1,478 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map.Entry; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageCredentials; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * RESERVED FOR INTERNAL USE. A class to help modify paths - */ -public final class PathUtility { - /** - * Adds a queryString to an URI. - * - * @param resourceURI - * the URI of the resource - * @param fieldCollection - * the key/ values collection to append. - * @return an appended URI. - * @throws URISyntaxException - * if the resulting URI is invalid. - * @throws StorageException - */ - public static URI addToQuery(final URI resourceURI, final HashMap fieldCollection) - throws URISyntaxException, StorageException { - final UriQueryBuilder outUri = new UriQueryBuilder(); - - // Generate new queryString - for (final Entry entry : fieldCollection.entrySet()) { - for (final String val : entry.getValue()) { - outUri.add(entry.getKey(), val); - } - } - - return outUri.addToURI(resourceURI); - } - - /** - * Adds a queryString to an URI. - * - * @param resourceURI - * the URI of the resource - * @param queryString - * the query string to add - * @return an appended URI. - * @throws URISyntaxException - * if the resulting URI is invalid. - * @throws StorageException - */ - public static URI addToQuery(final URI resourceURI, final String queryString) throws URISyntaxException, - StorageException { - return addToQuery(resourceURI, parseQueryString(queryString)); - } - - /** - * Appends a path to a Uri correctly using "/" as separator. - * - * @param uri - * The base Uri. - * @param relativeOrAbslouteUri - * The relative or absloute URI. - * @return The appended Uri. - * @throws URISyntaxException - */ - public static URI appendPathToUri(final URI uri, final String relativeOrAbslouteUri) throws URISyntaxException { - return appendPathToUri(uri, relativeOrAbslouteUri, "/"); - } - - /** - * Appends a path to a Uri correctly using the given separator. - * - * @param uri - * The base Uri. - * @param relativeOrAbsoluteUri - * The relative or absloute URI. - * @param separator - * the separator to use. - * @return The appended Uri. - * @throws URISyntaxException - */ - public static URI appendPathToUri(final URI uri, final String relativeOrAbsoluteUri, final String separator) - throws URISyntaxException { - - int hostNameBeginIndex = -1; - if (relativeOrAbsoluteUri.length() > 8) { - final String header = relativeOrAbsoluteUri.substring(0, 8).toLowerCase(); - if ("https://".equals(header)) { - hostNameBeginIndex = 8; - } - else if ("http://".equals(header.substring(0, 7))) { - hostNameBeginIndex = 7; - } - } - - // absolute URI - if (hostNameBeginIndex > 0) { - final int authorityLength = relativeOrAbsoluteUri.substring(hostNameBeginIndex).indexOf(separator); - final String authorityName = relativeOrAbsoluteUri.substring(hostNameBeginIndex, hostNameBeginIndex - + authorityLength); - final URI absoluteUri = new URI(relativeOrAbsoluteUri); - - if (uri.getAuthority().equals(authorityName)) { - return absoluteUri; - } - else { - // Happens when using fiddler, DNS aliases, or potentially NATs - return new URI(uri.getScheme(), uri.getAuthority(), absoluteUri.getPath(), absoluteUri.getRawQuery(), - absoluteUri.getRawFragment()); - } - } - else { - // relative URI - // used by directory - if (uri.getPath().length() == 0 && relativeOrAbsoluteUri.startsWith(separator)) { - return new URI(uri.getScheme(), uri.getAuthority(), relativeOrAbsoluteUri, uri.getRawQuery(), - uri.getRawFragment()); - } - - final StringBuilder pathString = new StringBuilder(uri.getPath()); - - if (uri.getPath().endsWith(separator)) { - pathString.append(relativeOrAbsoluteUri); - } - else { - pathString.append(separator); - pathString.append(relativeOrAbsoluteUri); - } - - return new URI(uri.getScheme(), uri.getAuthority(), pathString.toString(), uri.getQuery(), - uri.getFragment()); - } - } - - /** - * Gets the blob name from the URI. - * - * @param inURI - * the resource address - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return the blobs name - * @throws URISyntaxException - */ - public static String getBlobNameFromURI(final URI inURI, final boolean usePathStyleUris) throws URISyntaxException { - return Utility.safeRelativize(new URI(getContainerURI(inURI, usePathStyleUris).toString().concat("/")), inURI); - } - - /** - * Gets the canonical path for an object from the credentials. - * - * @param credentials - * the credentials to use. - * @param absolutePath - * the Absolute path of the object. - * @return the canonical path for an object from the credentials - */ - public static String getCanonicalPathFromCredentials(final StorageCredentials credentials, final String absolutePath) { - final String account = credentials.getAccountName(); - - if (account == null) { - final String errorMessage = "Cannot create Shared Access Signature as the credentials does not have account name information. Please check that the credentials used support creating Shared Access Signature."; - throw new IllegalArgumentException(errorMessage); - } - final StringBuilder builder = new StringBuilder("/"); - builder.append(account); - builder.append(absolutePath); - return builder.toString(); - } - - /** - * Get the container name from address from the URI. - * - * @param resourceAddress - * The container Uri. - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return container name from address from the URI. - * @throws IllegalArgumentException - */ - public static String getContainerNameFromUri(final URI resourceAddress, final boolean usePathStyleUris) { - return getResourceNameFromUri(resourceAddress, usePathStyleUris, - String.format("Invalid blob address '%s', missing container information", resourceAddress)); - } - - /** - * Get the table name from address from the URI. - * - * @param resourceAddress - * The table Uri. - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return table name from address from the URI. - * @throws IllegalArgumentException - */ - public static String getTableNameFromUri(final URI resourceAddress, final boolean usePathStyleUris) { - return getResourceNameFromUri(resourceAddress, usePathStyleUris, - String.format("Invalid table address '%s', missing table information", resourceAddress)); - } - - /** - * Get the container, queue or table name from address from the URI. - * - * @param resourceAddress - * The queue Uri. - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return container name from address from the URI. - * @throws IllegalArgumentException - */ - private static String getResourceNameFromUri(final URI resourceAddress, final boolean usePathStyleUris, - final String error) { - Utility.assertNotNull("resourceAddress", resourceAddress); - - final String[] pathSegments = resourceAddress.getRawPath().split("/"); - - final int expectedPartsLength = usePathStyleUris ? 3 : 2; - - if (pathSegments.length < expectedPartsLength) { - throw new IllegalArgumentException(error); - } - - final String resourceName = usePathStyleUris ? pathSegments[2] : pathSegments[1]; - - return Utility.trimEnd(resourceName, '/'); - } - - /** - * Gets the container URI from a blob address - * - * @param blobAddress - * the blob address - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return the container URI from a blob address - * @throws URISyntaxException - */ - public static URI getContainerURI(final URI blobAddress, final boolean usePathStyleUris) throws URISyntaxException { - final String containerName = getContainerNameFromUri(blobAddress, usePathStyleUris); - - final URI containerUri = appendPathToUri(new URI(getServiceClientBaseAddress(blobAddress, usePathStyleUris)), - containerName); - return containerUri; - } - - /** - * Retrieves the parent address for a blob Uri. - * - * @param blobAddress - * The blob address - * @param delimiter - * The delimiter. - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return The address of the parent. - * @throws URISyntaxException - * @throws StorageException - */ - public static URI getParentAddress(final URI blobAddress, final String delimiter, final boolean usePathStyleUris) - throws URISyntaxException, StorageException { - final String parentName = getParentNameFromURI(blobAddress, delimiter, usePathStyleUris); - - final URI parentUri = appendPathToUri(new URI(getServiceClientBaseAddress(blobAddress, usePathStyleUris)), - parentName); - return parentUri; - } - - /** - * Retrieves the parent name for a blob Uri. - * - * @param resourceAddress - * The resource Uri. - * @param delimiter - * the directory delimiter to use - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return the parent address for a blob Uri. - * @throws URISyntaxException - * @throws StorageException - */ - public static String getParentNameFromURI(final URI resourceAddress, final String delimiter, - final boolean usePathStyleUris) throws URISyntaxException, StorageException { - Utility.assertNotNull("resourceAddress", resourceAddress); - Utility.assertNotNullOrEmpty("delimiter", delimiter); - - final String containerName = getContainerNameFromUri(resourceAddress, usePathStyleUris); - - /* - * URI baseURI = appendPathToUri( new URI(getServiceClientBaseAddress(resourceAddress, usePathStyleUris)), - * containerName); - */ - URI baseURI = new URI(getServiceClientBaseAddress(resourceAddress, usePathStyleUris)); - if (usePathStyleUris && !baseURI.getRawPath().endsWith("/")) { - baseURI = new URI(baseURI.getScheme(), baseURI.getRawAuthority(), baseURI.getRawPath().concat("/"), null, - null); - } - - final URI relativeURI = new URI(Utility.safeRelativize(baseURI, resourceAddress)); - - String relativeURIString = relativeURI.toString(); - - if (relativeURIString.endsWith(delimiter)) { - relativeURIString = relativeURIString.substring(0, relativeURIString.length() - delimiter.length()); - } - - String parentName = Constants.EMPTY_STRING; - - if (Utility.isNullOrEmpty(relativeURIString)) { - // Case 1 /[Delimiter]*? => / - // Parent of container is container itself - parentName = containerName.concat(delimiter); - } - else { - final int lastDelimiterDex = relativeURIString.lastIndexOf(delimiter); - - if (lastDelimiterDex <= 0) { - // Case 2 // - // Parent of a folder is container - parentName = containerName.concat(delimiter); - } - else { - // Case 3 ///[/]* - // Parent of blob is folder - parentName = relativeURIString.substring(0, lastDelimiterDex + delimiter.length()); - } - } - - return parentName; - } - - /** - * Get the queue name from address from the URI. - * - * @param resourceAddress - * The queue Uri. - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return container name from address from the URI. - * @throws IllegalArgumentException - */ - public static String getQueueNameFromUri(final URI resourceAddress, final boolean usePathStyleUris) { - return getResourceNameFromUri(resourceAddress, usePathStyleUris, - String.format("Invalid queue URI '%s'.", resourceAddress)); - } - - /** - * Get the service client address from a complete Uri. - * - * @param address - * Complete address of the resource. - * @param usePathStyleUris - * a value indicating if the address is a path style uri. - * @return the service client address from a complete Uri. - * @throws URISyntaxException - */ - public static String getServiceClientBaseAddress(final URI address, final boolean usePathStyleUris) - throws URISyntaxException { - if (usePathStyleUris) { - final String[] pathSegments = address.getRawPath().split("/"); - - if (pathSegments.length < 2) { - final String error = String - .format("Missing account name information inside path style uri. Path style uris should be of the form http:///"); - throw new IllegalArgumentException(error); - } - - final StringBuilder completeAddress = new StringBuilder(new URI(address.getScheme(), - address.getAuthority(), null, null, null).toString()); - completeAddress.append("/"); - completeAddress.append(Utility.trimEnd(pathSegments[1], '/')); - - return completeAddress.toString(); - } - else { - return new URI(address.getScheme(), address.getAuthority(), null, null, null).toString(); - } - } - - /** - * Parses a query string into a one to many hashmap. - * - * @param parseString - * the string to parse - * @return a HashMap of the key values. - * @throws StorageException - */ - public static HashMap parseQueryString(String parseString) throws StorageException { - final HashMap retVals = new HashMap(); - if (Utility.isNullOrEmpty(parseString)) { - return retVals; - } - - // 1. Remove ? if present - final int queryDex = parseString.indexOf("?"); - if (queryDex >= 0 && parseString.length() > 0) { - parseString = parseString.substring(queryDex + 1); - } - - // 2. split name value pairs by splitting on the 'c&' character - final String[] valuePairs = parseString.contains("&") ? parseString.split("&") : parseString.split(";"); - - // 3. for each field value pair parse into appropriate map entries - for (int m = 0; m < valuePairs.length; m++) { - final int equalDex = valuePairs[m].indexOf("="); - - if (equalDex < 0 || equalDex == valuePairs[m].length() - 1) { - continue; - } - - String key = valuePairs[m].substring(0, equalDex); - String value = valuePairs[m].substring(equalDex + 1); - - key = Utility.safeDecode(key); - value = Utility.safeDecode(value); - - // 3.1 add to map - String[] values = retVals.get(key); - - if (values == null) { - values = new String[] { value }; - if (!value.equals(Constants.EMPTY_STRING)) { - retVals.put(key, values); - } - } - else if (!value.equals(Constants.EMPTY_STRING)) { - final String[] newValues = new String[values.length + 1]; - for (int j = 0; j < values.length; j++) { - newValues[j] = values[j]; - } - - newValues[newValues.length] = value; - } - } - - return retVals; - } - - /** - * Strips the Query and Fragment from the uri. - * - * @param inUri - * the uri to alter - * @return the stripped uri. - * @throws StorageException - */ - public static URI stripURIQueryAndFragment(final URI inUri) throws StorageException { - try { - return new URI(inUri.getScheme(), inUri.getAuthority(), inUri.getPath(), null, null); - } - catch (final URISyntaxException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - /** - * Private Default Ctor. - */ - private PathUtility() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/StreamMd5AndLength.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/StreamMd5AndLength.java deleted file mode 100644 index aac9c08199480..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/StreamMd5AndLength.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils; - -import java.security.MessageDigest; - -/** - * RESERVED FOR INTERNAL USE. Represents a stream descriptor that contains the stream size and MD5 hash. - */ -public final class StreamMd5AndLength { - /** - * Contains the MD5 hash for the stream data. - */ - private String streamMd5; - - /** - * Contains the length, in bytes, for the stream. - */ - private long streamLength; - - private MessageDigest intermediateMD5; - - public void setDigest(MessageDigest digest) { - this.intermediateMD5 = digest; - } - - /** - * @return the length - */ - public long getLength() { - return this.streamLength; - } - - /** - * @return the md5 - */ - public String getMd5() { - if (this.streamMd5 == null && this.intermediateMD5 != null) { - this.streamMd5 = Base64.encode(this.intermediateMD5.digest()); - } - - return this.streamMd5; - } - - /** - * @param length - * the length to set - */ - public void setLength(final long length) { - this.streamLength = length; - } - - /** - * @param md5 - * the md5 to set - */ - public void setMd5(final String md5) { - this.streamMd5 = md5; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/UriQueryBuilder.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/UriQueryBuilder.java deleted file mode 100644 index 43b1865b1580d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/UriQueryBuilder.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map.Entry; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * RESERVED FOR INTERNAL USE. A helper class to help modify the query string of a URI - */ -public final class UriQueryBuilder { - /** - * Stores the one to one key/ value collection of query parameters. - */ - private final HashMap> parameters = new HashMap>(); - - /** - * Adds a value to the URI with escaping. - * - * @param name - * the query key name. - * @param value - * the query value. - * @throws StorageException - */ - public void add(final String name, final String value) throws StorageException { - if (Utility.isNullOrEmpty(name)) { - throw new IllegalArgumentException("Cannot encode a query parameter with a null or empty key"); - } - - this.insertKeyValue(name, value); - } - - /** - * Add query parameter to an existing Uri. This takes care of any existing query parameters in the Uri. - * - * @param uri - * the original uri. - * @return the appended uri - * @throws URISyntaxException - * if the resulting uri is invalid. - * @throws StorageException - */ - public URI addToURI(final URI uri) throws URISyntaxException, StorageException { - final String origRawQuery = uri.getRawQuery(); - final String rawFragment = uri.getRawFragment(); - final String uriString = uri.resolve(uri).toASCIIString(); - - final HashMap origQueryMap = PathUtility.parseQueryString(origRawQuery); - - // Try/Insert original queries to map - - for (final Entry entry : origQueryMap.entrySet()) { - for (final String val : entry.getValue()) { - this.insertKeyValue(entry.getKey(), val); - } - } - - final StringBuilder retBuilder = new StringBuilder(); - - // has a fragment - if (Utility.isNullOrEmpty(origRawQuery) && !Utility.isNullOrEmpty(rawFragment)) { - final int bangDex = uriString.indexOf('#'); - retBuilder.append(uriString.substring(0, bangDex)); - } - else if (!Utility.isNullOrEmpty(origRawQuery)) { - // has a query - final int queryDex = uriString.indexOf('?'); - retBuilder.append(uriString.substring(0, queryDex)); - } - else { - // no fragment or query - retBuilder.append(uriString); - if (uri.getRawPath().length() <= 0) { - retBuilder.append("/"); - } - } - - final String finalQuery = this.toString(); - - if (finalQuery.length() > 0) { - retBuilder.append("?"); - retBuilder.append(finalQuery); - } - - if (!Utility.isNullOrEmpty(rawFragment)) { - retBuilder.append("#"); - retBuilder.append(rawFragment); - } - - return new URI(retBuilder.toString()); - } - - /** - * Inserts a key / value in the Hashmap, assumes the value is already utf-8 encoded. - * - * @param key - * the key to insert - * @param value - * the value to insert - * @throws StorageException - */ - private void insertKeyValue(String key, String value) throws StorageException { - if (value != null) { - value = Utility.safeEncode(value); - } - if (!key.startsWith("$")) { - key = Utility.safeEncode(key); - } - - ArrayList list = this.parameters.get(key); - if (list == null) { - list = new ArrayList(); - list.add(value); - this.parameters.put(key, list); - } - else { - if (!list.contains(value)) { - list.add(value); - } - } - } - - /** - * Returns a string that represents this instance. This will construct the full URI. - * - * @return a string that represents this instance. - */ - @Override - public String toString() { - final StringBuilder outString = new StringBuilder(); - Boolean isFirstPair = true; - - for (final String key : this.parameters.keySet()) { - if (this.parameters.get(key) != null) { - for (final String val : this.parameters.get(key)) { - if (isFirstPair) { - isFirstPair = false; - } - else { - outString.append("&"); - } - - outString.append(String.format("%s=%s", key, val)); - } - } - } - - return outString.toString(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/Utility.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/Utility.java deleted file mode 100644 index 54e66cd05b83c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/Utility.java +++ /dev/null @@ -1,1113 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Constructor; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.TimeZone; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.RequestResult; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.ResultContinuationType; -import com.microsoft.windowsazure.services.core.storage.StorageCredentials; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsAccountAndKey; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsAnonymous; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCode; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.StorageExtendedErrorInformation; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageErrorResponse; - -/** - * RESERVED FOR INTERNAL USE. A class which provides utility methods. - */ -public final class Utility { - /** - * Stores a reference to the GMT time zone. - */ - public static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT"); - - /** - * Stores a reference to the UTC time zone. - */ - public static final TimeZone UTC_ZONE = TimeZone.getTimeZone("UTC"); - - /** - * Stores a reference to the US locale. - */ - public static final Locale LOCALE_US = Locale.US; - - /** - * Stores a reference to the RFC1123 date/time pattern. - */ - private static final String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z"; - - /** - * Stores a reference to the ISO8061 date/time pattern. - */ - public static final String ISO8061_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; - - /** - * Stores a reference to the ISO8061 date/time pattern. - */ - public static final String ISO8061_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - - /** - * Stores a reference to the ISO8061_LONG date/time pattern. - */ - public static final String ISO8061_LONG_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"; - - /** - * - * Determines the size of an input stream, and optionally calculates the MD5 hash for the stream. - * - * @param sourceStream - * A InputStream object that represents the stream to measure. - * @param writeLength - * The number of bytes to read from the stream. - * @param abandonLength - * The number of bytes to read before the analysis is abandoned. Set this value to -1 to - * force the entire stream to be read. This parameter is provided to support upload thresholds. - * @param rewindSourceStream - * true if the stream should be rewound after it is read; otherwise, false. - * @param calculateMD5 - * true if an MD5 hash will be calculated; otherwise, false. - * - * @return A {@link StreamMd5AndLength} object that contains the stream length, and optionally the MD5 hash. - * - * @throws IOException - * If an I/O error occurs. - * @throws StorageException - * If a storage service error occurred. - */ - public static StreamMd5AndLength analyzeStream(final InputStream sourceStream, long writeLength, - long abandonLength, final boolean rewindSourceStream, final boolean calculateMD5) throws IOException, - StorageException { - if (abandonLength < 0) { - abandonLength = Long.MAX_VALUE; - } - - if (rewindSourceStream) { - if (!sourceStream.markSupported()) { - throw new IllegalArgumentException("Input stream must be markable!"); - } - - sourceStream.mark(Constants.MAX_MARK_LENGTH); - } - - MessageDigest digest = null; - if (calculateMD5) { - try { - digest = MessageDigest.getInstance("MD5"); - } - catch (final NoSuchAlgorithmException e) { - // This wont happen, throw fatal. - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - if (writeLength < 0) { - writeLength = Long.MAX_VALUE; - } - - final StreamMd5AndLength retVal = new StreamMd5AndLength(); - int count = -1; - final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; - - int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength()); - count = sourceStream.read(retrievedBuff, 0, nextCopy); - - while (nextCopy > 0 && count != -1) { - if (calculateMD5) { - digest.update(retrievedBuff, 0, count); - } - retVal.setLength(retVal.getLength() + count); - - if (retVal.getLength() > abandonLength) { - // Abandon operation - retVal.setLength(-1); - retVal.setMd5(null); - break; - } - - nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength()); - count = sourceStream.read(retrievedBuff, 0, nextCopy); - } - - if (retVal.getLength() != -1 && calculateMD5) { - retVal.setMd5(Base64.encode(digest.digest())); - } - - if (retVal.getLength() != -1 && writeLength > 0) { - retVal.setLength(Math.min(retVal.getLength(), writeLength)); - } - - if (rewindSourceStream) { - sourceStream.reset(); - sourceStream.mark(Constants.MAX_MARK_LENGTH); - } - - return retVal; - } - - /** - * Returns a value that indicates whether the specified credentials are equal. - * - * @param thisCred - * An object derived from {@link StorageCredentials} that represents the first set of credentials being - * compared for equality. - * @param thatCred - * An object derived from StorageCredentials that represents the second set of credentials - * being compared for equality. - * - * @return true if the credentials are equal; otherwise, false. - */ - public static boolean areCredentialsEqual(final StorageCredentials thisCred, final StorageCredentials thatCred) { - if (thisCred == thatCred) { - return true; - } - - if (thatCred == null || thisCred.getClass() != thatCred.getClass()) { - return false; - } - - if (thisCred instanceof StorageCredentialsAccountAndKey) { - return ((StorageCredentialsAccountAndKey) thisCred).toString(true).equals( - ((StorageCredentialsAccountAndKey) thatCred).toString(true)); - } - else if (thisCred instanceof StorageCredentialsSharedAccessSignature) { - return ((StorageCredentialsSharedAccessSignature) thisCred).getToken().equals( - ((StorageCredentialsSharedAccessSignature) thatCred).getToken()); - } - else if (thisCred instanceof StorageCredentialsAnonymous) { - return true; - } - - return thisCred.equals(thatCred); - } - - /** - * Asserts a continuation token is of the specified type. - * - * @param continuationToken - * A {@link ResultContinuation} object that represents the continuation token whose type is being - * examined. - * @param continuationType - * A {@link ResultContinuationType} value that represents the continuation token type being asserted with - * the specified continuation token. - */ - public static void assertContinuationType(final ResultContinuation continuationToken, - final ResultContinuationType continuationType) { - if (continuationToken != null) { - if (!(continuationToken.getContinuationType() == ResultContinuationType.NONE || continuationToken - .getContinuationType() == continuationType)) { - final String errorMessage = String - .format(Utility.LOCALE_US, - "The continuation type passed in is unexpected. Please verify that the correct continuation type is passed in. Expected {%s}, found {%s}", - continuationToken.getContinuationType(), continuationType); - throw new IllegalArgumentException(errorMessage); - } - } - } - - /** - * Asserts that a value is not null. - * - * @param param - * A String that represents the name of the parameter, which becomes the exception message - * text if the value parameter is null. - * @param value - * An Object object that represents the value of the specified parameter. This is the value - * being asserted as not null. - */ - public static void assertNotNull(final String param, final Object value) { - if (value == null) { - throw new IllegalArgumentException(param); - } - } - - /** - * Asserts that the specified string is not null or empty. - * - * @param param - * A String that represents the name of the parameter, which becomes the exception message - * text if the value parameter is null or an empty string. - * @param value - * A String that represents the value of the specified parameter. This is the value being - * asserted as not null and not an empty string. - */ - public static void assertNotNullOrEmpty(final String param, final String value) { - assertNotNull(param, value); - - if (Utility.isNullOrEmpty(value)) { - throw new IllegalArgumentException("The argument must not be an empty string or null:".concat(param)); - } - } - - /** - * Asserts that the specified integer is in the valid range. - * - * @param param - * A String that represents the name of the parameter, which becomes the exception message - * text if the value parameter is out of bounds. - * @param value - * The value of the specified parameter. - * @param min - * The minimum value for the specified parameter. - * @param max - * The maximum value for the specified parameter. - */ - public static void assertInBounds(final String param, final int value, final int min, final int max) { - if (value < min || value > max) { - throw new IllegalArgumentException(String.format( - "The value of the parameter %s should be between %s and %s.", param, min, max)); - } - } - - /** - * Creates an XML stream reader from the specified input stream. - * - * @param streamRef - * An InputStream object that represents the input stream to use as the source. - * - * @return A java.xml.stream.XMLStreamReader object that represents the XML stream reader created from - * the specified input stream. - * - * @throws XMLStreamException - * If the XML stream reader could not be created. - */ - public static XMLStreamReader createXMLStreamReaderFromStream(final InputStream streamRef) - throws XMLStreamException { - // TODO optimization keep this static - XMLInputFactory xmlif = null; - - xmlif = XMLInputFactory.newInstance(); - xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); - xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); - // set the IS_COALESCING property to true , if application desires to - // get whole text data as one event. - xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); - - return xmlif.createXMLStreamReader(streamRef); - } - - /** - * Creates an XML stream reader from the specified input stream. - * - * @param reader - * An InputStreamReader object that represents the input reader to use as the source. - * - * @return A java.xml.stream.XMLStreamReader object that represents the XML stream reader created from - * the specified input stream. - * - * @throws XMLStreamException - * If the XML stream reader could not be created. - */ - public static XMLStreamReader createXMLStreamReaderFromReader(final Reader reader) throws XMLStreamException { - // TODO optimization keep this static - XMLInputFactory xmlif = null; - - xmlif = XMLInputFactory.newInstance(); - xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); - xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); - // set the IS_COALESCING property to true , if application desires to - // get whole text data as one event. - xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); - - return xmlif.createXMLStreamReader(reader); - } - - /** - * Returns a value that indicates whether a specified URI is a path-style URI. - * - * @param baseURI - * A java.net.URI value that represents the URI being checked. - * @param knownAccountName - * A String that represents the known account name to examine with baseURI, or - * null to examine baseURI on its own for being a path-style URI. - * - * @return true if the specified URI is path-style; otherwise, false. - */ - public static boolean determinePathStyleFromUri(final URI baseURI, final String knownAccountName) { - String path = baseURI.getPath(); - - if (knownAccountName == null) { - if (Utility.isNullOrEmpty(path) || path.equals("/")) { - return false; - } - - return true; - } - - if (!Utility.isNullOrEmpty(path) && path.startsWith("/")) { - path = path.substring(1); - } - - if (Utility.isNullOrEmpty(path) || baseURI.getHost().startsWith(knownAccountName)) { - return false; - } - else if (!Utility.isNullOrEmpty(path) && path.startsWith(knownAccountName)) { - return true; - } - - return false; - } - - /** - * Returns an unexpected storage exception. - * - * @param cause - * An Exception object that represents the initial exception that caused the unexpected - * error. - * - * @return A {@link StorageException} object that represents the unexpected storage exception being thrown. - */ - public static StorageException generateNewUnexpectedStorageException(final Exception cause) { - final StorageException exceptionRef = new StorageException(StorageErrorCode.NONE.toString(), - "Unexpected internal storage client error.", 306, // unused - null, null); - exceptionRef.initCause(cause); - return exceptionRef; - } - - /** - * Returns a byte array that represents the data of a long value. - * - * @param value - * The value from which the byte array will be returned. - * - * @return A byte array that represents the data of the specified long value. - */ - public static byte[] getBytesFromLong(final long value) { - final byte[] tempArray = new byte[8]; - - for (int m = 0; m < 8; m++) { - tempArray[7 - m] = (byte) ((value >> (8 * m)) & 0xFF); - } - - return tempArray; - } - - /** - * Returns extended error information from the specified request. - * - * @param request - * An HttpURLConnection object that represents the request. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link StorageExtendedErrorInformation} object that represents the extended error information from the - * request. - */ - protected static StorageExtendedErrorInformation getErrorDetailsFromRequest(final HttpURLConnection request, - final OperationContext opContext) { - if (request == null) { - return null; - } - try { - final StorageErrorResponse response = new StorageErrorResponse(request.getErrorStream()); - return response.getExtendedErrorInformation(); - } - catch (final XMLStreamException e) { - return null; - } - } - - /** - * Returns the current GMT date/time using the RFC1123 pattern. - * - * @return A String that represents the current GMT date/time using the RFC1123 pattern. - */ - public static String getGMTTime() { - final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US); - rfc1123Format.setTimeZone(GMT_ZONE); - return rfc1123Format.format(new Date()); - } - - public static String getTimeByZoneAndFormat(Date date, TimeZone zone, String format) { - final DateFormat formatter = new SimpleDateFormat(format, LOCALE_US); - formatter.setTimeZone(zone); - return formatter.format(date); - } - - /** - * Returns the GTM date/time for the specified value using the RFC1123 pattern. - * - * @param inDate - * A Date object that represents the date to convert to GMT date/time in the RFC1123 - * pattern. - * - * @return A String that represents the GMT date/time for the specified value using the RFC1123 - * pattern. - */ - public static String getGMTTime(final Date inDate) { - final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US); - rfc1123Format.setTimeZone(GMT_ZONE); - return rfc1123Format.format(inDate); - } - - /** - * Returns the standard header value from the specified connection request, or an empty string if no header value - * has been specified for the request. - * - * @param conn - * An HttpURLConnection object that represents the request. - * @param headerName - * A String that represents the name of the header being requested. - * - * @return A String that represents the header value, or null if there is no corresponding - * header value for headerName. - */ - public static String getStandardHeaderValue(final HttpURLConnection conn, final String headerName) { - final String headerValue = conn.getRequestProperty(headerName); - - // Coalesce null value - return headerValue == null ? Constants.EMPTY_STRING : headerValue; - } - - /** - * Returns the current UTC date/time using the RFC1123 pattern. - * - * @return A String that represents the current UTC date/time using the RFC1123 pattern. - */ - protected static String getUTCTime() { - final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US); - rfc1123Format.setTimeZone(UTC_ZONE); - return rfc1123Format.format(new Date()); - } - - /** - * Returns the UTC date/time for the specified value using the RFC1123 pattern. - * - * @param inDate - * A Date object that represents the date to convert to UTC date/time in the RFC1123 - * pattern. - * - * @return A String that represents the UTC date/time for the specified value using the RFC1123 - * pattern. - */ - protected static String getUTCTime(final Date inDate) { - final DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US); - rfc1123Format.setTimeZone(UTC_ZONE); - return rfc1123Format.format(inDate); - } - - /** - * Returns the UTC date/time for the specified value using the ISO8061 pattern. - * - * @param value - * A Date object that represents the date to convert to UTC date/time in the ISO8061 - * pattern. If this value is null, this method returns an empty string. - * - * @return A String that represents the UTC date/time for the specified value using the ISO8061 - * pattern, or an empty string if value is null. - */ - public static String getUTCTimeOrEmpty(final Date value) { - if (value == null) { - return Constants.EMPTY_STRING; - } - - final DateFormat iso8061Format = new SimpleDateFormat(ISO8061_PATTERN, LOCALE_US); - iso8061Format.setTimeZone(UTC_ZONE); - - return iso8061Format.format(value); - } - - /** - * Creates an instance of the IOException class using the specified exception. - * - * @param ex - * An Exception object that represents the exception used to create the IO exception. - * - * @return A java.io.IOException object that represents the created IO exception. - */ - public static IOException initIOException(final Exception ex) { - final IOException retEx = new IOException(); - retEx.initCause(ex); - return retEx; - } - - /** - * Returns a value that indicates whether the specified string is null or empty. - * - * @param value - * A String being examined for null or empty. - * - * @return true if the specified value is null or empty; otherwise, false - */ - public static boolean isNullOrEmpty(final String value) { - return value == null || value.length() == 0; - } - - /** - * Parses a connection string and returns its values as a hash map of key/value pairs. - * - * @param parseString - * A String that represents the connection string to parse. - * - * @return A java.util.HashMap object that represents the hash map of the key / value pairs parsed from - * the connection string. - */ - public static HashMap parseAccountString(final String parseString) { - - // 1. split name value pairs by splitting on the ';' character - final String[] valuePairs = parseString.split(";"); - final HashMap retVals = new HashMap(); - - // 2. for each field value pair parse into appropriate map entries - for (int m = 0; m < valuePairs.length; m++) { - final int equalDex = valuePairs[m].indexOf("="); - if (equalDex < 1) { - throw new IllegalArgumentException("Invalid Connection String"); - } - - final String key = valuePairs[m].substring(0, equalDex); - final String value = valuePairs[m].substring(equalDex + 1); - - // 2.1 add to map - retVals.put(key, value); - } - - return retVals; - } - - /** - * Returns a GMT date in the specified format - * - * @param value - * the string to parse - * @return the GMT date, as a Date - * @throws ParseException - * If the specified string is invalid - */ - public static Date parseDateFromString(final String value, final String pattern, final TimeZone timeZone) - throws ParseException { - final DateFormat rfc1123Format = new SimpleDateFormat(pattern, Utility.LOCALE_US); - rfc1123Format.setTimeZone(timeZone); - return rfc1123Format.parse(value); - } - - /** - * Returns a date in the ISO8061 long pattern for the specified string. - * - * @param value - * A String that represents the string to parse. - * - * @return A Date object that represents the date in the ISO8061 long pattern. - * - * @throws ParseException - * If the specified string is invalid. - */ - public static Date parseISO8061LongDateFromString(final String value) throws ParseException { - return parseDateFromString(value, ISO8061_LONG_PATTERN, Utility.UTC_ZONE); - } - - /** - * Returns a GMT date in the RFC1123 pattern for the specified string. - * - * @param value - * A String that represents the string to parse. - * - * @return A Date object that represents the GMT date in the RFC1123 pattern. - * - * @throws ParseException - * If the specified string is invalid. - */ - public static Date parseRFC1123DateFromStringInGMT(final String value) throws ParseException { - return parseDateFromString(value, RFC1123_PATTERN, Utility.GMT_ZONE); - } - - /** - * Reads character data for the specified XML element from an XML stream reader. This method will read start events, - * characters, and end events from a stream. - * - * @param xmlr - * An XMLStreamReader object that represents the source XML stream reader. - * - * @param elementName - * A String that represents XML element name. - * - * @return A String that represents the character data for the specified element. - * - * @throws XMLStreamException - * If an XML stream failure occurs. - */ - public static String readElementFromXMLReader(final XMLStreamReader xmlr, final String elementName) - throws XMLStreamException { - return readElementFromXMLReader(xmlr, elementName, true); - } - - /** - * Reads character data for the specified XML element from an XML stream reader. This method will read start events, - * characters, and end events from a stream. - * - * @param xmlr - * An XMLStreamReader object that represents the source XML stream reader. - * - * @param elementName - * A String that represents XML element name. - * @param returnNullOnEmpty - * If true, returns null when a empty string is read, otherwise EmptyString ("") is returned. - * - * @return A String that represents the character data for the specified element. - * - * @throws XMLStreamException - * If an XML stream failure occurs. - */ - public static String readElementFromXMLReader(final XMLStreamReader xmlr, final String elementName, - boolean returnNullOnEmpty) throws XMLStreamException { - xmlr.require(XMLStreamConstants.START_ELEMENT, null, elementName); - int eventType = xmlr.next(); - final StringBuilder retVal = new StringBuilder(); - - if (eventType == XMLStreamConstants.CHARACTERS) { - // This do while is in case the XMLStreamReader does not have - // the IS_COALESCING property set - // to true which may result in text being read in multiple events - // If we ensure all xmlreaders have this property we can optimize - // the StringBuilder and while loop - // away - do { - retVal.append(xmlr.getText()); - eventType = xmlr.next(); - - } while (eventType == XMLStreamConstants.CHARACTERS); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, elementName); - if (retVal.length() == 0) { - return returnNullOnEmpty ? null : Constants.EMPTY_STRING; - } - else { - return retVal.toString(); - } - } - - /** - * Performs safe decoding of the specified string, taking care to preserve each + character, rather - * than replacing it with a space character. - * - * @param stringToDecode - * A String that represents the string to decode. - * - * @return A String that represents the decoded string. - * - * @throws StorageException - * If a storage service error occurred. - */ - public static String safeDecode(final String stringToDecode) throws StorageException { - if (stringToDecode == null) { - return null; - } - - if (stringToDecode.length() == 0) { - return Constants.EMPTY_STRING; - } - - try { - if (stringToDecode.contains("+")) { - final StringBuilder outBuilder = new StringBuilder(); - - int startDex = 0; - for (int m = 0; m < stringToDecode.length(); m++) { - if (stringToDecode.charAt(m) == '+') { - if (m > startDex) { - outBuilder.append(URLDecoder.decode(stringToDecode.substring(startDex, m), "UTF-8")); - } - - outBuilder.append("+"); - startDex = m + 1; - } - } - - if (startDex != stringToDecode.length()) { - outBuilder.append(URLDecoder.decode(stringToDecode.substring(startDex, stringToDecode.length()), - "UTF-8")); - } - - return outBuilder.toString(); - } - else { - return URLDecoder.decode(stringToDecode, "UTF-8"); - } - } - catch (final UnsupportedEncodingException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - /** - * Performs safe encoding of the specified string, taking care to insert %20 for each space character, - * instead of inserting the + character. - * - * @param stringToEncode - * A String that represents the string to encode. - * - * @return A String that represents the encoded string. - * - * @throws StorageException - * If a storage service error occurred. - */ - public static String safeEncode(final String stringToEncode) throws StorageException { - if (stringToEncode == null) { - return null; - } - if (stringToEncode.length() == 0) { - return Constants.EMPTY_STRING; - } - - try { - final String tString = URLEncoder.encode(stringToEncode, "UTF-8"); - - if (stringToEncode.contains(" ")) { - final StringBuilder outBuilder = new StringBuilder(); - - int startDex = 0; - for (int m = 0; m < stringToEncode.length(); m++) { - if (stringToEncode.charAt(m) == ' ') { - if (m > startDex) { - outBuilder.append(URLEncoder.encode(stringToEncode.substring(startDex, m), "UTF-8")); - } - - outBuilder.append("%20"); - startDex = m + 1; - } - } - - if (startDex != stringToEncode.length()) { - outBuilder.append(URLEncoder.encode(stringToEncode.substring(startDex, stringToEncode.length()), - "UTF-8")); - } - - return outBuilder.toString(); - } - else { - return tString; - } - - } - catch (final UnsupportedEncodingException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - /** - * Determines the relative difference between the two specified URIs. - * - * @param baseURI - * A java.net.URI object that represents the base URI for which toUri will be - * made relative. - * @param toUri - * A java.net.URI object that represents the URI to make relative to baseURI. - * - * @return A String that either represents the relative URI of toUri to - * baseURI, or the URI of toUri itself, depending on whether the hostname and - * scheme are identical for toUri and baseURI. If the hostname and scheme of - * baseURI and toUri are identical, this method returns a relative URI such that - * if appended to baseURI, it will yield toUri. If the hostname or scheme of - * baseURI and toUri are not identical, this method returns the full URI specified - * by toUri. - * - * @throws URISyntaxException - * If baseURI or toUri is invalid. - */ - public static String safeRelativize(final URI baseURI, final URI toUri) throws URISyntaxException { - // For compatibility followed - // http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx - - // if host and scheme are not identical return from uri - if (!baseURI.getHost().equals(toUri.getHost()) || !baseURI.getScheme().equals(toUri.getScheme())) { - return toUri.toString(); - } - - final String basePath = baseURI.getPath(); - String toPath = toUri.getPath(); - - int truncatePtr = 1; - - // Seek to first Difference - // int maxLength = Math.min(basePath.length(), toPath.length()); - int m = 0; - int ellipsesCount = 0; - for (; m < basePath.length(); m++) { - if (m >= toPath.length()) { - if (basePath.charAt(m) == '/') { - ellipsesCount++; - } - } - else { - if (basePath.charAt(m) != toPath.charAt(m)) { - break; - } - else if (basePath.charAt(m) == '/') { - truncatePtr = m + 1; - } - } - } - - if (m == toPath.length()) { - // No path difference, return query + fragment - return new URI(null, null, null, toUri.getQuery(), toUri.getFragment()).toString(); - } - else { - toPath = toPath.substring(truncatePtr); - final StringBuilder sb = new StringBuilder(); - while (ellipsesCount > 0) { - sb.append("../"); - ellipsesCount--; - } - - if (!Utility.isNullOrEmpty(toPath)) { - sb.append(toPath); - } - - if (!Utility.isNullOrEmpty(toUri.getQuery())) { - sb.append("?"); - sb.append(toUri.getQuery()); - } - if (!Utility.isNullOrEmpty(toUri.getFragment())) { - sb.append("#"); - sb.append(toUri.getRawFragment()); - } - - return sb.toString(); - } - } - - /** - * Trims the specified character from the end of a string. - * - * @param value - * A String that represents the string to trim. - * @param trimChar - * The character to trim from the end of the string. - * - * @return The string with the specified character trimmed from the end. - */ - protected static String trimEnd(final String value, final char trimChar) { - int stopDex = value.length() - 1; - while (stopDex > 0 && value.charAt(stopDex) == trimChar) { - stopDex--; - } - - return stopDex == value.length() - 1 ? value : value.substring(stopDex); - } - - /** - * Trims whitespace from the beginning of a string. - * - * @param value - * A String that represents the string to trim. - * - * @return The string with whitespace trimmed from the beginning. - */ - public static String trimStart(final String value) { - int spaceDex = 0; - while (spaceDex < value.length() && value.charAt(spaceDex) == ' ') { - spaceDex++; - } - - return value.substring(spaceDex); - } - - /** - * Reads data from an input stream and writes it to an output stream, calculates the length of the data written, and - * optionally calculates the MD5 hash for the data. - * - * @param sourceStream - * An InputStream object that represents the input stream to use as the source. - * @param outStream - * An OutputStream object that represents the output stream to use as the destination. - * @param writeLength - * The number of bytes to read from the stream. - * @param rewindSourceStream - * true if the input stream should be rewound before it is read; otherwise, - * false - * @param calculateMD5 - * true if an MD5 hash will be calculated; otherwise, false. - * @param currentResult - * A {@link RequestResult} object that represents the result for the current request. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link StreamMd5AndLength} object that contains the output stream length, and optionally the MD5 hash. - * - * @throws IOException - * If an I/O error occurs. - * @throws StorageException - * If a storage service error occurred. - */ - public static StreamMd5AndLength writeToOutputStream(final InputStream sourceStream, final OutputStream outStream, - long writeLength, final boolean rewindSourceStream, final boolean calculateMD5, - final RequestResult currentResult, OperationContext opContext) throws IOException, StorageException { - if (opContext != null) { - opContext.setCurrentOperationByteCount(0); - } - else { - opContext = new OperationContext(); - } - - if (rewindSourceStream && sourceStream.markSupported()) { - sourceStream.reset(); - sourceStream.mark(Constants.MAX_MARK_LENGTH); - } - - if (calculateMD5 && opContext.getIntermediateMD5() == null) { - try { - opContext.setIntermediateMD5(MessageDigest.getInstance("MD5")); - } - catch (final NoSuchAlgorithmException e) { - // This wont happen, throw fatal. - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - final StreamMd5AndLength retVal = new StreamMd5AndLength(); - - if (writeLength < 0) { - writeLength = Long.MAX_VALUE; - } - - int count = -1; - final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; - int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength()); - - count = sourceStream.read(retrievedBuff, 0, nextCopy); - - while (nextCopy > 0 && count != -1) { - if (outStream != null) { - outStream.write(retrievedBuff, 0, count); - } - - if (calculateMD5) { - opContext.getIntermediateMD5().update(retrievedBuff, 0, count); - } - - retVal.setLength(retVal.getLength() + count); - if (opContext != null) { - opContext.setCurrentOperationByteCount(opContext.getCurrentOperationByteCount() + count); - } - - nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength()); - count = sourceStream.read(retrievedBuff, 0, nextCopy); - } - - if (outStream != null) { - outStream.flush(); - } - - if (calculateMD5) { - retVal.setDigest(opContext.getIntermediateMD5()); - } - - return retVal; - } - - /** - * Private Default Ctor. - */ - private Utility() { - // No op - } - - public static void checkNullaryCtor(Class clazzType) { - Constructor ctor = null; - try { - ctor = clazzType.getDeclaredConstructor((Class[]) null); - } - catch (Exception e) { - throw new IllegalArgumentException("Class type must have contain a nullary constructor."); - } - - if (ctor == null) { - throw new IllegalArgumentException("Class type must have contain a nullary constructor."); - } - } - - public static Date parseDate(String dateString) { - try { - if (dateString.length() == 28) { - // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"-> [2012-01-04T23:21:59.1234567Z] length = 28 - return Utility.parseDateFromString(dateString, Utility.ISO8061_LONG_PATTERN, Utility.UTC_ZONE); - } - else if (dateString.length() == 20) { - // "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length = 20 - return Utility.parseDateFromString(dateString, Utility.ISO8061_PATTERN, Utility.UTC_ZONE); - } - else if (dateString.length() == 17) { - // "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17 - return Utility.parseDateFromString(dateString, Utility.ISO8061_PATTERN_NO_SECONDS, Utility.UTC_ZONE); - } - else if (dateString.length() == 27) { - // "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"-> [2012-01-04T23:21:59.123456Z] length = 27 - return Utility.parseDateFromString(dateString, "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", Utility.UTC_ZONE); - } - else if (dateString.length() == 26) { - // "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"-> [2012-01-04T23:21:59.12345Z] length = 26 - return Utility.parseDateFromString(dateString, "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'", Utility.UTC_ZONE); - } - else if (dateString.length() == 25) { - // "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z] length = 25 - return Utility.parseDateFromString(dateString, "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'", Utility.UTC_ZONE); - } - else if (dateString.length() == 24) { - // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z] length = 24 - return Utility.parseDateFromString(dateString, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Utility.UTC_ZONE); - } - else if (dateString.length() == 23) { - // "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z] length = 23 - return Utility.parseDateFromString(dateString, "yyyy-MM-dd'T'HH:mm:ss.SS'Z'", Utility.UTC_ZONE); - } - else if (dateString.length() == 22) { - // "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z] length = 22 - return Utility.parseDateFromString(dateString, "yyyy-MM-dd'T'HH:mm:ss.S'Z'", Utility.UTC_ZONE); - } - else { - throw new IllegalArgumentException(String.format("Invalid Date String: %s", dateString)); - } - } - catch (final ParseException e) { - throw new IllegalArgumentException(String.format("Invalid Date String: %s", dateString), e); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BaseRequest.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BaseRequest.java deleted file mode 100644 index 92209d4e18743..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BaseRequest.java +++ /dev/null @@ -1,573 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.InvalidKeyException; -import java.util.HashMap; -import java.util.Map.Entry; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.Credentials; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ServiceProperties; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.StorageKey; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. The Base Request class for the protocol layer. - */ -public final class BaseRequest { - /** - * Adds the lease id. - * - * @param request - * a HttpURLConnection for the operation. - * @param leaseId - * the lease id to add to the HttpURLConnection. - */ - public static void addLeaseId(final HttpURLConnection request, final String leaseId) { - if (leaseId != null) { - BaseRequest.addOptionalHeader(request, "x-ms-lease-id", leaseId); - } - } - - /** - * Stores the user agent to send over the wire to identify the client. - */ - private static String userAgent; - - /** - * Adds the metadata. - * - * @param request - * The request. - * @param metadata - * The metadata. - */ - public static void addMetadata(final HttpURLConnection request, final HashMap metadata, - final OperationContext opContext) { - if (metadata != null) { - for (final Entry entry : metadata.entrySet()) { - addMetadata(request, entry.getKey(), entry.getValue(), opContext); - } - } - } - - /** - * Adds the metadata. - * - * @param opContext - * an object used to track the execution of the operation - * @param request - * The request. - * @param name - * The metadata name. - * @param value - * The metadata value. - */ - public static void addMetadata(final HttpURLConnection request, final String name, final String value, - final OperationContext opContext) { - Utility.assertNotNullOrEmpty("value", value); - - request.setRequestProperty(Constants.HeaderConstants.PREFIX_FOR_STORAGE_METADATA + name, value); - } - - /** - * Adds the optional header. - * - * @param request - * a HttpURLConnection for the operation. - * @param name - * the metadata name. - * @param value - * the metadata value. - */ - public static void addOptionalHeader(final HttpURLConnection request, final String name, final String value) { - if (value != null && !value.equals(Constants.EMPTY_STRING)) { - request.setRequestProperty(name, value); - } - } - - /** - * Adds the snapshot. - * - * @param builder - * a query builder. - * @param snapshotVersion - * the snapshot version to the query builder. - * @throws StorageException - */ - public static void addSnapshot(final UriQueryBuilder builder, final String snapshotVersion) throws StorageException { - if (snapshotVersion != null) { - builder.add("snapshot", snapshotVersion); - } - } - - /** - * Creates the specified resource. Note request is set to setFixedLengthStreamingMode(0); Sign with 0 length. - * - * @param uri - * the request Uri. - * @param timeout - * the timeout for the request - * @param builder - * the UriQueryBuilder for the request - * @param opContext - * an object used to track the execution of the operation - * @return a HttpURLConnection to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if there is an improperly formated URI - * @throws StorageException - * @throws IllegalArgumentException - */ - public static HttpURLConnection create(final URI uri, final int timeout, UriQueryBuilder builder, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - if (builder == null) { - builder = new UriQueryBuilder(); - } - - final HttpURLConnection retConnection = createURLConnection(uri, timeout, builder, opContext); - retConnection.setFixedLengthStreamingMode(0); - retConnection.setDoOutput(true); - retConnection.setRequestMethod("PUT"); - - return retConnection; - } - - /** - * Creates the web request. - * - * @param uri - * the request Uri. - * @param timeoutInMs - * the timeout for the request - * @param builder - * the UriQueryBuilder for the request - * @param opContext - * an object used to track the execution of the operation - * @return a HttpURLConnection to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if there is an improperly formated URI - * @throws StorageException - */ - public static HttpURLConnection createURLConnection(final URI uri, final int timeoutInMs, UriQueryBuilder builder, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - if (builder == null) { - builder = new UriQueryBuilder(); - } - - if (timeoutInMs != 0) { - builder.add("timeout", String.valueOf(timeoutInMs / 1000)); - } - - final URL resourceUrl = builder.addToURI(uri).toURL(); - - final HttpURLConnection retConnection = (HttpURLConnection) resourceUrl.openConnection(); - - retConnection.setReadTimeout(timeoutInMs); - - // Note : accept behavior, java by default sends Accept behavior - // as text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 This will need to be set for table requests. - // - // To override set retConnection.setRequestProperty("Accept", - // "application/atom+xml"); - - retConnection.setRequestProperty(Constants.HeaderConstants.STORAGE_VERSION_HEADER, - Constants.HeaderConstants.TARGET_STORAGE_VERSION); - retConnection.setRequestProperty(Constants.HeaderConstants.USER_AGENT, getUserAgent()); - retConnection.setRequestProperty(Constants.HeaderConstants.CLIENT_REQUEST_ID_HEADER, - opContext.getClientRequestID()); - - // Java6 TODO remove me, this has to be manually set or it will - // sometimes default to application/x-www-form-urlencoded without us - // knowing causing auth fails in Java5. - retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, ""); - return retConnection; - } - - /** - * Deletes the specified resource. Sign with no length specified. - * - * @param uri - * the request Uri. - * @param timeout - * the timeout for the request - * @param builder - * the UriQueryBuilder for the request - * @param opContext - * an object used to track the execution of the operation - * @return a HttpURLConnection to perform the operation. - * @throws IOException - * if there is an error opening the connection - * @throws URISyntaxException - * if there is an improperly formated URI - * @throws StorageException - */ - public static HttpURLConnection delete(final URI uri, final int timeout, UriQueryBuilder builder, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - if (builder == null) { - builder = new UriQueryBuilder(); - } - - final HttpURLConnection retConnection = createURLConnection(uri, timeout, builder, opContext); - - retConnection.setDoOutput(true); - retConnection.setRequestMethod("DELETE"); - - return retConnection; - } - - /** - * Gets the metadata. Sign with no length specified. - * - * @param uri - * The Uri to query. - * @param timeout - * The timeout. - * @param builder - * The builder. - * @param opContext - * an object used to track the execution of the operation - * @return a web request for performing the operation. - * @throws StorageException - * @throws URISyntaxException - * @throws IOException - * */ - public static HttpURLConnection getMetadata(final URI uri, final int timeout, UriQueryBuilder builder, - final OperationContext opContext) throws StorageException, IOException, URISyntaxException { - if (builder == null) { - builder = new UriQueryBuilder(); - } - - builder.add("comp", "metadata"); - final HttpURLConnection retConnection = createURLConnection(uri, timeout, builder, opContext); - - retConnection.setDoOutput(true); - retConnection.setRequestMethod("HEAD"); - - return retConnection; - } - - /** - * Gets the properties. Sign with no length specified. - * - * @param uri - * The Uri to query. - * @param timeout - * The timeout. - * @param builder - * The builder. - * @param opContext - * an object used to track the execution of the operation - * @return a web request for performing the operation. - * @throws StorageException - * @throws URISyntaxException - * @throws IOException - * */ - public static HttpURLConnection getProperties(final URI uri, final int timeout, UriQueryBuilder builder, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - if (builder == null) { - builder = new UriQueryBuilder(); - } - - final HttpURLConnection retConnection = createURLConnection(uri, timeout, builder, opContext); - - retConnection.setDoOutput(true); - retConnection.setRequestMethod("HEAD"); - - return retConnection; - } - - /** - * Creates a HttpURLConnection used to retrieve the Analytics service properties from the storage service. - * - * @param uri - * The service endpoint. - * @param timeout - * The timeout. - * @param builder - * The builder. - * @param opContext - * an object used to track the execution of the operation - * @return a web request for performing the operation. - * @throws IOException - * @throws URISyntaxException - * @throws StorageException - */ - public static HttpURLConnection getServiceProperties(final URI uri, final int timeout, UriQueryBuilder builder, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - if (builder == null) { - builder = new UriQueryBuilder(); - } - - builder.add("comp", "properties"); - builder.add("restype", "service"); - - final HttpURLConnection retConnection = createURLConnection(uri, timeout, builder, opContext); - - retConnection.setDoOutput(true); - retConnection.setRequestMethod("GET"); - - return retConnection; - } - - /** - * Gets the user agent to send over the wire to identify the client. - * - * @return the user agent to send over the wire to identify the client. - */ - public static String getUserAgent() { - if (userAgent == null) { - userAgent = String.format("%s/%s", Constants.HeaderConstants.USER_AGENT_PREFIX, - Constants.HeaderConstants.USER_AGENT_VERSION); - } - return userAgent; - } - - /** - * Writes the contents of the ServiceProperties object to a byte array in XML form. - * - * @param properties - * the ServiceProperties to write to the stream. - * @param opContext - * an object used to track the execution of the operation - * @return the number of bytes written to the output stream. - * @throws XMLStreamException - * if there is an error writing the content to the stream. - * @throws StorageException - */ - public static byte[] serializeServicePropertiesToByteArray(final ServiceProperties properties, - final OperationContext opContext) throws XMLStreamException, StorageException { - return properties.serializeToByteArray(opContext); - } - - /** - * Sets the metadata. Sign with 0 length. - * - * @param uri - * The blob Uri. - * @param timeout - * The timeout. - * @param builder - * The builder. - * @param opContext - * an object used to track the execution of the operation - * @return a web request for performing the operation. - * @throws StorageException - * @throws URISyntaxException - * @throws IOException - * */ - public static HttpURLConnection setMetadata(final URI uri, final int timeout, UriQueryBuilder builder, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - - if (builder == null) { - builder = new UriQueryBuilder(); - } - - builder.add("comp", "metadata"); - final HttpURLConnection retConnection = createURLConnection(uri, timeout, builder, opContext); - - retConnection.setFixedLengthStreamingMode(0); - retConnection.setDoOutput(true); - retConnection.setRequestMethod("PUT"); - - return retConnection; - } - - /** - * Creates a HttpURLConnection used to set the Analytics service properties on the storage service. - * - * @param uri - * The service endpoint. - * @param timeout - * The timeout. - * @param builder - * The builder. - * @param opContext - * an object used to track the execution of the operation - * @return a web request for performing the operation. - * @throws IOException - * @throws URISyntaxException - * @throws StorageException - */ - public static HttpURLConnection setServiceProperties(final URI uri, final int timeout, UriQueryBuilder builder, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - if (builder == null) { - builder = new UriQueryBuilder(); - } - - builder.add("comp", "properties"); - builder.add("restype", "service"); - - final HttpURLConnection retConnection = createURLConnection(uri, timeout, builder, opContext); - - retConnection.setDoOutput(true); - retConnection.setRequestMethod("PUT"); - - return retConnection; - } - - /** - * Signs the request appropriately to make it an authenticated request for Blob and Queue. - * - * @param request - * a HttpURLConnection for the operation. - * @param credentials - * the credentials to use for signing. - * @param contentLength - * the length of the content written to the output stream, -1 if unknown. - * @param opContext - * an object used to track the execution of the operation - * @throws InvalidKeyException - * if the credentials key is invalid. - * @throws StorageException - */ - public static void signRequestForBlobAndQueue(final HttpURLConnection request, final Credentials credentials, - final Long contentLength, final OperationContext opContext) throws InvalidKeyException, StorageException { - request.setRequestProperty(Constants.HeaderConstants.DATE, Utility.getGMTTime()); - final Canonicalizer canonicalizer = CanonicalizerFactory.getBlobQueueFullCanonicalizer(request); - - final String stringToSign = canonicalizer.canonicalize(request, credentials.getAccountName(), contentLength, - opContext); - - final String computedBase64Signature = StorageKey.computeMacSha256(credentials.getKey(), stringToSign); - - // V2 add logging - // System.out.println(String.format("Signing %s\r\n%s\r\n", stringToSign, computedBase64Signature)); - request.setRequestProperty(Constants.HeaderConstants.AUTHORIZATION, - String.format("%s %s:%s", "SharedKey", credentials.getAccountName(), computedBase64Signature)); - } - - /** - * - * Signs the request appropriately to make it an authenticated request for Blob and Queue. - * - * @param request - * a HttpURLConnection for the operation. - * @param credentials - * the credentials to use for signing. - * @param contentLength - * the length of the content written to the output stream, -1 if unknown. - * @param opContext - * an object used to track the execution of the operation - * @throws InvalidKeyException - * if the credentials key is invalid. - * @throws StorageException - */ - public static void signRequestForBlobAndQueueSharedKeyLite(final HttpURLConnection request, - final Credentials credentials, final Long contentLength, final OperationContext opContext) - throws InvalidKeyException, StorageException { - request.setRequestProperty(Constants.HeaderConstants.DATE, Utility.getGMTTime()); - - final Canonicalizer canonicalizer = CanonicalizerFactory.getBlobQueueLiteCanonicalizer(request); - - final String stringToSign = canonicalizer.canonicalize(request, credentials.getAccountName(), contentLength, - opContext); - - final String computedBase64Signature = StorageKey.computeMacSha256(credentials.getKey(), stringToSign); - - // VNext add logging - // System.out.println(String.format("Signing %s\r\n%s\r\n", - // stringToSign, computedBase64Signature)); - request.setRequestProperty(Constants.HeaderConstants.AUTHORIZATION, - String.format("%s %s:%s", "SharedKeyLite", credentials.getAccountName(), computedBase64Signature)); - } - - /** - * - * Signs the request appropriately to make it an authenticated request for Table. - * - * @param request - * a HttpURLConnection for the operation. - * @param credentials - * the credentials to use for signing. - * @param contentLength - * the length of the content written to the output stream, -1 if unknown. - * @param opContext - * an object used to track the execution of the operation - * @throws InvalidKeyException - * if the credentials key is invalid. - * @throws StorageException - */ - public static void signRequestForTableSharedKey(final HttpURLConnection request, final Credentials credentials, - final Long contentLength, final OperationContext opContext) throws InvalidKeyException, StorageException { - request.setRequestProperty(Constants.HeaderConstants.DATE, Utility.getGMTTime()); - - final Canonicalizer canonicalizer = CanonicalizerFactory.getTableFullCanonicalizer(request); - - final String stringToSign = canonicalizer.canonicalize(request, credentials.getAccountName(), contentLength, - opContext); - - final String computedBase64Signature = StorageKey.computeMacSha256(credentials.getKey(), stringToSign); - - // TODO Vnext add logging - // System.out.println(String.format("Signing %s\r\n%s\r\n", stringToSign, computedBase64Signature)); - request.setRequestProperty(Constants.HeaderConstants.AUTHORIZATION, - String.format("%s %s:%s", "SharedKey", credentials.getAccountName(), computedBase64Signature)); - } - - /** - * - * Signs the request appropriately to make it an authenticated request for Table. - * - * @param request - * a HttpURLConnection for the operation. - * @param credentials - * the credentials to use for signing. - * @param contentLength - * the length of the content written to the output stream, -1 if unknown. - * @param opContext - * an object used to track the execution of the operation - * @throws InvalidKeyException - * if the credentials key is invalid. - * @throws StorageException - */ - public static void signRequestForTableSharedKeyLite(final HttpURLConnection request, final Credentials credentials, - final Long contentLength, final OperationContext opContext) throws InvalidKeyException, StorageException { - request.setRequestProperty(Constants.HeaderConstants.DATE, Utility.getGMTTime()); - - final Canonicalizer canonicalizer = CanonicalizerFactory.getTableLiteCanonicalizer(request); - - final String stringToSign = canonicalizer.canonicalize(request, credentials.getAccountName(), contentLength, - opContext); - - final String computedBase64Signature = StorageKey.computeMacSha256(credentials.getKey(), stringToSign); - - // TODO Vnext add logging - // System.out.println(String.format("Signing %s\r\n%s\r\n", stringToSign, computedBase64Signature)); - request.setRequestProperty(Constants.HeaderConstants.AUTHORIZATION, - String.format("%s %s:%s", "SharedKeyLite", credentials.getAccountName(), computedBase64Signature)); - } - - /** - * Private Default Ctor - */ - private BaseRequest() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BaseResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BaseResponse.java deleted file mode 100644 index e0412b996cdab..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BaseResponse.java +++ /dev/null @@ -1,236 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.blob.client.CopyState; -import com.microsoft.windowsazure.services.blob.client.CopyStatus; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.LeaseDuration; -import com.microsoft.windowsazure.services.core.storage.LeaseState; -import com.microsoft.windowsazure.services.core.storage.LeaseStatus; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ServiceProperties; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. The base response class for the protocol layer - */ -public class BaseResponse { - /** - * Gets the ContentMD5 - * - * @param request - * The response from server. - * @return The ContentMD5. - */ - public static String getContentMD5(final HttpURLConnection request) { - return request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); - } - - /** - * Gets the Date - * - * @param request - * The response from server. - * @return The Date. - */ - public static String getDate(final HttpURLConnection request) { - final String retString = request.getHeaderField("Date"); - return retString == null ? request.getHeaderField(Constants.HeaderConstants.DATE) : retString; - } - - /** - * Gets the Etag - * - * @param request - * The response from server. - * @return The Etag. - */ - public static String getEtag(final HttpURLConnection request) { - return request.getHeaderField(Constants.ETAG_ELEMENT); - } - - /** - * Gets the metadata from the request The response from server. - * - * @return the metadata from the request - */ - public static HashMap getMetadata(final HttpURLConnection request) { - return getValuesByHeaderPrefix(request, Constants.HeaderConstants.PREFIX_FOR_STORAGE_METADATA); - } - - /** - * Gets the LeaseStatus - * - * @param request - * The response from server. - * @return The Etag. - */ - public static LeaseStatus getLeaseStatus(final HttpURLConnection request) { - final String leaseStatus = request.getHeaderField(Constants.HeaderConstants.LEASE_STATUS); - if (!Utility.isNullOrEmpty(leaseStatus)) { - return LeaseStatus.parse(leaseStatus); - } - - return LeaseStatus.UNSPECIFIED; - } - - /** - * Gets the LeaseState - * - * @param request - * The response from server. - * @return The LeaseState. - */ - public static LeaseState getLeaseState(final HttpURLConnection request) { - final String leaseState = request.getHeaderField(Constants.HeaderConstants.LEASE_STATE); - if (!Utility.isNullOrEmpty(leaseState)) { - return LeaseState.parse(leaseState); - } - - return LeaseState.UNSPECIFIED; - } - - /** - * Gets the LeaseDuration - * - * @param request - * The response from server. - * @return The LeaseDuration. - */ - public static LeaseDuration getLeaseDuration(final HttpURLConnection request) { - final String leaseDuration = request.getHeaderField(Constants.HeaderConstants.LEASE_DURATION); - if (!Utility.isNullOrEmpty(leaseDuration)) { - return LeaseDuration.parse(leaseDuration); - } - - return LeaseDuration.UNSPECIFIED; - } - - /** - * Gets the copyState - * - * @param request - * The response from server. - * @return The CopyState. - * @throws URISyntaxException - * @throws ParseException - */ - public static CopyState getCopyState(final HttpURLConnection request) throws URISyntaxException, ParseException { - String copyStatusString = request.getHeaderField(Constants.HeaderConstants.COPY_STATUS); - if (!Utility.isNullOrEmpty(copyStatusString)) { - CopyState copyState = new CopyState(); - copyState.setStatus(CopyStatus.parse(copyStatusString)); - copyState.setCopyId(request.getHeaderField(Constants.HeaderConstants.COPY_ID)); - copyState.setStatusDescription(request.getHeaderField(Constants.HeaderConstants.COPY_STATUS_DESCRIPTION)); - - final String copyProgressString = request.getHeaderField(Constants.HeaderConstants.COPY_PROGRESS); - if (!Utility.isNullOrEmpty(copyProgressString)) { - String[] progressSequence = copyProgressString.split("/"); - copyState.setBytesCopied(Long.parseLong(progressSequence[0])); - copyState.setTotalBytes(Long.parseLong(progressSequence[1])); - } - - final String copySourceString = request.getHeaderField(Constants.HeaderConstants.COPY_SOURCE); - if (!Utility.isNullOrEmpty(copySourceString)) { - copyState.setSource(new URI(copySourceString)); - } - - final String copyCompletionTimeString = request - .getHeaderField(Constants.HeaderConstants.COPY_COMPLETION_TIME); - if (!Utility.isNullOrEmpty(copyCompletionTimeString)) { - copyState.setCompletionTime(Utility.parseRFC1123DateFromStringInGMT(copyCompletionTimeString)); - } - - return copyState; - } - else { - return null; - } - } - - /** - * Gets the request id. - * - * @param request - * The response from server. - * @return The request ID. - */ - public static String getRequestId(final HttpURLConnection request) { - return request.getHeaderField(Constants.HeaderConstants.REQUEST_ID_HEADER); - } - - /** - * Returns all the header/value pairs with the given prefix. - * - * @param request - * the request object containing headers to parse. - * @param prefix - * the prefix for headers to be returned. - * @return all the header/value pairs with the given prefix. - */ - private static HashMap getValuesByHeaderPrefix(final HttpURLConnection request, final String prefix) { - final HashMap retVals = new HashMap(); - final Map> headerMap = request.getHeaderFields(); - final int prefixLength = prefix.length(); - - for (final Entry> entry : headerMap.entrySet()) { - if (entry.getKey() != null && entry.getKey().startsWith(prefix)) { - final List currHeaderValues = entry.getValue(); - retVals.put(entry.getKey().substring(prefixLength), currHeaderValues.get(0)); - } - } - - return retVals; - } - - /** - * Deserializes the ServiceProperties object from an input stream. - * - * @param inStream - * the stream to read from. - * @param opContext - * an object used to track the execution of the operation - * @return a ServiceProperties object representing the Analytics configuration for the client. - * @throws XMLStreamException - * if the xml is invalid. - * @throws StorageException - * if unexpected xml is found. - */ - public static ServiceProperties readServicePropertiesFromStream(final InputStream inStream, - final OperationContext opContext) throws XMLStreamException, StorageException { - return ServiceProperties.readServicePropertiesFromStream(inStream, opContext); - } - - /** - * Private Default Ctor - */ - protected BaseResponse() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BlobQueueFullCanonicalizer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BlobQueueFullCanonicalizer.java deleted file mode 100644 index 40bd6c1481716..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BlobQueueFullCanonicalizer.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.net.HttpURLConnection; -import java.security.InvalidParameterException; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. Provides an implementation of the Canonicalizer class for requests against Blob and Queue - * Service under the Shared Key authentication scheme. - */ -final class BlobQueueFullCanonicalizer extends Canonicalizer { - - /** - * Constructs a canonicalized string for signing a request. - * - * @param conn - * the HttpURLConnection to canonicalize - * @param accountName - * the account name associated with the request - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param opContext - * the OperationContext for the given request - * @return a canonicalized string. - * @throws StorageException - */ - @Override - protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength, - final OperationContext opContext) throws StorageException { - - if (contentLength < -1) { - throw new InvalidParameterException("ContentLength must be set to -1 or positive Long value"); - } - - return canonicalizeHttpRequest(conn.getURL(), accountName, conn.getRequestMethod(), - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_TYPE), contentLength, null, - conn, opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BlobQueueLiteCanonicalizer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BlobQueueLiteCanonicalizer.java deleted file mode 100644 index 5d36b8b7a1691..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/BlobQueueLiteCanonicalizer.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.net.HttpURLConnection; -import java.security.InvalidParameterException; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. Provides an implementation of the Canonicalizer class for requests against Blob and Queue - * Service under the Shared Key authentication scheme. - */ -final class BlobQueueLiteCanonicalizer extends Canonicalizer { - - /** - * Constructs a canonicalized string for signing a request. - * - * @param conn - * the HttpURLConnection to canonicalize - * @param accountName - * the account name associated with the request - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param opContext - * the OperationContext for the given request - * @return a canonicalized string. - * @throws StorageException - */ - @Override - protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength, - final OperationContext opContext) throws StorageException { - if (contentLength < -1) { - throw new InvalidParameterException("ContentLength must be set to -1 or positive Long value"); - } - - return canonicalizeHttpRequestLite(conn.getURL(), accountName, conn.getRequestMethod(), - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_TYPE), contentLength, null, - conn, opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/Canonicalizer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/Canonicalizer.java deleted file mode 100644 index 77c5f71d266d7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/Canonicalizer.java +++ /dev/null @@ -1,454 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. This is a Version 2 Canonicalization strategy conforming to the PDC 2009-09-19 - * specification - */ -abstract class Canonicalizer { - - /** - * The expected length for the canonicalized string when SharedKeyFull is used to sign requests. - */ - private static final int ExpectedBlobQueueCanonicalizedStringLength = 300; - - /** - * The expected length for the canonicalized string when SharedKeyLite is used to sign requests. - */ - private static final int ExpectedBlobQueueLiteCanonicalizedStringLength = 250; - - /** - * The expected length for the canonicalized string when SharedKeyFull is used to sign table requests. - */ - private static final int ExpectedTableCanonicalizedStringLength = 200; - - /** - * Add x-ms- prefixed headers in a fixed order. - * - * @param conn - * the HttpURLConnection for the operation - * @param canonicalizedString - * the canonicalized string to add the canonicalized headerst to. - */ - private static void addCanonicalizedHeaders(final HttpURLConnection conn, final StringBuilder canonicalizedString) { - // Look for header names that start with - // HeaderNames.PrefixForStorageHeader - // Then sort them in case-insensitive manner. - - final Map> headers = conn.getRequestProperties(); - final ArrayList httpStorageHeaderNameArray = new ArrayList(); - - for (final String key : headers.keySet()) { - if (key.toLowerCase(Utility.LOCALE_US).startsWith(Constants.PREFIX_FOR_STORAGE_HEADER)) { - httpStorageHeaderNameArray.add(key.toLowerCase(Utility.LOCALE_US)); - } - } - - Collections.sort(httpStorageHeaderNameArray); - - // Now go through each header's values in the sorted order and append - // them to the canonicalized string. - for (final String key : httpStorageHeaderNameArray) { - final StringBuilder canonicalizedElement = new StringBuilder(key); - String delimiter = ":"; - final ArrayList values = getHeaderValues(headers, key); - - // Go through values, unfold them, and then append them to the - // canonicalized element string. - for (final String value : values) { - // Unfolding is simply removal of CRLF. - final String unfoldedValue = value.replace("\r\n", Constants.EMPTY_STRING); - - // Append it to the canonicalized element string. - canonicalizedElement.append(delimiter); - canonicalizedElement.append(unfoldedValue); - delimiter = ","; - } - - // Now, add this canonicalized element to the canonicalized header - // string. - appendCanonicalizedElement(canonicalizedString, canonicalizedElement.toString()); - } - } - - /** - * Append a string to a string builder with a newline constant - * - * @param builder - * the StringBuilder object - * @param element - * the string to append. - */ - protected static void appendCanonicalizedElement(final StringBuilder builder, final String element) { - builder.append("\n"); - builder.append(element); - } - - /** - * Constructs a canonicalized string from the request's headers that will be used to construct the signature string - * for signing a Blob or Queue service request under the Shared Key Full authentication scheme. - * - * @param address - * the request URI - * @param accountName - * the account name associated with the request - * @param method - * the verb to be used for the HTTP request. - * @param contentType - * the content type of the HTTP request. - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param date - * the date/time specification for the HTTP request - * @param conn - * the HttpURLConnection for the operation. - * @param opContext - * the OperationContext for the request. - * @return A canonicalized string. - * @throws StorageException - */ - protected static String canonicalizeHttpRequest(final java.net.URL address, final String accountName, - final String method, final String contentType, final long contentLength, final String date, - final HttpURLConnection conn, final OperationContext opContext) throws StorageException { - - // The first element should be the Method of the request. - // I.e. GET, POST, PUT, or HEAD. - final StringBuilder canonicalizedString = new StringBuilder(ExpectedBlobQueueCanonicalizedStringLength); - canonicalizedString.append(conn.getRequestMethod()); - - // The next elements are - // If any element is missing it may be empty. - appendCanonicalizedElement(canonicalizedString, - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_ENCODING)); - appendCanonicalizedElement(canonicalizedString, - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_LANGUAGE)); - appendCanonicalizedElement(canonicalizedString, - contentLength == -1 ? Constants.EMPTY_STRING : String.valueOf(contentLength)); - appendCanonicalizedElement(canonicalizedString, - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_MD5)); - appendCanonicalizedElement(canonicalizedString, contentType != null ? contentType : Constants.EMPTY_STRING); - - final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE); - // If x-ms-date header exists, Date should be empty string - appendCanonicalizedElement(canonicalizedString, dateString.equals(Constants.EMPTY_STRING) ? date - : Constants.EMPTY_STRING); - - String modifiedSinceString = Constants.EMPTY_STRING; - if (conn.getIfModifiedSince() > 0) { - modifiedSinceString = Utility.getGMTTime(new Date(conn.getIfModifiedSince())); - } - - appendCanonicalizedElement(canonicalizedString, modifiedSinceString); - appendCanonicalizedElement(canonicalizedString, - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.IF_MATCH)); - appendCanonicalizedElement(canonicalizedString, - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.IF_NONE_MATCH)); - appendCanonicalizedElement(canonicalizedString, - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.IF_UNMODIFIED_SINCE)); - appendCanonicalizedElement(canonicalizedString, - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.RANGE)); - - addCanonicalizedHeaders(conn, canonicalizedString); - - appendCanonicalizedElement(canonicalizedString, getCanonicalizedResource(address, accountName)); - - return canonicalizedString.toString(); - } - - /** - * Constructs a canonicalized string from the request's headers that will be used to construct the signature string - * for signing a Blob or Queue service request under the Shared Key Lite authentication scheme. - * - * @param address - * the request URI - * @param accountName - * the account name associated with the request - * @param method - * the verb to be used for the HTTP request. - * @param contentType - * the content type of the HTTP request. - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param date - * the date/time specification for the HTTP request - * @param conn - * the HttpURLConnection for the operation. - * @param opContext - * the OperationContext for the request. - * @return A canonicalized string. - * @throws StorageException - */ - protected static String canonicalizeHttpRequestLite(final java.net.URL address, final String accountName, - final String method, final String contentType, final long contentLength, final String date, - final HttpURLConnection conn, final OperationContext opContext) throws StorageException { - // The first element should be the Method of the request. - // I.e. GET, POST, PUT, or HEAD. - // - final StringBuilder canonicalizedString = new StringBuilder(ExpectedBlobQueueLiteCanonicalizedStringLength); - canonicalizedString.append(conn.getRequestMethod()); - - // The second element should be the MD5 value. - // This is optional and may be empty. - final String httpContentMD5Value = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_MD5); - appendCanonicalizedElement(canonicalizedString, httpContentMD5Value); - - // The third element should be the content type. - appendCanonicalizedElement(canonicalizedString, contentType); - - // The fourth element should be the request date. - // See if there's an storage date header. - // If there's one, then don't use the date header. - - final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE); - // If x-ms-date header exists, Date should be empty string - appendCanonicalizedElement(canonicalizedString, dateString.equals(Constants.EMPTY_STRING) ? date - : Constants.EMPTY_STRING); - - addCanonicalizedHeaders(conn, canonicalizedString); - - appendCanonicalizedElement(canonicalizedString, getCanonicalizedResourceLite(address, accountName)); - - return canonicalizedString.toString(); - } - - /** - * Constructs a canonicalized string that will be used to construct the signature string - * for signing a Table service request under the Shared Key authentication scheme. - * - * @param address - * the request URI - * @param accountName - * the account name associated with the request - * @param method - * the verb to be used for the HTTP request. - * @param contentType - * the content type of the HTTP request. - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param date - * the date/time specification for the HTTP request - * @param conn - * the HttpURLConnection for the operation. - * @param opContext - * the OperationContext for the request. - * @return A canonicalized string. - * @throws StorageException - */ - protected static String canonicalizeTableHttpRequest(final java.net.URL address, final String accountName, - final String method, final String contentType, final long contentLength, final String date, - final HttpURLConnection conn, final OperationContext opContext) throws StorageException { - // The first element should be the Method of the request. - // I.e. GET, POST, PUT, or HEAD. - final StringBuilder canonicalizedString = new StringBuilder(ExpectedTableCanonicalizedStringLength); - canonicalizedString.append(conn.getRequestMethod()); - - // The second element should be the MD5 value. - // This is optional and may be empty. - final String httpContentMD5Value = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_MD5); - appendCanonicalizedElement(canonicalizedString, httpContentMD5Value); - - // The third element should be the content type. - appendCanonicalizedElement(canonicalizedString, contentType); - - // The fourth element should be the request date. - // See if there's an storage date header. - // If there's one, then don't use the date header. - - final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE); - // If x-ms-date header exists, Date should be that value. - appendCanonicalizedElement(canonicalizedString, dateString.equals(Constants.EMPTY_STRING) ? date : dateString); - - appendCanonicalizedElement(canonicalizedString, getCanonicalizedResourceLite(address, accountName)); - - return canonicalizedString.toString(); - } - - /** - * Gets the canonicalized resource string for a Blob or Queue service request under the Shared Key Lite - * authentication scheme. - * - * @param address - * the resource URI. - * @param accountName - * the account name for the request. - * @return the canonicalized resource string. - * @throws StorageException - */ - protected static String getCanonicalizedResource(final java.net.URL address, final String accountName) - throws StorageException { - // Resource path - final StringBuilder resourcepath = new StringBuilder("/"); - resourcepath.append(accountName); - - // Note that AbsolutePath starts with a '/'. - resourcepath.append(address.getPath()); - final StringBuilder canonicalizedResource = new StringBuilder(resourcepath.toString()); - - // query parameters - final Map queryVariables = PathUtility.parseQueryString(address.getQuery()); - - final Map lowercasedKeyNameValue = new HashMap(); - - for (final Entry entry : queryVariables.entrySet()) { - // sort the value and organize it as comma separated values - final List sortedValues = Arrays.asList(entry.getValue()); - Collections.sort(sortedValues); - - final StringBuilder stringValue = new StringBuilder(); - - for (final String value : sortedValues) { - if (stringValue.length() > 0) { - stringValue.append(","); - } - - stringValue.append(value); - } - - // key turns out to be null for ?a&b&c&d - lowercasedKeyNameValue.put(entry.getKey() == null ? null : entry.getKey().toLowerCase(Utility.LOCALE_US), - stringValue.toString()); - } - - final ArrayList sortedKeys = new ArrayList(lowercasedKeyNameValue.keySet()); - - Collections.sort(sortedKeys); - - for (final String key : sortedKeys) { - final StringBuilder queryParamString = new StringBuilder(); - - queryParamString.append(key); - queryParamString.append(":"); - queryParamString.append(lowercasedKeyNameValue.get(key)); - - appendCanonicalizedElement(canonicalizedResource, queryParamString.toString()); - } - - return canonicalizedResource.toString(); - } - - /** - * Gets the canonicalized resource string for a Blob or Queue service request under the Shared Key Lite - * authentication scheme. - * - * @param address - * the resource URI. - * @param accountName - * the account name for the request. - * @return the canonicalized resource string. - * @throws StorageException - */ - protected static String getCanonicalizedResourceLite(final java.net.URL address, final String accountName) - throws StorageException { - // Resource path - final StringBuilder resourcepath = new StringBuilder("/"); - resourcepath.append(accountName); - - // Note that AbsolutePath starts with a '/'. - resourcepath.append(address.getPath()); - final StringBuilder canonicalizedResource = new StringBuilder(resourcepath.toString()); - - // query parameters - final Map queryVariables = PathUtility.parseQueryString(address.getQuery()); - - final String[] compVals = queryVariables.get("comp"); - - if (compVals != null) { - - final List sortedValues = Arrays.asList(compVals); - Collections.sort(sortedValues); - - canonicalizedResource.append("?comp="); - - final StringBuilder stringValue = new StringBuilder(); - for (final String value : sortedValues) { - if (stringValue.length() > 0) { - stringValue.append(","); - } - stringValue.append(value); - } - - canonicalizedResource.append(stringValue); - } - - return canonicalizedResource.toString(); - } - - /** - * Gets all the values for the given header in the one to many map, performs a trimStart() on each return value - * - * @param headers - * a one to many map of key / values representing the header values for the connection. - * @param headerName - * the name of the header to lookup - * @return an ArrayList of all trimmed values cooresponding to the requested headerName. This may be empty - * if the header is not found. - */ - private static ArrayList getHeaderValues(final Map> headers, final String headerName) { - - final ArrayList arrayOfValues = new ArrayList(); - List values = null; - - for (final Entry> entry : headers.entrySet()) { - if (entry.getKey().toLowerCase(Utility.LOCALE_US).equals(headerName)) { - values = entry.getValue(); - break; - } - } - if (values != null) { - for (final String value : values) { - // canonicalization formula requires the string to be left - // trimmed. - arrayOfValues.add(Utility.trimStart(value)); - } - } - return arrayOfValues; - } - - /** - * Constructs a canonicalized string for signing a request. - * - * @param conn - * the HttpURLConnection to canonicalize - * @param accountName - * the account name associated with the request - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param opContext - * the OperationContext for the given request - * @return a canonicalized string. - */ - protected abstract String canonicalize(HttpURLConnection conn, String accountName, Long contentLength, - OperationContext opContext) throws StorageException; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/CanonicalizerFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/CanonicalizerFactory.java deleted file mode 100644 index 1ba789f44c40b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/CanonicalizerFactory.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.net.HttpURLConnection; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. Retrieve appropriate version of CanonicalizationStrategy based on the webrequest for Blob - * and Queue. - */ -final class CanonicalizerFactory { - /** - * The Canonicalizer instance for Blob & Queue - */ - private static final BlobQueueFullCanonicalizer BLOB_QUEUE_FULL_V2_INSTANCE = new BlobQueueFullCanonicalizer(); - - /** - * The Canonicalizer instance for Blob & Queue Shared Key Lite - */ - private static final BlobQueueLiteCanonicalizer BLOB_QUEUE_LITE_INSTANCE = new BlobQueueLiteCanonicalizer(); - - /** - * The Canonicalizer instance for Table - */ - private static final TableFullCanonicalizer TABLE_FULL_INSTANCE = new TableFullCanonicalizer(); - - /** - * The Canonicalizer instance for Table Lite - */ - private static final TableLiteCanonicalizer TABLE_LITE_INSTANCE = new TableLiteCanonicalizer(); - - /** - * Gets the Blob queue Canonicalizer full version 2. - * - * @param conn - * the HttpURLConnection for the current operation - * @return the appropriate Canonicalizer for the operation. - */ - protected static Canonicalizer getBlobQueueFullCanonicalizer(final HttpURLConnection conn) { - if (validateVersionIsSupported(conn)) { - return BLOB_QUEUE_FULL_V2_INSTANCE; - } - else { - throw new UnsupportedOperationException("Storage protocol version prior to 2009-09-19 are not supported."); - } - } - - /** - * Gets the Blob queue lite Canonicalizer - * - * @param conn - * the HttpURLConnection for the current operation - * @return the appropriate Canonicalizer for the operation. - */ - protected static Canonicalizer getBlobQueueLiteCanonicalizer(final HttpURLConnection conn) { - if (validateVersionIsSupported(conn)) { - return BLOB_QUEUE_LITE_INSTANCE; - } - else { - throw new UnsupportedOperationException( - "Versions before 2009-09-19 do not support Shared Key Lite for Blob And Queue."); - } - } - - /** - * Gets the table full Canonicalizer. - * - * @param conn - * the HttpURLConnection for the current operation - * @return the appropriate Canonicalizer for the operation. - */ - protected static Canonicalizer getTableFullCanonicalizer(final HttpURLConnection conn) { - return TABLE_FULL_INSTANCE; - } - - /** - * Gets the table lite Canonicalizer - * - * @param conn - * the HttpURLConnection for the current operation - * @return the appropriate Canonicalizer for the operation. - */ - protected static Canonicalizer getTableLiteCanonicalizer(final HttpURLConnection conn) { - if (validateVersionIsSupported(conn)) { - return TABLE_LITE_INSTANCE; - } - else { - throw new UnsupportedOperationException( - "Versions before 2009-09-19 do not support Shared Key Lite for Table."); - } - } - - /** - * Determines if the current request is using a protocol post PDC 2009. - * - * @param conn - * the HttpURLConnection for the current operation - * @return true if is greater or equal PDC 09'; otherwise, false. - */ - private static Boolean validateVersionIsSupported(final HttpURLConnection conn) { - final String versionString = Utility.getStandardHeaderValue(conn, - Constants.HeaderConstants.STORAGE_VERSION_HEADER); - - if (versionString.length() == 0 || versionString.length() == 0) { - return true; - } - - try { - final Calendar versionThresholdCalendar = Calendar.getInstance(Utility.LOCALE_US); - versionThresholdCalendar.set(2009, Calendar.SEPTEMBER, 19, 0, 0, 0); - versionThresholdCalendar.set(Calendar.MILLISECOND, 0); - - final DateFormat versionFormat = new SimpleDateFormat("yyyy-MM-dd"); - final Date versionDate = versionFormat.parse(versionString); - final Calendar requestVersionCalendar = Calendar.getInstance(Utility.LOCALE_US); - requestVersionCalendar.setTime(versionDate); - requestVersionCalendar.set(Calendar.HOUR_OF_DAY, 0); - requestVersionCalendar.set(Calendar.MINUTE, 0); - requestVersionCalendar.set(Calendar.SECOND, 0); - requestVersionCalendar.set(Calendar.MILLISECOND, 1); - - return requestVersionCalendar.compareTo(versionThresholdCalendar) >= 0; - - } - catch (final ParseException e) { - return false; - } - } - - /** - * Private Default Ctor - */ - private CanonicalizerFactory() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/DeserializationHelper.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/DeserializationHelper.java deleted file mode 100644 index 99e9efae7d48c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/DeserializationHelper.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.util.HashMap; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. An internal helper class used to parse objects from responses. - */ -public final class DeserializationHelper { - /** - * Reads Metadata from the XMLStreamReader. - * - * @param xmlr - * the XMLStreamReader object - * @return the metadata as a hashmap. - * @throws XMLStreamException - * if there is a parsing exception - */ - public static HashMap parseMetadateFromXML(final XMLStreamReader xmlr) throws XMLStreamException { - final HashMap retVals = new HashMap(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.METADATA_ELEMENT); - - int eventType = xmlr.getEventType(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.END_ELEMENT && Constants.METADATA_ELEMENT.equals(name)) { - break; - } - else if (Constants.INVALID_METADATA_NAME.equals(name)) { - // no op , skip - } - else if (eventType == XMLStreamConstants.START_ELEMENT) { - final String tValue = Utility.readElementFromXMLReader(xmlr, name); - if (!Utility.isNullOrEmpty(tValue)) { - retVals.put(name, tValue); - } - } - } - - return retVals; - } - - /** - * Private Default Ctor - */ - private DeserializationHelper() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/ExecutionEngine.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/ExecutionEngine.java deleted file mode 100644 index 3a8155a8e6811..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/ExecutionEngine.java +++ /dev/null @@ -1,367 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.Date; -import java.util.concurrent.TimeoutException; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.RequestResult; -import com.microsoft.windowsazure.services.core.storage.ResponseReceivedEvent; -import com.microsoft.windowsazure.services.core.storage.RetryNoRetry; -import com.microsoft.windowsazure.services.core.storage.RetryPolicy; -import com.microsoft.windowsazure.services.core.storage.RetryPolicyFactory; -import com.microsoft.windowsazure.services.core.storage.RetryResult; -import com.microsoft.windowsazure.services.core.storage.SendingRequestEvent; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCode; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.table.client.TableServiceException; - -/** - * RESERVED FOR INTERNAL USE. A class that handles execution of StorageOperations and enforces retry policies. - */ -public final class ExecutionEngine { - - /** - * Executes an operation without a retry policy. - * - * @param - * The service client type - * @param - * The type of the parent object, i.e. CloudBlobContainer for downloadAttributes etc. - * @param - * The type of the expected result - * @param client - * the service client associated with the request - * @param parentObject - * the parent object - * @param task - * the StorageOperation to execute - * @param opContext - * an object used to track the execution of the operation - * @return the result of the operation - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - protected static RESULT_TYPE execute(final CLIENT_TYPE client, - final PARENT_TYPE parentObject, final StorageOperation task, - final OperationContext opContext) throws StorageException { - return executeWithRetry(client, parentObject, task, RetryNoRetry.getInstance(), opContext); - } - - /** - * Executes an operation and enforces a retrypolicy to handle any potential errors - * - * @param - * The service client type - * @param - * The type of the parent object, i.e. CloudBlobContainer for downloadAttributes etc. - * @param - * The type of the expected result - * @param client - * the service client associated with the request - * @param parentObject - * the parent object - * @param task - * the StorageOperation to execute - * @param policyFactory - * the factory used to generate a new retry policy instance - * @param opContext - * an object used to track the execution of the operation - * @return the result of the operation - * @throws StorageException - * an exception representing any error which occurred during the operation. - */ - public static RESULT_TYPE executeWithRetry(final CLIENT_TYPE client, - final PARENT_TYPE parentObject, final StorageOperation task, - final RetryPolicyFactory policyFactory, final OperationContext opContext) throws StorageException { - - final RetryPolicy policy = policyFactory.createInstance(opContext); - RetryResult retryRes; - int currentRetryCount = 0; - StorageException translatedException = null; - final long startTime = new Date().getTime(); - - while (true) { - try { - // reset result flags - task.initialize(opContext); - - final RESULT_TYPE result = task.execute(client, parentObject, opContext); - - opContext.setClientTimeInMs(new Date().getTime() - startTime); - - if (!task.isNonExceptionedRetryableFailure()) { - // Success return result and drain the input stream. - HttpURLConnection request = task.getConnection(); - if ((task.getResult().getStatusCode() >= 200) && (task.getResult().getStatusCode() < 300)) { - if (request != null) { - InputStream inStream = request.getInputStream(); - try { - Utility.writeToOutputStream(inStream, null, -1, false, false, task.getResult(), null); - } - // At this point, we already have a result / exception to return to the user. - // This is just an optimization to improve socket reuse. - catch (final IOException ex) { - } - catch (StorageException e) { - } - finally { - inStream.close(); - } - } - } - return result; - } - else { - // The task may have already parsed an exception. - translatedException = task.materializeException(getLastRequestObject(opContext), opContext); - task.getResult().setException(translatedException); - - // throw on non retryable status codes: 501, 505, blob type - // mismatch - if (task.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_IMPLEMENTED - || task.getResult().getStatusCode() == HttpURLConnection.HTTP_VERSION - || translatedException.getErrorCode().equals(StorageErrorCodeStrings.INVALID_BLOB_TYPE)) { - throw translatedException; - } - } - } - catch (final TimeoutException e) { - // Retryable - translatedException = StorageException - .translateException(getLastRequestObject(opContext), e, opContext); - task.getResult().setException(translatedException); - } - catch (final SocketTimeoutException e) { - // Retryable - translatedException = new StorageException(StorageErrorCodeStrings.OPERATION_TIMED_OUT, - "The operation did not complete in the specified time.", -1, null, e); - task.getResult().setException(translatedException); - } - catch (final IOException e) { - // Retryable - translatedException = StorageException - .translateException(getLastRequestObject(opContext), e, opContext); - task.getResult().setException(translatedException); - } - catch (final XMLStreamException e) { - // Non Retryable except when the inner exception is actually an IOException - - // Only in the case of xml exceptions that are due to connection issues. - if (e.getCause() instanceof SocketException) { - translatedException = new StorageException(StorageErrorCode.SERVICE_INTERNAL_ERROR.toString(), - "An unknown failure occurred : ".concat(e.getCause().getMessage()), - HttpURLConnection.HTTP_INTERNAL_ERROR, null, e); - } - else { - translatedException = StorageException.translateException(getLastRequestObject(opContext), e, - opContext); - } - - task.getResult().setException(translatedException); - if (!(e.getCause() instanceof IOException) && !(e.getCause() instanceof SocketException)) { - throw translatedException; - } - } - catch (final InvalidKeyException e) { - // Non Retryable, just throw - translatedException = StorageException - .translateException(getLastRequestObject(opContext), e, opContext); - task.getResult().setException(translatedException); - throw translatedException; - } - catch (final URISyntaxException e) { - // Non Retryable, just throw - translatedException = StorageException - .translateException(getLastRequestObject(opContext), e, opContext); - task.getResult().setException(translatedException); - throw translatedException; - } - catch (final TableServiceException e) { - task.getResult().setStatusCode(e.getHttpStatusCode()); - task.getResult().setStatusMessage(e.getMessage()); - task.getResult().setException(e); - if (!e.isRetryable()) { - throw e; - } - else { - translatedException = e; - } - } - catch (final StorageException e) { - // Non Retryable, just throw - // do not translate StorageException - task.getResult().setException(e); - throw e; - } - catch (final Exception e) { - // Non Retryable, just throw - translatedException = StorageException - .translateException(getLastRequestObject(opContext), e, opContext); - task.getResult().setException(translatedException); - throw translatedException; - } - - // Evaluate Retry Policy - retryRes = policy.shouldRetry(currentRetryCount, task.getResult().getStatusCode(), task.getResult() - .getException(), opContext); - if (!retryRes.isShouldRetry()) { - throw translatedException; - } - else { - retryRes.doSleep(); - currentRetryCount++; - } - } - } - - /** - * Gets the input stream from the request - * - * @param request - * the request to process - * @param opContext - * an object used to track the execution of the operation - * @param currResult - * A {@link RequestResult} object that represents the current request result. - * @return the input stream from the request - * @throws IOException - * if there is an error making the connection - */ - public static InputStream getInputStream(final HttpURLConnection request, final OperationContext opContext, - final RequestResult currResult) throws IOException { - - opContext.setCurrentRequestObject(request); - currResult.setStartDate(new Date()); - - if (opContext.getSendingRequestEventHandler().hasListeners()) { - opContext.getSendingRequestEventHandler() - .fireEvent(new SendingRequestEvent(opContext, request, currResult)); - } - - try { - return request.getInputStream(); - } - catch (final IOException ex) { - getResponseCode(currResult, request, opContext); - throw ex; - } - } - - /** - * Gets the last request object in a safe way, returns null if there was not last request result. - * - * @param opContext - * an object used to track the execution of the operation - * @return the last request object in a safe way, returns null if there was not last request result. - */ - private static HttpURLConnection getLastRequestObject(final OperationContext opContext) { - if (opContext == null || opContext.getCurrentRequestObject() == null) { - return null; - } - - return opContext.getCurrentRequestObject(); - } - - /** - * Gets the response code form the request - * - * @param currResult - * the current RequestResult object - * @param request - * the request to process - * @param opContext - * an object used to track the execution of the operation - * @throws IOException - * if there is an error making the connection - */ - public static void getResponseCode(final RequestResult currResult, final HttpURLConnection request, - final OperationContext opContext) throws IOException { - // Send the request - currResult.setStatusCode(request.getResponseCode()); - currResult.setStatusMessage(request.getResponseMessage()); - - currResult.setStopDate(new Date()); - currResult.setServiceRequestID(BaseResponse.getRequestId(request)); - currResult.setEtag(BaseResponse.getEtag(request)); - currResult.setRequestDate(BaseResponse.getDate(request)); - currResult.setContentMD5(BaseResponse.getContentMD5(request)); - - if (opContext.getResponseReceivedEventHandler().hasListeners()) { - opContext.getResponseReceivedEventHandler().fireEvent( - new ResponseReceivedEvent(opContext, request, currResult)); - } - } - - /** - * Gets the response for a given HttpURLConnection, populates the opContext with the result, and fires an event if - * it has listeners. - * - * @param request - * the request to process - * @param opContext - * an object used to track the execution of the operation - * @param currResult - * A {@link RequestResult} object that represents the current request result. - * @throws IOException - * if there is an error making the connection - */ - public static void processRequest(final HttpURLConnection request, final OperationContext opContext, - final RequestResult currResult) throws IOException { - - opContext.setCurrentRequestObject(request); - currResult.setStartDate(new Date()); - - if (opContext.getSendingRequestEventHandler().hasListeners()) { - opContext.getSendingRequestEventHandler() - .fireEvent(new SendingRequestEvent(opContext, request, currResult)); - } - - // Send the request - currResult.setStatusCode(request.getResponseCode()); - currResult.setStatusMessage(request.getResponseMessage()); - - currResult.setStopDate(new Date()); - currResult.setServiceRequestID(BaseResponse.getRequestId(request)); - currResult.setEtag(BaseResponse.getEtag(request)); - currResult.setRequestDate(BaseResponse.getDate(request)); - currResult.setContentMD5(BaseResponse.getContentMD5(request)); - - if (opContext.getResponseReceivedEventHandler().hasListeners()) { - opContext.getResponseReceivedEventHandler().fireEvent( - new ResponseReceivedEvent(opContext, request, currResult)); - } - } - - /** - * Private default Ctor for Utility Class - */ - private ExecutionEngine() { - // private ctor - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LazySegmentedIterable.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LazySegmentedIterable.java deleted file mode 100644 index 02d2c76e3f09a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LazySegmentedIterable.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.util.Iterator; - -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.RetryPolicyFactory; - -/** - * RESERVED FOR INTERNAL USE. Provides a lazy iterator which will retrieve the next segment of a result as the iterator - * is consumed - * - * @param - * The service client type - * @param - * The type of the parent object, i.e. CloudBlobClient for ListContainers etc. - * @param - * The type of the objects the resulting iterable objects - */ -public final class LazySegmentedIterable implements Iterable { - /** - * Holds the service client associated with the operations. - */ - private final CLIENT_TYPE client; - - /** - * Holds a reference to the parent object, i.e. CloudBlobContainer for list blobs. - */ - private final PARENT_TYPE parentObject; - - /** - * Holds the reference to the RetryPolicyFactory object. - */ - private final RetryPolicyFactory policyFactory; - - /** - * Holds the SegmentedStorageOperation which is used to retrieve the next segment of results. - */ - private final SegmentedStorageOperation> segmentGenerator; - - /** - * Holds an object used to track the execution of the operation - */ - private final OperationContext opContext; - - public LazySegmentedIterable( - final SegmentedStorageOperation> segmentGenerator, - final CLIENT_TYPE client, final PARENT_TYPE parent, final RetryPolicyFactory policyFactory, - final OperationContext opContext) { - this.segmentGenerator = segmentGenerator; - this.parentObject = parent; - this.opContext = opContext; - this.policyFactory = policyFactory; - this.client = client; - } - - @Override - public Iterator iterator() { - return new LazySegmentedIterator(this.segmentGenerator, this.client, - this.parentObject, this.policyFactory, this.opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LazySegmentedIterator.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LazySegmentedIterator.java deleted file mode 100644 index f43f0a41b8d52..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LazySegmentedIterator.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.RetryPolicyFactory; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * RESERVED FOR INTERNAL USE. Provides a lazy iterator which will retrieve the next segment of a result as the iterator - * is consumed - * - * @param - * The service client type - * @param - * The type of the parent object, i.e. CloudBlobClient for ListContainers etc. - * @param - * The type of the objects the resulting iterable objects - */ -public final class LazySegmentedIterator implements Iterator { - - /** - * Holds the current segment of results. - */ - private ResultSegment currentSegment; - - /** - * Holds the iterator for the current Segment. - */ - private Iterator currentSegmentIterator; - - /** - * Holds the service client associated with the operations. - */ - private final CLIENT_TYPE client; - - /** - * Holds a reference to the parent object, i.e. CloudBlobContainer for list blobs. - */ - private final PARENT_TYPE parentObject; - - /** - * Holds the reference to the RetryPolicyFactory object. - */ - private final RetryPolicyFactory policyFactory; - - /** - * Holds the SegmentedStorageOperation which is used to retrieve the next segment of results. - */ - private final SegmentedStorageOperation> segmentGenerator; - - /** - * Holds an object used to track the execution of the operation - */ - private final OperationContext opContext; - - /** - * Initializes the LazySegmentedIterator. - * - * @param segmentGenerator - * a SegmentedStorageOperation to execute in order to retrieve the next segment of the result. - * @param client - * the service client associated with the request - * @param parent - * the parent object - * @param policyFactory - * the factory used to generate a new retry policy instance - * @param opContext - * an object used to track the execution of the operation - */ - public LazySegmentedIterator( - final SegmentedStorageOperation> segmentGenerator, - final CLIENT_TYPE client, final PARENT_TYPE parent, final RetryPolicyFactory policyFactory, - final OperationContext opContext) { - this.segmentGenerator = segmentGenerator; - this.parentObject = parent; - this.opContext = opContext; - this.policyFactory = policyFactory; - this.client = client; - } - - /** - * Indicates if the iterator has another element. - */ - @Override - @DoesServiceRequest - public boolean hasNext() { - while (this.currentSegment == null - || (!this.currentSegmentIterator.hasNext() && this.currentSegment != null && this.currentSegment - .getHasMoreResults())) { - try { - this.currentSegment = ExecutionEngine.executeWithRetry(this.client, this.parentObject, - this.segmentGenerator, this.policyFactory, this.opContext); - } - catch (final StorageException e) { - final NoSuchElementException ex = new NoSuchElementException( - "An error occurred while enumerating the result, check the original exception for details."); - ex.initCause(e); - throw ex; - } - this.currentSegmentIterator = this.currentSegment.getResults().iterator(); - - if (!this.currentSegmentIterator.hasNext() && !this.currentSegment.getHasMoreResults()) { - return false; - } - } - - return this.currentSegmentIterator.hasNext(); - } - - /** - * Returns the next element. - */ - @Override - public ENTITY_TYPE next() { - return this.currentSegmentIterator.next(); - } - - /** - * Removes an element, not supported - */ - @Override - public void remove() { - // read only, no-op - throw new UnsupportedOperationException(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LeaseAction.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LeaseAction.java deleted file mode 100644 index 91a1f7b95c08d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/LeaseAction.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import com.microsoft.windowsazure.services.core.storage.Constants; - -/** - * RESERVED FOR INTERNAL USE. Describes actions that can be performed on a lease. - */ -public enum LeaseAction { - - /** - * Acquire the lease. - */ - ACQUIRE, - - /** - * Renew the lease. - */ - RENEW, - - /** - * Release the lease. - */ - RELEASE, - - /** - * Break the lease. - */ - BREAK, - - /** - * Change the lease. - */ - CHANGE; - - @Override - public String toString() { - switch (this) { - case ACQUIRE: - return "Acquire"; - case RENEW: - return "Renew"; - case RELEASE: - return "Release"; - case BREAK: - return "Break"; - case CHANGE: - return "Change"; - default: - // Wont Happen, all possible values covered above. - return Constants.EMPTY_STRING; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/ListingContext.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/ListingContext.java deleted file mode 100644 index 6e28a1cddb5e6..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/ListingContext.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -/** - * RESERVED FOR INTERNAL USE. A class which holds the current context of a listing - */ -public class ListingContext { - - /** - * The Marker value. - */ - private String marker; - - /** - * The MaxResults value. - */ - private Integer maxResults; - - /** - * The Prefix value. - */ - private String prefix; - - /** - * Initializes a new instance of the ListingContext class. - * - * @param prefix - * the listing prefix to use - * @param maxResults - * the maximum number of results to retrieve. - */ - public ListingContext(final String prefix, final Integer maxResults) { - this.setPrefix(prefix); - this.setMaxResults(maxResults); - this.setMarker(null); - } - - /** - * @return the marker - */ - public final String getMarker() { - return this.marker; - } - - /** - * @return the maxResults - */ - public final Integer getMaxResults() { - return this.maxResults; - } - - /** - * @return the prefix - */ - public final String getPrefix() { - return this.prefix; - } - - /** - * @param marker - * the marker to set - */ - public final void setMarker(final String marker) { - this.marker = marker; - } - - /** - * @param maxResults - * the maxResults to set - */ - protected final void setMaxResults(final Integer maxResults) { - this.maxResults = maxResults; - } - - /** - * @param prefix - * the prefix to set - */ - public final void setPrefix(final String prefix) { - this.prefix = prefix; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/SegmentedStorageOperation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/SegmentedStorageOperation.java deleted file mode 100644 index 349428f12a723..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/SegmentedStorageOperation.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import com.microsoft.windowsazure.services.core.storage.RequestOptions; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; - -/** - * RESERVED FOR INTERNAL USE. A base class which encapsulate the execution of a given segmented storage operation. - * - * @param - * The service client type - * @param

- * The type of the parent object, i.e. CloudBlobContainer for downloadAttributes etc. - * @param - * The type of the expected result - */ -public abstract class SegmentedStorageOperation extends StorageOperation { - - /** - * Holds the ResultContinuation between executions. - */ - private ResultContinuation token; - - /** - * Initializes a new instance of the SegmentedStorageOperation class. - * - * @param options - * the RequestOptions to use - */ - public SegmentedStorageOperation(final RequestOptions options) { - super(options); - } - - /** - * Initializes a new instance of the SegmentedStorageOperation class. - * - * @param options - * the RequestOptions to use - * @param token - * the ResultContinuation to use - */ - public SegmentedStorageOperation(final RequestOptions options, final ResultContinuation token) { - super(options); - this.setToken(token); - } - - /** - * @return the token. - */ - protected final ResultContinuation getToken() { - return this.token; - } - - /** - * @param token - * the token to set. - */ - protected final void setToken(final ResultContinuation token) { - this.token = token; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/StorageErrorResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/StorageErrorResponse.java deleted file mode 100644 index 6a1cda8d4c223..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/StorageErrorResponse.java +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.io.InputStream; -import java.io.Reader; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageExtendedErrorInformation; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/*** - * RESERVED FOR INTERNAL USE. A class to help parse the Error details from an input stream. - */ -public final class StorageErrorResponse { - /** - * Holds the StorageExtendedErrorInformation to return. - */ - private final StorageExtendedErrorInformation errorInfo; - - /** - * Holds a flag indicating if the response has been parsed or not. - */ - private boolean isParsed; - - /** - * Holds a reference to the xml reader to parse error details from. - */ - private XMLStreamReader xmlr = null; - - // true to support table. - private boolean useLowerCaseElementNames = false; - - /** - * Initializes the StorageErrorResponse object. - * - * @param stream - * the input stream to read error details from. - * @throws XMLStreamException - */ - public StorageErrorResponse(final InputStream stream) throws XMLStreamException { - this.xmlr = Utility.createXMLStreamReaderFromStream(stream); - this.errorInfo = new StorageExtendedErrorInformation(); - } - - /** - * Initializes the StorageErrorResponse object. - * - * @param reader - * the input stream to read error details from. - * @throws XMLStreamException - */ - public StorageErrorResponse(final Reader reader) throws XMLStreamException { - this.xmlr = Utility.createXMLStreamReaderFromReader(reader); - this.errorInfo = new StorageExtendedErrorInformation(); - // TODO fix me with more elegant table solution - this.useLowerCaseElementNames = true; - } - - /** - * Gets the Extended Error information from the response stream. - * - * @return the Extended Error information from the response stream - * @throws XMLStreamException - * if an xml exception occurs - */ - public StorageExtendedErrorInformation getExtendedErrorInformation() throws XMLStreamException { - if (!this.isParsed) { - this.parseResponse(); - } - - return this.errorInfo; - } - - /** - * Parses the Error Exception details from the response. - * - * @param xmlr - * the XMLStreamReader to read from - * @throws XMLStreamException - * if an xml exception occurs - */ - private void parseErrorException(final XMLStreamReader xmlr) throws XMLStreamException { - int eventType = xmlr.getEventType(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.ERROR_EXCEPTION); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.CHARACTERS) { - continue; - } - - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.ERROR_EXCEPTION_MESSAGE)) { - final String errorExceptionMessage = Utility.readElementFromXMLReader(xmlr, - Constants.ERROR_EXCEPTION_MESSAGE); - this.errorInfo.getAdditionalDetails().put(Constants.ERROR_EXCEPTION_MESSAGE, - new String[] { errorExceptionMessage }); - - } - else if (eventType == XMLStreamConstants.START_ELEMENT - && name.equals(Constants.ERROR_EXCEPTION_STACK_TRACE)) { - final String errorExceptionStack = Utility.readElementFromXMLReader(xmlr, - Constants.ERROR_EXCEPTION_STACK_TRACE); - this.errorInfo.getAdditionalDetails().put(Constants.ERROR_EXCEPTION_STACK_TRACE, - new String[] { errorExceptionStack }); - } - else if (eventType == XMLStreamConstants.END_ELEMENT) { - break; - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.ERROR_EXCEPTION); - } - - /** - * Parses the extended error information from the response stream. - * - * @throws XMLStreamException - * if an xml exception occurs - */ - private void parseResponse() throws XMLStreamException { - String tempParseString; - - // Start document - int eventType = this.xmlr.getEventType(); - this.xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // 1. get Error Root Header - eventType = this.xmlr.next(); - this.xmlr.require(XMLStreamConstants.START_ELEMENT, null, - this.useLowerCaseElementNames ? Constants.ERROR_ROOT_ELEMENT.toLowerCase() - : Constants.ERROR_ROOT_ELEMENT); - - while (this.xmlr.hasNext()) { - eventType = this.xmlr.next(); - if (eventType == XMLStreamConstants.CHARACTERS) { - continue; - } - - if (eventType == XMLStreamConstants.END_ELEMENT) { - break; - } - - String name = this.xmlr.getName().getLocalPart().toString(); - name = this.useLowerCaseElementNames ? name.toLowerCase() : name; - - if (eventType == XMLStreamConstants.START_ELEMENT) { - - if (name.equals(this.useLowerCaseElementNames ? Constants.ERROR_CODE.toLowerCase() - : Constants.ERROR_CODE)) { - this.errorInfo.setErrorCode(Utility.readElementFromXMLReader(this.xmlr, - this.useLowerCaseElementNames ? Constants.ERROR_CODE.toLowerCase() : Constants.ERROR_CODE)); - } - else if (name.equals(this.useLowerCaseElementNames ? Constants.ERROR_MESSAGE.toLowerCase() - : Constants.ERROR_MESSAGE)) { - this.errorInfo.setErrorMessage(Utility.readElementFromXMLReader(this.xmlr, - this.useLowerCaseElementNames ? Constants.ERROR_MESSAGE.toLowerCase() - : Constants.ERROR_MESSAGE)); - } - else if (name.equals(this.useLowerCaseElementNames ? Constants.ERROR_EXCEPTION.toLowerCase() - : Constants.ERROR_EXCEPTION)) { - // get error exception - this.parseErrorException(this.xmlr); - this.xmlr.require(XMLStreamConstants.END_ELEMENT, null, - this.useLowerCaseElementNames ? Constants.ERROR_EXCEPTION.toLowerCase() - : Constants.ERROR_EXCEPTION); - } - else { - // get additional details - tempParseString = Utility.readElementFromXMLReader(this.xmlr, name); - - this.errorInfo.getAdditionalDetails().put(name, new String[] { tempParseString }); - - this.xmlr.require(XMLStreamConstants.END_ELEMENT, null, null); - } - } - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/StorageOperation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/StorageOperation.java deleted file mode 100644 index 47ae9204e384c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/StorageOperation.java +++ /dev/null @@ -1,220 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.net.HttpURLConnection; -import java.security.InvalidKeyException; - -import com.microsoft.windowsazure.services.core.storage.AuthenticationScheme; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.RequestOptions; -import com.microsoft.windowsazure.services.core.storage.RequestResult; -import com.microsoft.windowsazure.services.core.storage.ServiceClient; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * RESERVED FOR INTERNAL USE. A base class which encapsulate the execution of a given storage operation. - * - * @param - * The service client type - * @param

- * The type of the parent object, i.e. CloudBlobContainer for downloadAttributes etc. - * @param - * The type of the expected result - */ -public abstract class StorageOperation { - - /** - * Holds a reference to a realized exception which occurred during execution. - */ - private StorageException exceptionReference; - - /** - * A flag to indicate a failure which did not result in an exception, i.e a 400 class status code. - */ - private boolean nonExceptionedRetryableFailure; - - /** - * The RequestOptions to use for the request. - */ - private RequestOptions requestOptions; - - /** - * Holds the result for the operation. - */ - private RequestResult result; - - /** - * Holds the url connection for the operation. - */ - private HttpURLConnection connection; - - /** - * Default Ctor. - */ - protected StorageOperation() { - // no op - } - - /** - * Initializes a new instance of the StorageOperation class. - * - * @param options - * the RequestOptions to use - */ - public StorageOperation(final RequestOptions options) { - this.setRequestOptions(options); - } - - /** - * Executes the operation. - * - * @param client - * a reference to the service client associated with the object being operated against - * @param parentObject - * a reference to the parent object of the operation, (i.e. CloudBlobContainer for Create) - * @param opContext - * an object used to track the execution of the operation - * @return the result from the operation - * @throws Exception - * an error which occurred during execution - */ - public abstract R execute(C client, P parentObject, OperationContext opContext) throws Exception; - - /** - * @return the exception - */ - public final StorageException getException() { - return this.exceptionReference; - } - - /** - * @return the requestOptions - */ - public final RequestOptions getRequestOptions() { - return this.requestOptions; - } - - /** - * @return the result - */ - public final RequestResult getResult() { - return this.result; - } - - /** - * @return the URL connection - */ - public final HttpURLConnection getConnection() { - return this.connection; - } - - /** - * Resets the operation status flags between operations. - */ - protected final void initialize(OperationContext opContext) { - RequestResult currResult = new RequestResult(); - this.setResult(currResult); - opContext.appendRequestResult(currResult); - - this.setException(null); - this.setNonExceptionedRetryableFailure(false); - } - - /** - * @return the nonExceptionedRetryableFailure - */ - public final boolean isNonExceptionedRetryableFailure() { - return this.nonExceptionedRetryableFailure; - } - - /** - * Returns either the held exception from the operation if it is set, otherwise the translated exception. - * - * @param request - * the reference to the HttpURLConnection for the operation. - * @param opContext - * an object used to track the execution of the operation - * @return the exception to throw. - */ - protected final StorageException materializeException(final HttpURLConnection request, - final OperationContext opContext) { - if (this.getException() != null) { - return this.getException(); - } - - return StorageException.translateException(request, null, opContext); - } - - public final void signRequest(ServiceClient client, HttpURLConnection request, long contentLength, - OperationContext context) throws InvalidKeyException, StorageException { - if (client.getAuthenticationScheme() == AuthenticationScheme.SHAREDKEYFULL) { - client.getCredentials().signBlobAndQueueRequest(request, contentLength, context); - } - else { - client.getCredentials().signBlobAndQueueRequestLite(request, contentLength, context); - } - } - - public final void signTableRequest(ServiceClient client, HttpURLConnection request, long contentLength, - OperationContext context) throws InvalidKeyException, StorageException { - if (client.getAuthenticationScheme() == AuthenticationScheme.SHAREDKEYFULL) { - client.getCredentials().signTableRequest(request, contentLength, context); - } - else { - client.getCredentials().signTableRequestLite(request, contentLength, context); - } - } - - /** - * @param exceptionReference - * the exception to set - */ - protected final void setException(final StorageException exceptionReference) { - this.exceptionReference = exceptionReference; - } - - /** - * @param nonExceptionedRetryableFailure - * the nonExceptionedRetryableFailure to set - */ - public final void setNonExceptionedRetryableFailure(final boolean nonExceptionedRetryableFailure) { - this.nonExceptionedRetryableFailure = nonExceptionedRetryableFailure; - } - - /** - * @param requestOptions - * the requestOptions to set - */ - protected final void setRequestOptions(final RequestOptions requestOptions) { - this.requestOptions = requestOptions; - } - - /** - * @param result - * the result to set - */ - public final void setResult(final RequestResult result) { - this.result = result; - } - - /** - * @param connection - * the connection to set - */ - public final void setConnection(final HttpURLConnection connection) { - this.connection = connection; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/TableFullCanonicalizer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/TableFullCanonicalizer.java deleted file mode 100644 index c3088315fb731..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/TableFullCanonicalizer.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.net.HttpURLConnection; -import java.security.InvalidParameterException; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. Provides an implementation of the Canonicalizer class for requests against Table - * Service under the Shared Key authentication scheme. - */ -final class TableFullCanonicalizer extends Canonicalizer { - - /** - * Constructs a canonicalized string for signing a request. - * - * @param conn - * the HttpURLConnection to canonicalize - * @param accountName - * the account name associated with the request - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param opContext - * the OperationContext for the given request - * @return a canonicalized string. - * @throws StorageException - */ - @Override - protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength, - final OperationContext opContext) throws StorageException { - - if (contentLength < -1) { - throw new InvalidParameterException("ContentLength must be set to -1 or non-negative Long value"); - } - - return canonicalizeTableHttpRequest(conn.getURL(), accountName, conn.getRequestMethod(), - Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_TYPE), contentLength, null, - conn, opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/TableLiteCanonicalizer.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/TableLiteCanonicalizer.java deleted file mode 100644 index 44211bf769467..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/storage/utils/implementation/TableLiteCanonicalizer.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - */ -package com.microsoft.windowsazure.services.core.storage.utils.implementation; - -import java.net.HttpURLConnection; -import java.security.InvalidParameterException; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. Provides an implementation of the Canonicalizer class for requests against Table Service - * under the Shared Key Lite authentication scheme. - */ -class TableLiteCanonicalizer extends Canonicalizer { - - /** - * The expected length for the canonicalized string when SharedKeyLite is used to sign table requests. - */ - private static final int ExpectedTableLiteCanonicalizedStringLength = 150; - - /** - * Constructs a canonicalized string for signing a request. - * - * @param conn - * the HttpURLConnection to canonicalize - * @param accountName - * the account name associated with the request - * @param contentLength - * the length of the content written to the outputstream in bytes, -1 if unknown - * @param opContext - * the OperationContext for the given request - * @return a canonicalized string. - * @throws StorageException - */ - @Override - protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength, - final OperationContext opContext) throws StorageException { - if (contentLength < -1) { - throw new InvalidParameterException("ContentLength must be set to -1 or positive Long value"); - } - - final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE); - if (Utility.isNullOrEmpty(dateString)) { - throw new IllegalArgumentException( - "Canonicalization did not find a non empty x-ms-date header in the request. Please use a request with a valid x-ms-date header in RFC 123 format."); - } - final StringBuilder canonicalizedString = new StringBuilder(ExpectedTableLiteCanonicalizedStringLength); - canonicalizedString.append(dateString); - appendCanonicalizedElement(canonicalizedString, getCanonicalizedResourceLite(conn.getURL(), accountName)); - - return canonicalizedString.toString(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/Exports.java deleted file mode 100644 index 179dafb31dccb..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/Exports.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.utils; - -import com.microsoft.windowsazure.services.core.Builder; - -public class Exports implements Builder.Exports { - public void register(Builder.Registry registry) { - registry.add(DateFactory.class, DefaultDateFactory.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ParsedConnectionString.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ParsedConnectionString.java deleted file mode 100644 index 8be49de1b5383..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ParsedConnectionString.java +++ /dev/null @@ -1,329 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.core.utils; - -import com.microsoft.windowsazure.services.core.utils.pipeline.ConnectionStringField; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Base class representing an Azure connection string. This - * provides parsing logic to split the string up into - * the various fields. - */ -public abstract class ParsedConnectionString { - private String connectionString; - private int currentIndex; - private String currentKey; - private String currentValue; - - public ParsedConnectionString(String connectionString) throws ConnectionStringSyntaxException { - // Forcing a separator at the end makes implementation below - // easier - don't have to check for end of string everywhere - this.connectionString = connectionString + ';'; - this.currentIndex = 0; - - matchConnectionString(); - } - - private char currentChar() { - return connectionString.charAt(currentIndex); - } - - private void consumeChar() { - currentIndex++; - } - - private boolean charsLeft() { - return currentIndex < connectionString.length(); - } - - // - // PEG Grammar for a connection string: - // - // ConnectionString <- Attribute (Separator+ Attribute)* Separator* END - // Attribute <- Spacing (KeyValuePair / &Separator) - // KeyValuePair <- Key Equals Spacing Value - // Key <- QuotedKey / RawKey - // QuotedKey <- DoubleQuote (!DoubleQuote .)* DoubleQuote / SingleQuote (!SingleQuote .)* SingleQuote - // RawKey <- (!Equals .)+ - // Equals <- Spacing '=' - // Value <- QuotedValue / RawValue - // QuotedValue <- DoubleQuote (!DoubleQuote .)* DoubleQuote / SingleQuote (!SingleQuote .*) SingleQuote - // RawValue <- (!Separator .)* - // Separator <- Spacing ';' - // Spacing <- WS* - // WS <- ' ' / '\t' - // END <- !. - // - - private boolean matchConnectionString() throws ConnectionStringSyntaxException { - if (!matchAttribute()) { - throw new ConnectionStringSyntaxException(String.format( - "Could not parse connection string '%1$s'", connectionString)); - } - - boolean moreAttributes = true; - int bookmark; - - while (moreAttributes) { - bookmark = currentIndex; - boolean separators = false; - while (matchSeparator()) { - separators = true; - } - moreAttributes = separators && matchAttribute(); - if (!moreAttributes) { - currentIndex = bookmark; - } - } - - while (matchSeparator()) { - } - - if (!matchEND()) { - throw new ConnectionStringSyntaxException(String.format( - "Expected end of connection string '%1$s', did not get it", connectionString)); - } - - return true; - } - - private boolean matchAttribute() throws ConnectionStringSyntaxException { - matchSpacing(); - if (matchKeyValuePair()) { - return true; - } - int bookmark = currentIndex; - boolean matchedSeparator = matchSeparator(); - currentIndex = bookmark; - return matchedSeparator; - } - - private boolean matchKeyValuePair() throws ConnectionStringSyntaxException { - if (!charsLeft()) { - return false; - } - if (!matchKey()) { - throw new ConnectionStringSyntaxException(String.format( - "Expected key in connection string '%1$s' at position %2$d but did not find one", - connectionString, currentIndex)); - } - if (!matchEquals()) { - throw new ConnectionStringSyntaxException(String.format( - "Expected '=' character in connection string '%1$s' after key near position %2$d", - connectionString, currentIndex)); - } - if (!matchValue()) { - throw new ConnectionStringSyntaxException(String.format( - "Expected value in connection string '%1$s' for key '%3$s' at position %2$d but did not find one", - connectionString, currentIndex, currentKey)); - } - - saveValue(currentKey, currentValue); - return true; - } - - private boolean matchKey() throws ConnectionStringSyntaxException { - return matchQuotedKey() || matchRawKey(); - } - - private boolean matchQuotedKey() throws ConnectionStringSyntaxException { - if (!charsLeft()) { - return false; - } - String value = ""; - char quote = currentChar(); - int bookmark = currentIndex; - - if (quote == '"' || quote == '\'') { - consumeChar(); - while (charsLeft() && currentChar() != quote) { - value += currentChar(); - consumeChar(); - } - if (!charsLeft()) { - throw new ConnectionStringSyntaxException(String.format( - "Unterminated quoted value in string '%1$s', starting at character %2$d", connectionString, bookmark)); - } - consumeChar(); - currentKey = value; - return true; - } else { - return false; - } - } - - private boolean matchRawKey() throws ConnectionStringSyntaxException { - if (!charsLeft()) { - return false; - } - - String value = ""; - int bookmark = currentIndex; - - while (charsLeft() && !matchEquals()) { - value += currentChar(); - consumeChar(); - bookmark = currentIndex; - } - - if (!charsLeft()) { - throw new ConnectionStringSyntaxException(String.format( - "Expected '=' in connection string '%1$s', key started at index %2$d", connectionString, bookmark - )); - } - - currentIndex = bookmark; - currentKey = value; - return true; - } - - private boolean matchEquals() { - int bookmark = currentIndex; - matchSpacing(); - if (charsLeft() && currentChar() == '=') { - consumeChar(); - return true; - } - currentIndex = bookmark; - return false; - } - - private boolean matchValue() throws ConnectionStringSyntaxException { - return matchQuotedValue() || matchRawValue(); - } - - private boolean matchQuotedValue() throws ConnectionStringSyntaxException { - String value = ""; - char quote = currentChar(); - int bookmark = currentIndex; - - if (quote == '"' || quote == '\'') { - consumeChar(); - while (charsLeft() && currentChar() != quote) { - value += currentChar(); - consumeChar(); - } - if (!charsLeft()) { - throw new ConnectionStringSyntaxException(String.format( - "Unterminated quoted value in string '%1$s', starting at character %2$d", connectionString, bookmark)); - } - consumeChar(); - currentValue = value; - return true; - } else { - return false; - } - } - - private boolean matchRawValue() { - String value = ""; - int bookmark = currentIndex; - - while (charsLeft() && !matchSeparator()) { - value += currentChar(); - consumeChar(); - bookmark = currentIndex; - } - currentIndex = bookmark; - currentValue = value; - return true; - } - - private boolean matchSeparator() { - int bookmark = currentIndex; - matchSpacing(); - if (charsLeft() && currentChar() == ';') { - consumeChar(); - return true; - } - currentIndex = bookmark; - return false; - } - - private boolean matchSpacing() { - while (matchWS()) { - } - return true; - } - - private boolean matchWS() { - if (charsLeft() && (currentChar() == ' ' || currentChar() == '\t')) { - consumeChar(); - return true; - } - return false; - } - - private boolean matchEND() { - return !(currentIndex < connectionString.length()); - } - - /** - * Store the value for the given key. - * - * Default implementation looks for a property setter with the - * matching name or the @ConnectionStringField annotation on the - * setter method to set the field. You can override this method - * for other behavior. - * - * @param key Key to store value under. If keys repeat, older values are overwritten. - * @param value value to associate with the key. - * - * @throws ConnectionStringSyntaxException - */ - protected void saveValue(String key, String value) throws ConnectionStringSyntaxException { - Method setter; - try { - setter = findSetter(key); - setter.invoke(this, value); - } catch (NoSuchMethodException e) { - throw new ConnectionStringSyntaxException(String.format( - "The key '%1$s' is not valid for this connection string", key), e); - } catch (InvocationTargetException e) { - throw new ConnectionStringSyntaxException(String.format( - "Could not invoke setter for key '%1$s'", key), e); - } catch (IllegalAccessException e) { - throw new ConnectionStringSyntaxException(String.format( - "Setter for key '%1$s' is not accessible in class %2$s", key, getClass().getName()), e); - } - } - - private Method findSetter(String key) throws NoSuchMethodException { - Class thisClass = getClass(); - for (Method m : thisClass.getDeclaredMethods()) { - if (methodMatches(m, key)) { - return m; - } - } - throw new NoSuchMethodException(); - } - - private boolean methodMatches(Method method, String key) { - return matchesViaAnnotation(method, key) || matchesByName(method, key); - } - - private boolean matchesViaAnnotation(Method method, String key) { - ConnectionStringField annotation = method.getAnnotation(ConnectionStringField.class); - return annotation != null && annotation.name().toLowerCase().equals(key.toLowerCase()); - } - - private boolean matchesByName(Method method, String key) { - return method.getName().toLowerCase().equals("set" + key.toLowerCase()); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ServiceExceptionFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ServiceExceptionFactory.java deleted file mode 100644 index 2d7a029c30c71..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/ServiceExceptionFactory.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.utils; - -import java.net.SocketTimeoutException; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceTimeoutException; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.ClientResponse.Status; -import com.sun.jersey.api.client.UniformInterfaceException; - -public class ServiceExceptionFactory { - - public static ServiceException process(String serviceName, ServiceException exception) { - Throwable cause = exception.getCause(); - - for (Throwable scan = cause; scan != null; scan = scan.getCause()) { - Class scanClass = scan.getClass(); - if (ServiceException.class.isAssignableFrom(scanClass)) { - return populate(exception, serviceName, (ServiceException) scan); - } - else if (UniformInterfaceException.class.isAssignableFrom(scanClass)) { - return populate(exception, serviceName, (UniformInterfaceException) scan); - } - else if (SocketTimeoutException.class.isAssignableFrom(scanClass)) { - return populate(exception, serviceName, (SocketTimeoutException) scan); - } - } - - exception.setServiceName(serviceName); - - return exception; - } - - static ServiceException populate(ServiceException exception, String serviceName, UniformInterfaceException cause) { - exception.setServiceName(serviceName); - - if (cause != null) { - ClientResponse response = cause.getResponse(); - if (response != null) { - // Set status - Status status = response.getClientResponseStatus(); - if (status == null) { - status = Status.fromStatusCode(response.getStatus()); - } - if (status == null) { - exception.setHttpStatusCode(response.getStatus()); - } - else { - exception.setHttpStatusCode(status.getStatusCode()); - exception.setHttpReasonPhrase(status.getReasonPhrase()); - } - - // Set raw response body - if (response.hasEntity()) { - try { - String body = response.getEntity(String.class); - exception.setRawResponseBody(body); - } - catch (Exception e) { - // Skip exceptions as getting the response body as a string is a best effort thing - } - } - } - } - return exception; - } - - static ServiceException populate(ServiceException exception, String serviceName, ServiceException cause) { - exception.setServiceName(cause.getServiceName()); - exception.setHttpStatusCode(cause.getHttpStatusCode()); - exception.setHttpReasonPhrase(cause.getHttpReasonPhrase()); - exception.setErrorCode(cause.getErrorCode()); - exception.setErrorMessage(cause.getErrorMessage()); - exception.setRawResponseBody(cause.getRawResponseBody()); - exception.setErrorValues(cause.getErrorValues()); - return exception; - } - - static ServiceException populate(ServiceException exception, String serviceName, SocketTimeoutException cause) { - ServiceTimeoutException newException = new ServiceTimeoutException(cause.getMessage(), cause); - newException.setServiceName(serviceName); - return newException; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ClientFilterAdapter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ClientFilterAdapter.java deleted file mode 100644 index 4af39301fccfd..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/ClientFilterAdapter.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.utils.pipeline; - -import java.io.InputStream; -import java.net.URI; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; - -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.ServiceFilter.Request; -import com.microsoft.windowsazure.services.core.ServiceFilter.Response; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.filter.ClientFilter; - -public class ClientFilterAdapter extends ClientFilter { - ServiceFilter filter; - - public ClientFilterAdapter(ServiceFilter filter) { - this.filter = filter; - } - - @Override - public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException { - - final ClientRequest cr = clientRequest; - try { - Response resp = filter.handle(new ServiceFilterRequest(clientRequest), new ServiceFilter.Next() { - public Response handle(Request request) { - return new ServiceFilterResponse(getNext().handle(cr)); - } - }); - - return ((ServiceFilterResponse) resp).clientResponse; - } - catch (Exception e) { - throw new ClientHandlerException(e); - } - } -} - -class ServiceFilterRequest implements ServiceFilter.Request { - ClientRequest clientRequest; - - public ServiceFilterRequest(ClientRequest clientRequest) { - this.clientRequest = clientRequest; - } - - public Map getProperties() { - return clientRequest.getProperties(); - } - - public void setProperties(Map properties) { - clientRequest.setProperties(properties); - } - - public URI getURI() { - return clientRequest.getURI(); - } - - public void setURI(URI uri) { - clientRequest.setURI(uri); - } - - public String getMethod() { - return clientRequest.getMethod(); - } - - public void setMethod(String method) { - clientRequest.setMethod(method); - } - - public Object getEntity() { - return clientRequest.getEntity(); - } - - public void setEntity(Object entity) { - clientRequest.setEntity(entity); - } - - public MultivaluedMap getHeaders() { - return clientRequest.getHeaders(); - } - -} - -class ServiceFilterResponse implements ServiceFilter.Response { - ClientResponse clientResponse; - - public ServiceFilterResponse(ClientResponse clientResponse) { - this.clientResponse = clientResponse; - } - - public Map getProperties() { - return clientResponse.getProperties(); - } - - public int getStatus() { - return clientResponse.getStatus(); - } - - public void setStatus(int status) { - clientResponse.setStatus(status); - } - - public MultivaluedMap getHeaders() { - return clientResponse.getHeaders(); - } - - public boolean hasEntity() { - return clientResponse.hasEntity(); - } - - public InputStream getEntityInputStream() { - return clientResponse.getEntityInputStream(); - } - - public void setEntityInputStream(InputStream entity) { - clientResponse.setEntityInputStream(entity); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/Exports.java deleted file mode 100644 index 9028aa8a1adcf..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/Exports.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.utils.pipeline; - -import static com.microsoft.windowsazure.services.core.utils.ExportUtils.*; - -import java.util.Map; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.Builder.Registry; -import com.microsoft.windowsazure.services.core.Configuration; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; - -public class Exports implements Builder.Exports { - - @Override - public void register(Registry registry) { - registry.add(new Builder.Factory() { - @Override - public ClientConfig create(String profile, Class service, Builder builder, - Map properties) { - ClientConfig clientConfig = new DefaultClientConfig(); - ClientConfigSettings settings = builder.build(profile, service, ClientConfigSettings.class, properties); - settings.applyConfig(clientConfig); - return clientConfig; - } - }); - - registry.add(new Builder.Factory() { - - @Override - public ClientConfigSettings create(String profile, Class service, Builder builder, - Map properties) { - Object connectTimeout = getPropertyIfExists(profile, properties, Configuration.PROPERTY_CONNECT_TIMEOUT); - Object readTimeout = getPropertyIfExists(profile, properties, Configuration.PROPERTY_READ_TIMEOUT); - - return new ClientConfigSettings(connectTimeout, readTimeout, getPropertyIfExists(profile, properties, - Configuration.PROPERTY_LOG_HTTP_REQUESTS) != null); - } - - }); - - registry.add(new Builder.Factory() { - @Override - public Client create(String profile, Class service, Builder builder, Map properties) { - ClientConfig clientConfig = builder.build(profile, service, ClientConfig.class, properties); - ClientConfigSettings settings = builder.build(profile, service, ClientConfigSettings.class, properties); - Client client = Client.create(clientConfig); - settings.applyConfig(client); - return client; - } - }); - - registry.add(new Builder.Factory() { - @Override - public HttpURLConnectionClient create(String profile, Class service, Builder builder, - Map properties) { - ClientConfig clientConfig = builder.build(profile, service, ClientConfig.class, properties); - ClientConfigSettings settings = builder.build(profile, service, ClientConfigSettings.class, properties); - HttpURLConnectionClient client = HttpURLConnectionClient.create(clientConfig); - settings.applyConfig(client); - return client; - } - }); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/HttpURLConnectionClientHandler.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/HttpURLConnectionClientHandler.java deleted file mode 100644 index 4cd755578a75d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/HttpURLConnectionClientHandler.java +++ /dev/null @@ -1,323 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.utils.pipeline; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MultivaluedMap; - -import com.microsoft.windowsazure.services.core.utils.CommaStringBuilder; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.CommittingOutputStream; -import com.sun.jersey.api.client.TerminatingClientHandler; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.core.header.InBoundHeaders; - -public class HttpURLConnectionClientHandler extends TerminatingClientHandler { - - private final int connectionTimeoutMillis; - private final int readTimeoutMillis; - - public HttpURLConnectionClientHandler(ClientConfig clientConfig) { - connectionTimeoutMillis = readTimeoutFromConfig(clientConfig, ClientConfig.PROPERTY_CONNECT_TIMEOUT); - readTimeoutMillis = readTimeoutFromConfig(clientConfig, ClientConfig.PROPERTY_READ_TIMEOUT); - } - - private static int readTimeoutFromConfig(ClientConfig config, String propertyName) { - Integer property = (Integer) config.getProperty(propertyName); - if (property != null) { - return property.intValue(); - } - throw new IllegalArgumentException(propertyName); - } - - /** - * Empty "no-op" listener if none registered - */ - private static final EntityStreamingListener EMPTY_STREAMING_LISTENER = new EntityStreamingListener() { - @Override - public void onBeforeStreamingEntity(ClientRequest clientRequest) { - } - }; - - /** - * OutputStream used for buffering entity body when "Content-Length" is not known in advance. - */ - private final class BufferingOutputStream extends OutputStream { - private final ByteArrayOutputStream outputStream; - private final HttpURLConnection urlConnection; - private final ClientRequest clientRequest; - private final EntityStreamingListener entityStreamingListener; - private boolean closed; - - private BufferingOutputStream(HttpURLConnection urlConnection, ClientRequest clientRequest, - EntityStreamingListener entityStreamingListener) { - this.outputStream = new ByteArrayOutputStream(); - this.urlConnection = urlConnection; - this.clientRequest = clientRequest; - this.entityStreamingListener = entityStreamingListener; - } - - @Override - public void close() throws IOException { - outputStream.close(); - - if (!closed) { - closed = true; - - // Give the listener a last change to modify headers now that the content length is known - setContentLengthHeader(clientRequest, outputStream.size()); - entityStreamingListener.onBeforeStreamingEntity(clientRequest); - - // Write headers, then entity to the http connection. - setURLConnectionHeaders(clientRequest.getHeaders(), urlConnection); - - // Since we buffered the entity and we know the content size, we might as well - // use the "fixed length" streaming mode of HttpURLConnection to stream - // the buffer directly. - urlConnection.setFixedLengthStreamingMode(outputStream.size()); - OutputStream httpOutputStream = urlConnection.getOutputStream(); - outputStream.writeTo(httpOutputStream); - httpOutputStream.flush(); - httpOutputStream.close(); - } - } - - @Override - public void flush() throws IOException { - outputStream.flush(); - } - - @Override - public void write(byte[] b, int off, int len) { - outputStream.write(b, off, len); - } - - @Override - public void write(byte[] b) throws IOException { - outputStream.write(b); - } - - @Override - public void write(int b) { - outputStream.write(b); - } - } - - /** - * OutputStream used for directly streaming entity to url connection stream. Headers are written just before sending - * the first bytes to the output stream. - */ - private final class StreamingOutputStream extends CommittingOutputStream { - private final HttpURLConnection urlConnection; - private final ClientRequest clientRequest; - - private StreamingOutputStream(HttpURLConnection urlConnection, ClientRequest clientRequest) { - this.urlConnection = urlConnection; - this.clientRequest = clientRequest; - } - - @Override - protected OutputStream getOutputStream() throws IOException { - return urlConnection.getOutputStream(); - } - - @Override - public void commit() throws IOException { - setURLConnectionHeaders(clientRequest.getHeaders(), urlConnection); - } - } - - /** - * Simple response implementation around an HttpURLConnection response - */ - private final class URLConnectionResponse extends ClientResponse { - private final String method; - private final HttpURLConnection urlConnection; - - URLConnectionResponse(int status, InBoundHeaders headers, InputStream entity, String method, - HttpURLConnection urlConnection) { - super(status, headers, entity, getMessageBodyWorkers()); - this.method = method; - this.urlConnection = urlConnection; - } - - @Override - public boolean hasEntity() { - if (method.equals("HEAD") || getEntityInputStream() == null) - return false; - - // Length "-1" means "unknown" - int length = urlConnection.getContentLength(); - return length > 0 || length == -1; - } - - @Override - public String toString() { - return urlConnection.getRequestMethod() + " " + urlConnection.getURL() + " returned a response status of " - + this.getStatus() + " " + this.getClientResponseStatus(); - } - } - - @Override - public ClientResponse handle(final ClientRequest ro) throws ClientHandlerException { - try { - return doHandle(ro); - } - catch (Exception e) { - throw new ClientHandlerException(e); - } - } - - private ClientResponse doHandle(final ClientRequest clientRequest) throws IOException, MalformedURLException, - ProtocolException { - final HttpURLConnection urlConnection = (HttpURLConnection) clientRequest.getURI().toURL().openConnection(); - urlConnection.setReadTimeout(readTimeoutMillis); - urlConnection.setConnectTimeout(connectionTimeoutMillis); - - final EntityStreamingListener entityStreamingListener = getEntityStreamingListener(clientRequest); - - urlConnection.setRequestMethod(clientRequest.getMethod()); - - // Write the request headers - setURLConnectionHeaders(clientRequest.getHeaders(), urlConnection); - - // Write the entity (if any) - Object entity = clientRequest.getEntity(); - - // If no entity and "PUT method, force an empty entity to force the underlying - // connection to set the "Content-Length" header to 0. - // This is needed because some web servers require a "Content-Length" field for - // all PUT method calls (unless chunked encoding is used). - if (entity == null && "PUT".equals(clientRequest.getMethod())) { - entity = new byte[0]; - clientRequest.setEntity(entity); - } - - // Send headers and entity on the wire - if (entity != null) { - urlConnection.setDoOutput(true); - - writeRequestEntity(clientRequest, new RequestEntityWriterListener() { - private boolean inStreamingMode; - - @Override - public void onRequestEntitySize(long size) { - if (size != -1 && size < Integer.MAX_VALUE) { - inStreamingMode = true; - setContentLengthHeader(clientRequest, (int) size); - entityStreamingListener.onBeforeStreamingEntity(clientRequest); - - urlConnection.setFixedLengthStreamingMode((int) size); - } - else { - Integer chunkedEncodingSize = (Integer) clientRequest.getProperties().get( - ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); - if (chunkedEncodingSize != null) { - inStreamingMode = true; - entityStreamingListener.onBeforeStreamingEntity(clientRequest); - - urlConnection.setChunkedStreamingMode(chunkedEncodingSize); - } - } - } - - @Override - public OutputStream onGetOutputStream() throws IOException { - if (inStreamingMode) - return new StreamingOutputStream(urlConnection, clientRequest); - else - return new BufferingOutputStream(urlConnection, clientRequest, entityStreamingListener); - } - }); - } - else { - entityStreamingListener.onBeforeStreamingEntity(clientRequest); - setURLConnectionHeaders(clientRequest.getHeaders(), urlConnection); - } - - // Return the in-bound response - return new URLConnectionResponse(urlConnection.getResponseCode(), getInBoundHeaders(urlConnection), - getInputStream(urlConnection), clientRequest.getMethod(), urlConnection); - } - - private EntityStreamingListener getEntityStreamingListener(final ClientRequest clientRequest) { - EntityStreamingListener result = (EntityStreamingListener) clientRequest.getProperties().get( - EntityStreamingListener.class.getName()); - - if (result != null) - return result; - - return EMPTY_STREAMING_LISTENER; - } - - private void setContentLengthHeader(ClientRequest clientRequest, int size) { - // Skip if already set - if (clientRequest.getHeaders().getFirst("Content-Length") != null) - return; - - // Skip if size is unknown - if (size < 0) - return; - - clientRequest.getHeaders().putSingle("Content-Length", size); - } - - private void setURLConnectionHeaders(MultivaluedMap headers, HttpURLConnection urlConnection) { - for (Map.Entry> e : headers.entrySet()) { - List vs = e.getValue(); - if (vs.size() == 1) { - urlConnection.setRequestProperty(e.getKey(), ClientRequest.getHeaderValue(vs.get(0))); - } - else { - CommaStringBuilder sb = new CommaStringBuilder(); - for (Object v : e.getValue()) { - sb.add(ClientRequest.getHeaderValue(v)); - } - urlConnection.setRequestProperty(e.getKey(), sb.toString()); - } - } - } - - private InBoundHeaders getInBoundHeaders(HttpURLConnection urlConnection) { - InBoundHeaders headers = new InBoundHeaders(); - for (Map.Entry> e : urlConnection.getHeaderFields().entrySet()) { - if (e.getKey() != null) - headers.put(e.getKey(), e.getValue()); - } - return headers; - } - - private InputStream getInputStream(HttpURLConnection urlConnection) throws IOException { - if (urlConnection.getResponseCode() < 300) { - return urlConnection.getInputStream(); - } - else { - InputStream ein = urlConnection.getErrorStream(); - return (ein != null) ? ein : new ByteArrayInputStream(new byte[0]); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/PipelineHelpers.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/PipelineHelpers.java deleted file mode 100644 index 8aca9db4c693b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/core/utils/pipeline/PipelineHelpers.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.utils.pipeline; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.microsoft.windowsazure.services.blob.models.AccessCondition; -import com.microsoft.windowsazure.services.blob.models.AccessConditionHeaderType; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; - -public class PipelineHelpers { - - private static String createErrorMessage(ClientResponse clientResponse) { - clientResponse.bufferEntity(); - String errorMessage = clientResponse.toString(); - if (clientResponse.hasEntity()) { - errorMessage = errorMessage + " " + clientResponse.getEntity(String.class); - } - return errorMessage; - } - - public static void ThrowIfNotSuccess(ClientResponse clientResponse) { - int statusCode = clientResponse.getStatus(); - - if ((statusCode < 200) || (statusCode >= 300)) { - String errorMessage = createErrorMessage(clientResponse); - throw new UniformInterfaceException(errorMessage, clientResponse); - } - } - - public static void ThrowIfError(ClientResponse clientResponse) { - if (clientResponse.getStatus() >= 400) { - String errorMessage = createErrorMessage(clientResponse); - throw new UniformInterfaceException(errorMessage, clientResponse); - } - } - - public static WebResource addOptionalQueryParam(WebResource webResource, String key, Object value) { - if (value != null) { - webResource = webResource.queryParam(key, value.toString()); - } - return webResource; - } - - public static WebResource addOptionalQueryParam(WebResource webResource, String key, int value, int defaultValue) { - if (value != defaultValue) { - webResource = webResource.queryParam(key, Integer.toString(value)); - } - return webResource; - } - - public static Builder addOptionalHeader(Builder builder, String name, Object value) { - if (value != null) { - builder = builder.header(name, value); - } - return builder; - } - - public static Builder addOptionalMetadataHeader(Builder builder, Map metadata) { - for (Entry entry : metadata.entrySet()) { - builder = builder.header("x-ms-meta-" + entry.getKey(), entry.getValue()); - } - return builder; - } - - public static Builder addOptionalRangeHeader(Builder builder, Long rangeStart, Long rangeEnd) { - if (rangeStart != null) { - String range = rangeStart.toString() + "-"; - if (rangeEnd != null) { - range += rangeEnd.toString(); - } - builder = addOptionalHeader(builder, "Range", "bytes=" + range); - } - return builder; - } - - public static Builder addOptionalAccessConditionHeader(Builder builder, AccessCondition accessCondition) { - if (accessCondition != null) { - if (accessCondition.getHeader() != AccessConditionHeaderType.NONE) { - builder = addOptionalHeader(builder, accessCondition.getHeader().toString(), accessCondition.getValue()); - } - } - return builder; - } - - public static Builder addOptionalSourceAccessConditionHeader(Builder builder, AccessCondition accessCondition) { - if (accessCondition != null) { - if (accessCondition.getHeader() != AccessConditionHeaderType.NONE) { - String headerName; - switch (accessCondition.getHeader()) { - case IF_MATCH: - headerName = "x-ms-source-if-match"; - break; - case IF_UNMODIFIED_SINCE: - headerName = "x-ms-source-if-unmodified-since"; - break; - case IF_MODIFIED_SINCE: - headerName = "x-ms-source-if-modified-since"; - break; - case IF_NONE_MATCH: - headerName = "x-ms-source-if-none-match"; - break; - default: - headerName = ""; - } - builder = addOptionalHeader(builder, headerName, accessCondition.getValue()); - } - } - return builder; - } - - public static HashMap getMetadataFromHeaders(ClientResponse response) { - HashMap metadata = new HashMap(); - for (Entry> entry : response.getHeaders().entrySet()) { - if (entry.getKey().startsWith("x-ms-meta-")) { - String name = entry.getKey().substring("x-ms-meta-".length()); - String value = entry.getValue().get(0); - metadata.put(name, value); - } - } - return metadata; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/Exports.java deleted file mode 100644 index 5c562f4ad58bb..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/Exports.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management; - -import static com.microsoft.windowsazure.services.core.utils.ExportUtils.*; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.Map; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.management.implementation.KeyStoreCredential; -import com.microsoft.windowsazure.services.management.implementation.KeyStoreType; -import com.microsoft.windowsazure.services.management.implementation.ManagementExceptionProcessor; -import com.microsoft.windowsazure.services.management.implementation.ManagementRestProxy; -import com.microsoft.windowsazure.services.management.implementation.SSLContextFactory; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.client.urlconnection.HTTPSProperties; - -/** - * The Class Exports. - */ -public class Exports implements Builder.Exports { - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.Builder.Exports#register(com.microsoft.windowsazure.services.core.Builder.Registry) - */ - @Override - public void register(Builder.Registry registry) { - - // provide contract implementation - registry.add(ManagementContract.class, ManagementExceptionProcessor.class); - registry.add(ManagementRestProxy.class); - registry.add(UserAgentFilter.class); - - // alter jersey client config for service management. - registry.alter(ManagementContract.class, ClientConfig.class, new Builder.Alteration() { - - @Override - public ClientConfig alter(String profile, ClientConfig clientConfig, Builder builder, - Map properties) { - - String keyStorePath = (String) getPropertyIfExists(profile, properties, - ManagementConfiguration.KEYSTORE_PATH); - - String keyStorePass = (String) getPropertyIfExists(profile, properties, - ManagementConfiguration.KEYSTORE_PASSWORD); - - KeyStoreType keyStoreType = KeyStoreType.valueOf((String) getPropertyIfExists(profile, properties, - ManagementConfiguration.KEYSTORE_TYPE)); - - KeyStoreCredential keyStoreCredential = null; - try { - keyStoreCredential = new KeyStoreCredential(keyStorePath, keyStorePass, keyStoreType); - } - catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - catch (IOException e) { - throw new RuntimeException(e); - } - - SSLContext sslContext = null; - try { - sslContext = SSLContextFactory.createSSLContext(keyStoreCredential); - } - catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - catch (IOException e) { - throw new RuntimeException(e); - } - - clientConfig.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, - new HTTPSProperties(new HostnameVerifier() { - @Override - public boolean verify(String arg0, SSLSession arg1) { - return true; - } - }, sslContext)); - return clientConfig; - } - }); - - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementConfiguration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementConfiguration.java deleted file mode 100644 index 1adc84750a9f1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementConfiguration.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management; - -import com.microsoft.windowsazure.services.core.Configuration; - -/** - * Provides functionality to create a service management configuration. - * - */ -public class ManagementConfiguration { - - /** - * Defines the path of the keystore. - * - */ - public final static String KEYSTORE_PATH = "management.keystore.path"; - - /** - * Defines the password of the keystore. - * - */ - public final static String KEYSTORE_PASSWORD = "management.keystore.password"; - - /** - * Defines the type of the keystore. - */ - public static final String KEYSTORE_TYPE = "management.keystore.type"; - - /** - * Defines the URI of service management. - * - */ - public final static String URI = "management.uri"; - - /** - * Defines the subscription ID of the Windows Azure account. - */ - public static final String SUBSCRIPTION_ID = "management.subscription.id"; - - /** - * Creates a service management configuration using specified URI, and subscription ID. - * - * @param uri - * A String object that represents the root URI of the service management service. - * @param subscriptionId - * A String object that represents the subscription ID. - * @return the configuration - * A Configuration object that can be used when creating an instance of the - * ManagementContract class. - */ - public static Configuration configure(String uri, String subscriptionId) { - return configure(null, Configuration.getInstance(), uri, subscriptionId, null, null); - } - - /** - * Creates a service management configuration with specified parameters. - * - * @param profile - * A String object that represents the profile. - * @param configuration - * A previously instantiated Configuration object. - * @param uri - * A String object that represents the URI of the service management service. - * @param subscriptionId - * A String object that represents the subscription ID. - * @param keyStoreLocation - * the key store location - * @param keyStorePassword - * A String object that represents the password of the keystore. - * @return A Configuration object that can be used when creating an instance of the - * ManagementContract class. - */ - public static Configuration configure(String profile, Configuration configuration, String uri, - String subscriptionId, String keyStoreLocation, String keyStorePassword) { - - if (profile == null) { - profile = ""; - } - else if (profile.length() != 0 && !profile.endsWith(".")) { - profile = profile + "."; - } - - configuration.setProperty(profile + URI, "https://" + uri); - configuration.setProperty(profile + SUBSCRIPTION_ID, subscriptionId); - configuration.setProperty(profile + KEYSTORE_PATH, keyStoreLocation); - configuration.setProperty(profile + KEYSTORE_PASSWORD, keyStorePassword); - - return configuration; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementContract.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementContract.java deleted file mode 100644 index febe9e49fff11..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementContract.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management; - -import com.microsoft.windowsazure.services.core.FilterableService; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.management.models.AffinityGroupInfo; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.DeleteAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.GetAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.ListResult; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupResult; - -/** - * - * Defines the service management contract. - * - */ -public interface ManagementContract extends FilterableService { - - /** - * Gets the information of an affinity group. - * - * @param name - * The name of the affinity group. - * @return A GetAffinityGroupResult instance which contains the information of the affinity group. - * @throws ServiceException - * the service exception - */ - GetAffinityGroupResult getAffinityGroup(String name) throws ServiceException; - - /** - * Creates an affinity group. - * - * @param createAffinityGroupOptions - * The options to create an affinity group. - * @return A CreateAffinityGroupResult instance which contains the information of the affinity group. - * @throws ServiceException - * the service exception - */ - CreateAffinityGroupResult createAffinityGroup(CreateAffinityGroupOptions createAffinityGroupOptions) - throws ServiceException; - - /** - * Delete affinity group. - * - * @param name - * The name of the affinity group. - * @return A DeleteAffinityGroupResult instance containing the result of delete affinity group - * operation. - * - * @throws ServiceException - * the service exception - */ - DeleteAffinityGroupResult deleteAffinityGroup(String name) throws ServiceException; - - /** - * List affinity groups. - * - * @return the result of the list affinity group operation. - * @throws ServiceException - * the service exception - */ - ListResult listAffinityGroups() throws ServiceException; - - /** - * Update affinity group. - * - * @param updateAffinityGroupOptions - * The options to update the affinity group. - * @return A UpdateAffinityGroupResult class instance which contains the result of update affinity - * group operation. - * - * @throws ServiceException - * the service exception - */ - UpdateAffinityGroupResult updateAffinityGroup(UpdateAffinityGroupOptions updateAffinityGroupOptions) - throws ServiceException; - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementService.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementService.java deleted file mode 100644 index 5413546069826..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/ManagementService.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management; - -import com.microsoft.windowsazure.services.core.Configuration; - -/** - * - * Access service management functionality. - * - */ -public class ManagementService { - - private ManagementService() { - // class is not instantiated - } - - /** - * Creates an instance of the ManagementContract API. - * - */ - public static ManagementContract create() { - return Configuration.getInstance().create(ManagementContract.class); - } - - /** - * Creates an instance of the ManagementContract API using the specified configuration. - * - * @param config - * A Configuration object that represents the configuration for the service management. - * - */ - public static ManagementContract create(Configuration config) { - return config.create(ManagementContract.class); - } - - /** - * Creates an instance of the ManagementContract API. - * - * @param profile - * A String object that representing the profile of the service management service. - * - */ - public static ManagementContract create(String profile) { - return Configuration.getInstance().create(profile, ManagementContract.class); - } - - /** - * Creates an instance of the ManagementContract API using the specified configuration. - * - * @param config - * A Configuration object that represents the configuration for the service management. - * - */ - public static ManagementContract create(String profile, Configuration config) { - return config.create(profile, ManagementContract.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/KeyStoreType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/KeyStoreType.java deleted file mode 100644 index ffd178b12687c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/KeyStoreType.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.implementation; - -/** - * The Enum representing the type of the KeyStore. - */ -public enum KeyStoreType { - - /** The jceks. */ - jceks, - /** The jks. */ - jks, - /** The pkcs12. */ - pkcs12 -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/ManagementExceptionProcessor.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/ManagementExceptionProcessor.java deleted file mode 100644 index ef82bc576ddab..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/ManagementExceptionProcessor.java +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management.implementation; - -import javax.inject.Inject; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.microsoft.windowsazure.services.management.ManagementContract; -import com.microsoft.windowsazure.services.management.models.AffinityGroupInfo; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.DeleteAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.GetAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.ListResult; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupResult; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.UniformInterfaceException; - -/** - * The Class ManagementExceptionProcessor. - */ -public class ManagementExceptionProcessor implements ManagementContract { - - /** The next. */ - private final ManagementContract next; - - /** The log. */ - static Log log = LogFactory.getLog(ManagementContract.class); - - /** - * Instantiates a new management exception processor. - * - * @param next - * the next - */ - public ManagementExceptionProcessor(ManagementContract next) { - this.next = next; - } - - /** - * Instantiates a new management exception processor. - * - * @param next - * the next - */ - @Inject - public ManagementExceptionProcessor(ManagementRestProxy next) { - this.next = next; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.FilterableService#withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) - */ - @Override - public ManagementContract withFilter(ServiceFilter filter) { - return new ManagementExceptionProcessor(next.withFilter(filter)); - } - - /** - * Process catch. - * - * @param e - * the e - * @return the service exception - */ - private ServiceException processCatch(ServiceException e) { - log.warn(e.getMessage(), e.getCause()); - return ServiceExceptionFactory.process("serviceBus", e); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#listAffinityGroups() - */ - @Override - public ListResult listAffinityGroups() throws ServiceException { - try { - return next.listAffinityGroups(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#getAffinityGroup(java.lang.String) - */ - @Override - public GetAffinityGroupResult getAffinityGroup(String name) throws ServiceException { - try { - return next.getAffinityGroup(name); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#deleteAffinityGroup(java.lang.String) - */ - @Override - public DeleteAffinityGroupResult deleteAffinityGroup(String name) throws ServiceException { - try { - return next.deleteAffinityGroup(name); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#createAffinityGroup(com.microsoft.windowsazure.services.management.models.CreateAffinityGroupOptions) - */ - @Override - public CreateAffinityGroupResult createAffinityGroup(CreateAffinityGroupOptions createAffinityGroupOptions) - throws ServiceException { - try { - return next.createAffinityGroup(createAffinityGroupOptions); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#updateAffinityGroup(com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupOptions) - */ - @Override - public UpdateAffinityGroupResult updateAffinityGroup(UpdateAffinityGroupOptions updateAffinityGroupOptions) - throws ServiceException { - try { - return next.updateAffinityGroup(updateAffinityGroupOptions); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/ManagementRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/ManagementRestProxy.java deleted file mode 100644 index ee12354b10065..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/ManagementRestProxy.java +++ /dev/null @@ -1,261 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management.implementation; - -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.pipeline.ClientFilterAdapter; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.microsoft.windowsazure.services.management.ManagementConfiguration; -import com.microsoft.windowsazure.services.management.ManagementContract; -import com.microsoft.windowsazure.services.management.models.AffinityGroupInfo; -import com.microsoft.windowsazure.services.management.models.AffinityGroupInfoFactory; -import com.microsoft.windowsazure.services.management.models.AffinityGroupInfoListFactory; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.DeleteAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.GetAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.ListResult; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupResult; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; - -/** - * The Class ManagementRestProxy. - */ -public class ManagementRestProxy implements ManagementContract { - - /** The channel. */ - private Client channel; - - /** The uri. */ - private final String uri; - - /** The subscription id. */ - private final String subscriptionId; - - /** The rfc1123 date convert. */ - private final RFC1123DateConverter rfc1123DateConvert = new RFC1123DateConverter(); - - /** The log. */ - static Log log = LogFactory.getLog(ManagementContract.class); - - /** The filters. */ - ServiceFilter[] filters; - - /** - * Instantiates a new management rest proxy. - * - * @param channel - * the channel - * @param uri - * the uri - * @param subscriptionId - * the subscription id - * @param userAgentFilter - * the user agent filter - */ - @Inject - public ManagementRestProxy(Client channel, @Named(ManagementConfiguration.URI) String uri, - @Named(ManagementConfiguration.SUBSCRIPTION_ID) String subscriptionId, UserAgentFilter userAgentFilter) { - - this.channel = channel; - this.filters = new ServiceFilter[0]; - this.uri = uri; - this.subscriptionId = subscriptionId; - this.channel.addFilter(userAgentFilter); - } - - /** - * Instantiates a new management rest proxy. - * - * @param channel - * the channel - * @param serviceFilter - * the service filter - * @param uri - * the uri - * @param subscriptionId - * the subscription id - * @param keyStorePath - * the key store path - */ - public ManagementRestProxy(Client channel, ServiceFilter[] serviceFilter, String uri, String subscriptionId) { - this.channel = channel; - this.filters = serviceFilter; - this.uri = uri; - this.subscriptionId = subscriptionId; - } - - /** - * Gets the channel. - * - * @return the channel - */ - public Client getChannel() { - return channel; - } - - /** - * Sets the channel. - * - * @param channel - * the new channel - */ - public void setChannel(Client channel) { - this.channel = channel; - } - - /** - * Gets the resource. - * - * @return the resource - */ - private WebResource getResource() { - WebResource resource = getChannel().resource(this.uri); - for (ServiceFilter filter : filters) { - resource.addFilter(new ClientFilterAdapter(filter)); - } - return resource; - } - - /** - * Gets the request id. - * - * @param clientResponse - * the client response - * @return the request id - */ - private String getRequestId(ClientResponse clientResponse) { - return clientResponse.getHeaders().getFirst("x-ms-request-id"); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.FilterableService#withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) - */ - @Override - public ManagementContract withFilter(ServiceFilter filter) { - ServiceFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1); - newFilters[filters.length] = filter; - return new ManagementRestProxy(channel, newFilters, uri, subscriptionId); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#listAffinityGroups() - */ - @Override - public ListResult listAffinityGroups() { - ClientResponse clientResponse = getResource().path(subscriptionId).path("affinitygroups") - .header("x-ms-version", "2013-03-01").header("x-ms-client-request-id", UUID.randomUUID()) - .get(ClientResponse.class); - PipelineHelpers.ThrowIfNotSuccess(clientResponse); - String requestId = getRequestId(clientResponse); - AffinityGroups affinityGroups = clientResponse.getEntity(AffinityGroups.class); - List affinityGroupInfoList = AffinityGroupInfoListFactory.getItem(affinityGroups); - return new ListResult(clientResponse.getStatus(), requestId, affinityGroupInfoList); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#createAffinityGroup(com.microsoft.windowsazure.services.management.models.CreateAffinityGroupOptions) - */ - @Override - public CreateAffinityGroupResult createAffinityGroup(CreateAffinityGroupOptions createAffinityGroupOptions) { - - CreateAffinityGroup createAffinityGroup = new CreateAffinityGroup(); - createAffinityGroup.setName(createAffinityGroupOptions.getName()); - createAffinityGroup.setLabel(createAffinityGroupOptions.getLabel()); - createAffinityGroup.setLocation(createAffinityGroupOptions.getLocation()); - if (createAffinityGroupOptions != null) { - createAffinityGroup.setDescription(createAffinityGroupOptions.getDescription()); - } - ClientResponse clientResponse = getResource().path(subscriptionId).path("affinitygroups") - .header("x-ms-version", "2013-03-01").header("x-ms-client-request-id", UUID.randomUUID().toString()) - .type(MediaType.APPLICATION_XML).post(ClientResponse.class, createAffinityGroup); - CreateAffinityGroupResult createAffinityGroupResult = new CreateAffinityGroupResult(clientResponse.getStatus(), - getRequestId(clientResponse)); - MultivaluedMap headers = clientResponse.getHeaders(); - createAffinityGroupResult.setLocation(headers.getFirst("Location")); - createAffinityGroupResult.setRegion(headers.getFirst("x-ms-servedbyregion")); - createAffinityGroupResult.setServer(headers.getFirst("Server")); - createAffinityGroupResult.setDate(rfc1123DateConvert.parse((headers.getFirst("Date")))); - return createAffinityGroupResult; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#getAffinityGroup(java.lang.String) - */ - @Override - public GetAffinityGroupResult getAffinityGroup(String name) { - ClientResponse clientResponse = getResource().path(subscriptionId).path("affinitygroups").path(name) - .header("x-ms-version", "2013-03-01").get(ClientResponse.class); - PipelineHelpers.ThrowIfError(clientResponse); - GetAffinityGroupResult getAffinityGroupResult = new GetAffinityGroupResult(clientResponse.getStatus(), - getRequestId(clientResponse)); - AffinityGroup affinityGroup = clientResponse.getEntity(AffinityGroup.class); - AffinityGroupInfo affinityGroupInfo = AffinityGroupInfoFactory.getItem(affinityGroup); - getAffinityGroupResult.setValue(affinityGroupInfo); - return getAffinityGroupResult; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#deleteAffinityGroup(java.lang.String) - */ - @Override - public DeleteAffinityGroupResult deleteAffinityGroup(String name) { - ClientResponse clientResponse = getResource().path(subscriptionId).path("affinitygroups").path(name) - .header("x-ms-version", "2013-03-01").delete(ClientResponse.class); - PipelineHelpers.ThrowIfError(clientResponse); - DeleteAffinityGroupResult deleteAffinityGroupResult = new DeleteAffinityGroupResult(clientResponse.getStatus(), - getRequestId(clientResponse)); - return deleteAffinityGroupResult; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.management.ManagementContract#updateAffinityGroup(com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupOptions) - */ - @Override - public UpdateAffinityGroupResult updateAffinityGroup(UpdateAffinityGroupOptions updateAffinityGroupOptions) { - UpdateAffinityGroup updateAffinityGroup = new UpdateAffinityGroup(); - updateAffinityGroup.setLabel(updateAffinityGroupOptions.getLabel()); - if (updateAffinityGroupOptions != null) { - updateAffinityGroup.setDescription(updateAffinityGroupOptions.getDescription()); - } - ClientResponse clientResponse = getResource().path(subscriptionId).path("affinitygroups") - .path(updateAffinityGroupOptions.getName()).header("x-ms-version", "2011-02-25") - .put(ClientResponse.class, updateAffinityGroup); - PipelineHelpers.ThrowIfError(clientResponse); - UpdateAffinityGroupResult updateAffinityGroupResult = new UpdateAffinityGroupResult(clientResponse.getStatus(), - getRequestId(clientResponse)); - MultivaluedMap headers = clientResponse.getHeaders(); - updateAffinityGroupResult.setRegion(headers.getFirst("x-ms-servedbyregion")); - updateAffinityGroupResult.setDate(rfc1123DateConvert.parse((headers.getFirst("Date")))); - return updateAffinityGroupResult; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/SSLContextFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/SSLContextFactory.java deleted file mode 100644 index e19d2f291f7f7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/implementation/SSLContextFactory.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.implementation; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; - -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; - -/** - * A factory for creating SSLContext instance. - */ -public class SSLContextFactory { - - /** - * Creates a SSLContext with specified keystore credential. - * - * @param keyStoreCredential - * the credential of the keystore. - * @return a SSLContext instance. - * @throws GeneralSecurityException - * the general security exception - * @throws IOException - * when an I/O exception has occurred. - */ - public static SSLContext createSSLContext(KeyStoreCredential keyStoreCredential) throws GeneralSecurityException, - IOException { - if (keyStoreCredential == null) { - throw new IllegalArgumentException("KeyStoreCredential cannot be null."); - } - return create(keyStoreCredential.getKeyStorePath(), keyStoreCredential.getKeystorePassword(), - keyStoreCredential.getKeyStoreType()); - } - - /** - * Creates a SSLContext object with specified keystore stream and password. - * - * @param keyStorePath - * the path of the keystore. - * @param keyStorePassword - * the password of the keystore. - * @param keyStoreType - * the type of the keystore. - * @return An SSLContext instance. - * @throws GeneralSecurityException - * the general security exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ - public static SSLContext create(String keyStorePath, String keyStorePassword, KeyStoreType keyStoreType) - throws GeneralSecurityException, IOException { - - if ((keyStorePath == null) || (keyStorePath.isEmpty())) { - throw new IllegalArgumentException("The keystore path cannot be null or empty."); - } - - if (keyStoreType == null) { - throw new IllegalArgumentException("The type of the keystore cannot be null"); - } - - InputStream keyStoreInputStream = new FileInputStream(keyStorePath); - KeyManager[] keyManagers = getKeyManagers(keyStoreInputStream, keyStorePassword, keyStoreType); - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, null, new SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); - keyStoreInputStream.close(); - return sslContext; - } - - /** - * Gets the key managers. - * - * @param keyStoreStream - * the key store stream - * @param keyStorePassword - * the key stream password - * @param type - * the type - * @return the key managers - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws GeneralSecurityException - * the general security exception - */ - private static KeyManager[] getKeyManagers(InputStream keyStoreInputStream, String keyStorePassword, - KeyStoreType keyStoreType) throws IOException, GeneralSecurityException { - - KeyStore keyStore = KeyStore.getInstance(keyStoreType.name()); - keyStore.load(keyStoreInputStream, keyStorePassword.toCharArray()); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); - - return keyManagerFactory.getKeyManagers(); - } - -} \ No newline at end of file diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfo.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfo.java deleted file mode 100644 index 58698b4ce6865..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfo.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -/** - * Type containing data about affinity group. - * - */ -public class AffinityGroupInfo { - - /** The name. */ - private String name; - - /** The label. */ - private String label; - - /** The description. */ - private String description; - - /** The location. */ - private String location; - - /** - * Gets the name. - * - * @return the name - */ - public String getName() { - return this.name; - } - - /** - * Sets the name. - * - * @param name - * the name - * @return the affinity group info - */ - public AffinityGroupInfo setName(String name) { - this.name = name; - return this; - } - - /** - * Gets the label. - * - * @return the label - */ - public String getLabel() { - return this.label; - } - - /** - * Sets the label. - * - * @param label - * the label - * @return the affinity group info - */ - public AffinityGroupInfo setLabel(String label) { - this.label = label; - return this; - } - - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - return this.description; - } - - /** - * Sets the description. - * - * @param description - * the description - * @return the affinity group info - */ - public AffinityGroupInfo setDescription(String description) { - this.description = description; - return this; - } - - /** - * Gets the location. - * - * @return the location - */ - public String getLocation() { - return this.location; - } - - /** - * Sets the location. - * - * @param location - * the location - * @return the affinity group info - */ - public AffinityGroupInfo setLocation(String location) { - this.location = location; - return this; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfoFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfoFactory.java deleted file mode 100644 index 65f9d39a95c51..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfoFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -import com.microsoft.windowsazure.services.management.implementation.AffinityGroup; - -/** - * A factory for creating AffinityGroupInfo objects. - */ -public class AffinityGroupInfoFactory { - - /** - * Gets an affinity group info instance with specified affinity group. - * - * @param affinityGroup - * the affinity group - * @return A AffinityGroupInfo instance. - */ - public static AffinityGroupInfo getItem(AffinityGroup affinityGroup) { - if (affinityGroup == null) { - return null; - } - else { - return new AffinityGroupInfo().setName(affinityGroup.getName()).setLabel(affinityGroup.getLabel()) - .setLocation(affinityGroup.getLocation()).setDescription(affinityGroup.getDescription()); - } - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfoListFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfoListFactory.java deleted file mode 100644 index 6f131867b8465..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/AffinityGroupInfoListFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -import java.util.ArrayList; -import java.util.List; - -import com.microsoft.windowsazure.services.management.implementation.AffinityGroup; -import com.microsoft.windowsazure.services.management.implementation.AffinityGroups; - -/** - * A factory for creating AffinityGroupInfoList objects. - */ -public class AffinityGroupInfoListFactory { - - /** - * Gets the item. - * - * @param affinityGroups - * the affinity groups - * @return the item - */ - public static List getItem(AffinityGroups affinityGroups) { - List result = new ArrayList(); - List affinityGroupList = affinityGroups.getAffinityGroups(); - for (AffinityGroup affinityGroup : affinityGroupList) { - AffinityGroupInfo affinityGroupInfo = AffinityGroupInfoFactory.getItem(affinityGroup); - result.add(affinityGroupInfo); - } - return result; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/CreateAffinityGroupOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/CreateAffinityGroupOptions.java deleted file mode 100644 index ec8c91aa320e6..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/CreateAffinityGroupOptions.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -/** - * The options to create affinity group. - * - */ -public class CreateAffinityGroupOptions { - - /** The descrption. */ - private String descrption; - - /** The name. */ - private final String name; - - /** The label. */ - private final String label; - - /** The location. */ - private final String location; - - /** - * Instantiates a new creates the affinity group options. - * - * @param name - * the name - * @param label - * the label - * @param location - * the location - */ - public CreateAffinityGroupOptions(String name, String label, String location) { - this.name = name; - this.label = label; - this.location = location; - } - - /** - * Sets the description. - * - * @param description - * the description - * @return the creates the affinity group options - */ - public CreateAffinityGroupOptions setDescription(String description) { - this.descrption = description; - return this; - } - - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - return this.descrption; - } - - /** - * Gets the name. - * - * @return the name - */ - public String getName() { - return this.name; - } - - /** - * Gets the label. - * - * @return the label - */ - public String getLabel() { - return this.label; - } - - /** - * Gets the location. - * - * @return the location - */ - public String getLocation() { - return this.location; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/CreateAffinityGroupResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/CreateAffinityGroupResult.java deleted file mode 100644 index 33bb8b6640a47..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/CreateAffinityGroupResult.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -import java.util.Date; - -/** - * The base result class for all the result of service management operation. - * - */ -public class CreateAffinityGroupResult extends OperationResult { - - private String location; - private String region; - private String server; - private Date date; - - public CreateAffinityGroupResult(int statusCode, String requestId) { - super(statusCode, requestId); - } - - public CreateAffinityGroupResult setLocation(String location) { - this.location = location; - return this; - - } - - public CreateAffinityGroupResult setRegion(String region) { - this.region = region; - return this; - } - - public CreateAffinityGroupResult setServer(String server) { - this.server = server; - return this; - } - - public CreateAffinityGroupResult setDate(Date date) { - this.date = date; - return this; - } - - public String getLocation() { - return this.location; - } - - public String getRegion() { - return this.region; - } - - public String getServer() { - return this.server; - } - - public Date getDate() { - return this.date; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/DeleteAffinityGroupResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/DeleteAffinityGroupResult.java deleted file mode 100644 index 9150ea812c2b9..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/DeleteAffinityGroupResult.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - - -/** - * The base result class for all the result of service management operation. - * - */ -public class DeleteAffinityGroupResult extends OperationResult { - - public DeleteAffinityGroupResult(int statusCode, String requestId) { - super(statusCode, requestId); - } - - public AffinityGroupInfo getValue() { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/GetAffinityGroupResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/GetAffinityGroupResult.java deleted file mode 100644 index 41b39decb7623..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/GetAffinityGroupResult.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - - -/** - * The base result class for all the result of service management operation. - * - */ -public class GetAffinityGroupResult extends OperationResult { - - private AffinityGroupInfo value; - - public GetAffinityGroupResult(int statusCode, String requestId) { - super(statusCode, requestId); - } - - public AffinityGroupInfo getValue() { - return value; - } - - public GetAffinityGroupResult setValue(AffinityGroupInfo affinityGroupInfo) { - this.value = affinityGroupInfo; - return this; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/ListResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/ListResult.java deleted file mode 100644 index f0f600740e19e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/ListResult.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -/** - * Wrapper class for all returned lists from service management. - * - */ -public class ListResult extends OperationResult implements List { - - private final List contents; - - public ListResult(int statusCode, String requestId, Collection contentList) { - super(statusCode, requestId); - contents = Collections.unmodifiableList(new ArrayList(contentList)); - } - - @Override - public boolean add(T element) { - return contents.add(element); - } - - @Override - public void add(int index, T element) { - contents.add(index, element); - } - - @Override - public boolean addAll(Collection c) { - return contents.addAll(c); - } - - @Override - public boolean addAll(int index, Collection c) { - return contents.addAll(index, c); - } - - @Override - public void clear() { - contents.clear(); - } - - @Override - public boolean contains(Object object) { - return contents.contains(object); - } - - @Override - public boolean containsAll(Collection c) { - return contents.containsAll(c); - } - - @Override - public T get(int index) { - return contents.get(index); - } - - @Override - public int indexOf(Object object) { - return contents.indexOf(object); - } - - @Override - public boolean isEmpty() { - return contents.isEmpty(); - } - - @Override - public Iterator iterator() { - return contents.iterator(); - } - - @Override - public int lastIndexOf(Object object) { - return contents.lastIndexOf(object); - } - - @Override - public ListIterator listIterator() { - return contents.listIterator(); - } - - @Override - public ListIterator listIterator(int index) { - return contents.listIterator(index); - - } - - @Override - public boolean remove(Object o) { - return contents.remove(o); - } - - @Override - public T remove(int index) { - return contents.remove(index); - } - - @Override - public boolean removeAll(Collection c) { - return contents.removeAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return contents.retainAll(c); - } - - @Override - public T set(int index, T element) { - return contents.set(index, element); - } - - @Override - public int size() { - return contents.size(); - } - - @Override - public List subList(int fromIndex, int toIndex) { - return contents.subList(fromIndex, toIndex); - } - - @Override - public Object[] toArray() { - return contents.toArray(); - } - - @Override - public U[] toArray(U[] a) { - return contents.toArray(a); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/OperationResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/OperationResult.java deleted file mode 100644 index c426891bfd1c0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/OperationResult.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - - -/** - * The base result class for all the result of service management operation. - * - */ -public class OperationResult { - - protected final String requestId; - protected final int statusCode; - - public OperationResult(int statusCode, String requestId) { - this.statusCode = statusCode; - this.requestId = requestId; - } - - public int getStatusCode() { - return this.statusCode; - } - - public String getRequestId() { - return this.requestId; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/UpdateAffinityGroupOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/UpdateAffinityGroupOptions.java deleted file mode 100644 index 27bcd82890c38..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/UpdateAffinityGroupOptions.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -/** - * The base result class for all the result of service management operation. - * - */ -public class UpdateAffinityGroupOptions { - - private String description; - private final String name; - private final String label; - - public UpdateAffinityGroupOptions(String name, String label) { - this.name = name; - this.label = label; - } - - public UpdateAffinityGroupOptions setDescription(String description) { - this.description = description; - return this; - } - - public String getDescription() { - return this.description; - } - - public String getName() { - return this.name; - } - - public String getLabel() { - return this.label; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/UpdateAffinityGroupResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/UpdateAffinityGroupResult.java deleted file mode 100644 index 90b60432f9697..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/models/UpdateAffinityGroupResult.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.management.models; - -import java.util.Date; - -/** - * The base result class for all the result of service management operation. - * - */ -public class UpdateAffinityGroupResult extends OperationResult { - - private String region; - private Date date; - - public UpdateAffinityGroupResult(int statusCode, String requestId) { - super(statusCode, requestId); - } - - public UpdateAffinityGroupResult setRegion(String region) { - this.region = region; - return this; - } - - public UpdateAffinityGroupResult setDate(Date date) { - this.date = date; - return this; - } - - public String getRegion() { - return this.region; - } - - public Date getDate() { - return this.date; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/package.html deleted file mode 100644 index e8dfd96862b70..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/management/package.html +++ /dev/null @@ -1,6 +0,0 @@ - - -This package contains the service management class, - interface, and associated configuration and utility classes. - - diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/Exports.java deleted file mode 100644 index ff79a26d66370..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/Exports.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.media; - -import java.util.Map; - -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.media.implementation.MediaContentProvider; -import com.microsoft.windowsazure.services.media.implementation.MediaExceptionProcessor; -import com.microsoft.windowsazure.services.media.implementation.MediaRestProxy; -import com.microsoft.windowsazure.services.media.implementation.OAuthContract; -import com.microsoft.windowsazure.services.media.implementation.OAuthFilter; -import com.microsoft.windowsazure.services.media.implementation.OAuthRestProxy; -import com.microsoft.windowsazure.services.media.implementation.OAuthTokenManager; -import com.microsoft.windowsazure.services.media.implementation.ODataEntityCollectionProvider; -import com.microsoft.windowsazure.services.media.implementation.ODataEntityProvider; -import com.microsoft.windowsazure.services.media.implementation.RedirectFilter; -import com.microsoft.windowsazure.services.media.implementation.ResourceLocationManager; -import com.microsoft.windowsazure.services.media.implementation.VersionHeadersFilter; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; - -public class Exports implements Builder.Exports { - - /** - * register the Media services. - */ - @Override - public void register(Builder.Registry registry) { - registry.add(MediaContract.class, MediaExceptionProcessor.class); - registry.add(MediaRestProxy.class); - registry.add(OAuthContract.class, OAuthRestProxy.class); - registry.add(OAuthTokenManager.class); - registry.add(OAuthFilter.class); - registry.add(ResourceLocationManager.class); - registry.add(RedirectFilter.class); - registry.add(VersionHeadersFilter.class); - registry.add(UserAgentFilter.class); - - registry.alter(MediaContract.class, ClientConfig.class, new Builder.Alteration() { - @SuppressWarnings("rawtypes") - @Override - public ClientConfig alter(String profile, ClientConfig instance, Builder builder, - Map properties) { - - instance.getProperties().put(JSONConfiguration.FEATURE_POJO_MAPPING, true); - - // Turn off auto-follow redirects, because Media Services rest calls break if it's on - instance.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, false); - - try { - instance.getSingletons().add(new ODataEntityProvider()); - instance.getSingletons().add(new ODataEntityCollectionProvider()); - instance.getSingletons().add(new MediaContentProvider()); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - catch (ParserConfigurationException e) { - throw new RuntimeException(e); - } - - return instance; - } - }); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaConfiguration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaConfiguration.java deleted file mode 100644 index e85fd9803b60c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/MediaConfiguration.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.media; - -import com.microsoft.windowsazure.services.core.Configuration; - -/** - * Provides functionality to create a media services configuration. - * - */ -public class MediaConfiguration { - - private MediaConfiguration() { - } - - /** - * Defines the media service configuration URI constant. - * - */ - public static final String URI = "media.uri"; - - /** - * Defines the OAUTH configuration URI constant. - * - */ - public static final String OAUTH_URI = "media.oauth.uri"; - - /** - * Defines the OAUTH configuration client ID constant. - * - */ - public static final String OAUTH_CLIENT_ID = "media.oauth.client.id"; - - /** - * Defines the OAUTH configuration client secret constant. - * - */ - public static final String OAUTH_CLIENT_SECRET = "media.oauth.client.secret"; - - /** - * Defines the SCOPE of the media service sent to OAUTH. - */ - public static final String OAUTH_SCOPE = "media.oauth.scope"; - - /** - * Creates a media service configuration using the specified media service base URI, OAUTH URI, - * client ID, and client secret. - * - * @param mediaServiceUri - * A String object that represents the media service URI. - * - * @param oAuthUri - * A String object that represents the OAUTH URI. - * - * @param clientId - * A String object that represents the client ID. - * - * @param clientSecret - * A String object that represents the client secret. - * - * @param scope - * A String object that represents the scope. - * - * @return - * A Configuration object that can be used when creating an instance of the - * MediaService class. - * - */ - public static Configuration configureWithOAuthAuthentication(String mediaServiceUri, String oAuthUri, - String clientId, String clientSecret, String scope) { - return configureWithOAuthAuthentication(null, Configuration.getInstance(), mediaServiceUri, oAuthUri, clientId, - clientSecret, scope); - } - - /** - * Creates a media service configuration using the specified configuration, media service base URI, OAuth URI, - * client ID, and client secret. - * - * @param configuration - * A previously instantiated Configuration object. - * - * @param mediaServiceUri - * A String object that represents the URI of media service. - * - * @param oAuthUri - * A String object that represents the URI of OAuth service. - * - * @param clientId - * A String object that represents the client ID. - * - * @param clientSecret - * A String object that represents the client secret. - * - * @param scope - * A String object that represents the scope. - * - * @return - * A Configuration object that can be used when creating an instance of the - * MediaService class. - * - */ - public static Configuration configureWithOAuthAuthentication(Configuration configuration, String mediaServiceUri, - String oAuthUri, String clientId, String clientSecret, String scope) { - return configureWithOAuthAuthentication(null, configuration, mediaServiceUri, oAuthUri, clientId, clientSecret, - scope); - } - - /** - * Creates a media service configuration using the specified profile, configuration, media service base URI, - * OAuth URI, client ID, and client secret. - * - * @param profile - * A String object that represents the profile. - * - * @param configuration - * A previously instantiated Configuration object. - * - * @param mediaServiceUri - * A String object that represents the URI of media service. - * - * @param oAuthUri - * A String object that represents the URI of OAUTH service. - * - * @param clientId - * A String object that represents the client ID. - * - * @param clientSecret - * A String object that represents the client secret. - * - * @param scope - * A String object that represents the scope. - * - * @return - * A Configuration object that can be used when creating an instance of the - * MediaService class. - * - */ - public static Configuration configureWithOAuthAuthentication(String profile, Configuration configuration, - String mediaServiceUri, String oAuthUri, String clientId, String clientSecret, String scope) { - - if (profile == null) { - profile = ""; - } - else if (profile.length() != 0 && !profile.endsWith(".")) { - profile = profile + "."; - } - - configuration.setProperty(profile + URI, mediaServiceUri); - configuration.setProperty(profile + OAUTH_URI, oAuthUri); - configuration.setProperty(profile + OAUTH_CLIENT_ID, clientId); - configuration.setProperty(profile + OAUTH_CLIENT_SECRET, clientSecret); - configuration.setProperty(profile + OAUTH_SCOPE, scope); - - return configuration; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultActionOperation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultActionOperation.java deleted file mode 100644 index df08ea0e749a7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultActionOperation.java +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.entityoperations; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.core.util.MultivaluedMapImpl; - -/** - * Generic implementation of Delete operation usable by most entities. - */ -public class DefaultActionOperation implements EntityActionOperation { - - /** The proxy data. */ - private EntityProxyData proxyData; - - /** The name. */ - protected String name; - - /** The content type. */ - private MediaType contentType = MediaType.APPLICATION_ATOM_XML_TYPE; - - /** The accept type. */ - private MediaType acceptType = MediaType.APPLICATION_ATOM_XML_TYPE; - - /** The query parameters. */ - protected MultivaluedMap queryParameters; - - /** - * The default action operation. - * - * @param name - * the name - */ - public DefaultActionOperation(String name) { - this(); - this.name = name; - } - - /** - * Instantiates a new default action operation. - */ - public DefaultActionOperation() { - this.queryParameters = new MultivaluedMapImpl(); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#setProxyData(com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData) - */ - @Override - public void setProxyData(EntityProxyData proxyData) { - this.proxyData = proxyData; - } - - /** - * Get the current proxy data. - * - * @return the proxy data - */ - protected EntityProxyData getProxyData() { - return proxyData; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityDeleteOperation#getUri() - */ - @Override - public String getUri() { - return name; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation#getQueryParameters() - */ - @Override - public MultivaluedMap getQueryParameters() { - return this.queryParameters; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation#addQueryParameter(java.lang.String, java.lang.String) - */ - @Override - public DefaultActionOperation addQueryParameter(String key, String value) { - this.queryParameters.add(key, value); - return this; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#getContentType() - */ - @Override - public MediaType getContentType() { - return this.contentType; - } - - /** - * Sets the content type. - * - * @param contentType - * the content type - * @return the default action operation - */ - @Override - public DefaultActionOperation setContentType(MediaType contentType) { - this.contentType = contentType; - return this; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#getAcceptType() - */ - @Override - public MediaType getAcceptType() { - return this.acceptType; - } - - /** - * Sets the accept type. - * - * @param acceptType - * the accept type - * @return the default action operation - */ - public DefaultActionOperation setAcceptType(MediaType acceptType) { - this.acceptType = acceptType; - return this; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation#getVerb() - */ - @Override - public String getVerb() { - return "GET"; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation#getRequestContents() - */ - @Override - public Object getRequestContents() { - return null; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#processResponse(java.lang.Object) - */ - @Override - public Object processResponse(Object rawResponse) throws ServiceException { - PipelineHelpers.ThrowIfNotSuccess((ClientResponse) rawResponse); - return rawResponse; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityTypeActionOperation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityTypeActionOperation.java deleted file mode 100644 index d5e480a3bf9d8..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/DefaultEntityTypeActionOperation.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.entityoperations; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.core.util.MultivaluedMapImpl; - -/** - * The Class DefaultTypeActionOperation. - * - * @param - * the generic type - */ -public class DefaultEntityTypeActionOperation implements EntityTypeActionOperation { - - /** The name. */ - private String name; - - /** The content type. */ - private MediaType contentType = MediaType.APPLICATION_ATOM_XML_TYPE; - - /** The accept type. */ - private MediaType acceptType = MediaType.APPLICATION_ATOM_XML_TYPE; - - /** The query parameters. */ - private final MultivaluedMap queryParameters; - - /** The proxy data. */ - protected EntityProxyData proxyData; - - /** - * Instantiates a new default type action operation. - * - * @param name - * the name - */ - public DefaultEntityTypeActionOperation(String name) { - this(); - this.name = name; - } - - /** - * Instantiates a new default type action operation. - */ - public DefaultEntityTypeActionOperation() { - this.queryParameters = new MultivaluedMapImpl(); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation#processTypeResponse(com.sun.jersey.api.client.ClientResponse) - */ - @Override - public T processTypeResponse(ClientResponse clientResponse) { - return null; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation#getQueryParameters() - */ - @Override - public MultivaluedMap getQueryParameters() { - return this.queryParameters; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation#getVerb() - */ - @Override - public String getVerb() { - return "GET"; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation#getRequestContents() - */ - @Override - public Object getRequestContents() { - return null; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#setProxyData(com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData) - */ - @Override - public void setProxyData(EntityProxyData proxyData) { - this.proxyData = proxyData; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#getUri() - */ - @Override - public String getUri() { - return this.name; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#getContentType() - */ - @Override - public MediaType getContentType() { - return this.contentType; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#getAcceptType() - */ - @Override - public MediaType getAcceptType() { - return this.acceptType; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#processResponse(java.lang.Object) - */ - @Override - public Object processResponse(Object rawResponse) throws ServiceException { - return null; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation#addQueryParameter(java.lang.String, java.lang.String) - */ - @Override - public DefaultEntityTypeActionOperation addQueryParameter(String key, String value) { - this.queryParameters.add(key, value); - return this; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation#setContentType(javax.ws.rs.core.MediaType) - */ - @Override - public EntityTypeActionOperation setContentType(MediaType contentType) { - this.contentType = contentType; - return this; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation#setAcceptType(javax.ws.rs.core.MediaType) - */ - @Override - public EntityTypeActionOperation setAcceptType(MediaType acceptType) { - this.acceptType = acceptType; - return this; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationBase.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationBase.java deleted file mode 100644 index 013181e32de4e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationBase.java +++ /dev/null @@ -1,166 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.entityoperations; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.security.InvalidParameterException; - -import javax.ws.rs.core.MediaType; - -import com.microsoft.windowsazure.services.core.ServiceException; - -/** - * Default implementation of EntityOperation to provide - * default values for common methods. - * - */ -public abstract class EntityOperationBase implements EntityOperation { - - /** The uri builder. */ - private final EntityUriBuilder uriBuilder; - - /** The proxy data. */ - private EntityProxyData proxyData; - - /** - * Instantiates a new entity operation base. - * - * @param uri - * the uri - */ - protected EntityOperationBase(final String uri) { - this.uriBuilder = new EntityUriBuilder() { - @Override - public String getUri() { - return uri; - } - }; - } - - /** - * Instantiates a new entity operation base. - * - * @param uriBuilder - * the uri builder - */ - protected EntityOperationBase(EntityUriBuilder uriBuilder) { - this.uriBuilder = uriBuilder; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#setProxyData(com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData) - */ - @Override - public void setProxyData(EntityProxyData proxyData) { - this.proxyData = proxyData; - } - - /** - * Get the currently set proxy data. - * - * @return the proxy data - */ - protected EntityProxyData getProxyData() { - return proxyData; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityOperation#getUri() - */ - @Override - public String getUri() { - return uriBuilder.getUri(); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityOperation#getContentType() - */ - @Override - public MediaType getContentType() { - return MediaType.APPLICATION_ATOM_XML_TYPE; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityOperation#getAcceptType() - */ - @Override - public MediaType getAcceptType() { - return MediaType.APPLICATION_ATOM_XML_TYPE; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityOperation#processResponse(java.lang.Object) - */ - @Override - public Object processResponse(Object rawResponse) throws ServiceException { - return rawResponse; - } - - /** - * The Interface EntityUriBuilder. - */ - public interface EntityUriBuilder { - - /** - * Gets the uri. - * - * @return the uri - */ - String getUri(); - } - - /** - * The Class EntityIdUriBuilder. - */ - public static class EntityIdUriBuilder implements EntityUriBuilder { - - /** The entity type. */ - private final String entityType; - - /** The entity id. */ - private final String entityId; - - /** - * Instantiates a new entity id uri builder. - * - * @param entityName - * the entity name - * @param entityId - * the entity id - */ - public EntityIdUriBuilder(String entityName, String entityId) { - super(); - this.entityType = entityName; - this.entityId = entityId; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityOperationBase.EntityUriBuilder#getUri() - */ - @Override - public String getUri() { - String escapedEntityId; - try { - escapedEntityId = URLEncoder.encode(entityId, "UTF-8"); - } - catch (UnsupportedEncodingException e) { - throw new InvalidParameterException(entityId); - } - return String.format("%s('%s')", entityType, escapedEntityId); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResultBase.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResultBase.java deleted file mode 100644 index 65b82a98b36b2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityOperationSingleResultBase.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.entityoperations; - -import com.microsoft.windowsazure.services.core.ServiceException; - -/** - * - * - */ -public class EntityOperationSingleResultBase extends EntityOperationBase implements EntityOperationSingleResult { - private final Class responseClass; - - /** - * - */ - public EntityOperationSingleResultBase(String uri, Class responseClass) { - super(uri); - this.responseClass = responseClass; - } - - public EntityOperationSingleResultBase(EntityOperationBase.EntityUriBuilder uriBuilder, Class responseClass) { - super(uriBuilder); - this.responseClass = responseClass; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entities.EntityOperationSingleResult#getResponseClass() - */ - @Override - public Class getResponseClass() { - return responseClass; - } - - public Object processResponse(Object rawResponse) throws ServiceException { - return rawResponse; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityRestProxy.java deleted file mode 100644 index 00366fac6f604..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/entityoperations/EntityRestProxy.java +++ /dev/null @@ -1,203 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.entityoperations; - -import javax.ws.rs.core.MediaType; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.pipeline.ClientFilterAdapter; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; - -/** - * The Class EntityRestProxy. - */ -public abstract class EntityRestProxy implements EntityContract { - - /** The channel. */ - private final Client channel; - /** The filters. */ - private final ServiceFilter[] filters; - - /** - * Instantiates a new entity rest proxy. - * - * @param channel - * the channel - * @param filters - * the filters - */ - public EntityRestProxy(Client channel, ServiceFilter[] filters) { - this.channel = channel; - this.filters = filters; - } - - /** - * Gets the channel. - * - * @return the channel - */ - protected Client getChannel() { - return channel; - } - - /** - * Gets the filters. - * - * @return the filters - */ - protected ServiceFilter[] getFilters() { - return filters; - } - - /** - * Get the proxy data to pass to operations. - * - * @return The proxy data. - */ - protected abstract EntityProxyData createProxyData(); - - /** - * Gets the resource. - * - * @param entityName - * the entity name - * @return the resource - */ - private WebResource getResource(String entityName) { - WebResource resource = channel.resource(entityName); - for (ServiceFilter filter : filters) { - resource.addFilter(new ClientFilterAdapter(filter)); - } - return resource; - } - - /** - * Gets the resource. - * - * @param operation - * the operation - * @return the resource - * @throws ServiceException - * the service exception - */ - private Builder getResource(EntityOperation operation) throws ServiceException { - return getResource(operation.getUri()).type(operation.getContentType()).accept(operation.getAcceptType()); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#create(com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation) - */ - @SuppressWarnings("unchecked") - @Override - public T create(EntityCreateOperation creator) throws ServiceException { - creator.setProxyData(createProxyData()); - Object rawResponse = getResource(creator).post(creator.getResponseClass(), creator.getRequestContents()); - Object processedResponse = creator.processResponse(rawResponse); - return (T) processedResponse; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#get(com.microsoft.windowsazure.services.media.entityoperations.EntityGetOperation) - */ - @SuppressWarnings("unchecked") - @Override - public T get(EntityGetOperation getter) throws ServiceException { - getter.setProxyData(createProxyData()); - Object rawResponse = getResource(getter).get(getter.getResponseClass()); - Object processedResponse = getter.processResponse(rawResponse); - return (T) processedResponse; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#list(com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation) - */ - @SuppressWarnings("unchecked") - @Override - public ListResult list(EntityListOperation lister) throws ServiceException { - lister.setProxyData(createProxyData()); - Object rawResponse = getResource(lister.getUri()).queryParams(lister.getQueryParameters()) - .type(lister.getContentType()).accept(lister.getAcceptType()).get(lister.getResponseGenericType()); - Object processedResponse = lister.processResponse(rawResponse); - return (ListResult) processedResponse; - - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#update(com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation) - */ - @Override - public void update(EntityUpdateOperation updater) throws ServiceException { - updater.setProxyData(createProxyData()); - Object rawResponse = getResource(updater).header("X-HTTP-METHOD", "MERGE").post(ClientResponse.class, - updater.getRequestContents()); - PipelineHelpers.ThrowIfNotSuccess((ClientResponse) rawResponse); - updater.processResponse(rawResponse); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#delete(com.microsoft.windowsazure.services.media.entityoperations.EntityDeleteOperation) - */ - @Override - public void delete(EntityDeleteOperation deleter) throws ServiceException { - deleter.setProxyData(createProxyData()); - getResource(deleter.getUri()).delete(); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#action(com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation) - */ - @Override - public T action(EntityTypeActionOperation entityTypeActionOperation) throws ServiceException { - entityTypeActionOperation.setProxyData(createProxyData()); - Builder webResource = getResource(entityTypeActionOperation.getUri()) - .queryParams(entityTypeActionOperation.getQueryParameters()) - .accept(entityTypeActionOperation.getAcceptType()).accept(MediaType.APPLICATION_XML_TYPE) - .entity(entityTypeActionOperation.getRequestContents(), MediaType.APPLICATION_XML_TYPE); - - ClientResponse clientResponse = webResource.method(entityTypeActionOperation.getVerb(), ClientResponse.class); - return entityTypeActionOperation.processTypeResponse(clientResponse); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#action(com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation) - */ - @Override - public void action(EntityActionOperation entityActionOperation) throws ServiceException { - entityActionOperation.processResponse(getActionClientResponse(entityActionOperation)); - } - - /** - * Gets the action client response. - * - * @param entityActionOperation - * the entity action operation - * @return the action client response - */ - private ClientResponse getActionClientResponse(EntityActionOperation entityActionOperation) { - entityActionOperation.setProxyData(createProxyData()); - Builder webResource = getResource(entityActionOperation.getUri()) - .queryParams(entityActionOperation.getQueryParameters()).accept(entityActionOperation.getAcceptType()) - .accept(MediaType.APPLICATION_XML_TYPE) - .entity(entityActionOperation.getRequestContents(), MediaType.APPLICATION_XML_TYPE); - return webResource.method(entityActionOperation.getVerb(), ClientResponse.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobContainerWriter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobContainerWriter.java deleted file mode 100644 index 87c4f66dde5e4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobContainerWriter.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import java.io.InputStream; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.blob.implementation.BlobExceptionProcessor; -import com.microsoft.windowsazure.services.blob.models.BlockList; -import com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; -import com.sun.jersey.api.client.Client; - -/** - * Implementation of WritableBlobContainerContract, used to upload blobs to the - * Media Services storage. - * - */ -public class MediaBlobContainerWriter implements WritableBlobContainerContract { - - private final BlobContract blobService; - private final BlobContract restProxy; - private final String containerName; - - /** - * - */ - public MediaBlobContainerWriter(Client client, String accountName, String blobServiceUri, String containerName, - String sasToken) { - this.containerName = containerName; - this.restProxy = new MediaBlobRestProxy(client, accountName, blobServiceUri, new SASTokenFilter(sasToken)); - this.blobService = new BlobExceptionProcessor(this.restProxy); - } - - private MediaBlobContainerWriter(MediaBlobContainerWriter baseWriter, ServiceFilter filter) { - this.containerName = baseWriter.containerName; - this.restProxy = baseWriter.restProxy.withFilter(filter); - this.blobService = new BlobExceptionProcessor(this.restProxy); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.FilterableService#withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) - */ - @Override - public WritableBlobContainerContract withFilter(ServiceFilter filter) { - return new MediaBlobContainerWriter(this, filter); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.WritableBlobContainerContract#createBlockBlob(java.lang.String, java.io.InputStream) - */ - @Override - public CreateBlobResult createBlockBlob(String blob, InputStream contentStream) throws ServiceException { - return blobService.createBlockBlob(containerName, blob, contentStream); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.WritableBlobContainerContract#createBlockBlob(java.lang.String, java.io.InputStream, com.microsoft.windowsazure.services.blob.models.CreateBlobOptions) - */ - @Override - public CreateBlobResult createBlockBlob(String blob, InputStream contentStream, CreateBlobOptions options) - throws ServiceException { - return blobService.createBlockBlob(containerName, blob, contentStream, options); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.WritableBlobContainerContract#createBlobBlock(java.lang.String, java.lang.String, java.io.InputStream) - */ - @Override - public void createBlobBlock(String blob, String blockId, InputStream contentStream) throws ServiceException { - blobService.createBlobBlock(containerName, blob, blockId, contentStream); - - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.WritableBlobContainerContract#createBlobBlock(java.lang.String, java.lang.String, java.io.InputStream, com.microsoft.windowsazure.services.blob.models.CreateBlobBlockOptions) - */ - @Override - public void createBlobBlock(String blob, String blockId, InputStream contentStream, CreateBlobBlockOptions options) - throws ServiceException { - blobService.createBlobBlock(containerName, blob, blockId, contentStream, options); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.WritableBlobContainerContract#commitBlobBlocks(java.lang.String, com.microsoft.windowsazure.services.blob.models.BlockList) - */ - @Override - public void commitBlobBlocks(String blob, BlockList blockList) throws ServiceException { - blobService.commitBlobBlocks(containerName, blob, blockList); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.WritableBlobContainerContract#commitBlobBlocks(java.lang.String, com.microsoft.windowsazure.services.blob.models.BlockList, com.microsoft.windowsazure.services.blob.models.CommitBlobBlocksOptions) - */ - @Override - public void commitBlobBlocks(String blob, BlockList blockList, CommitBlobBlocksOptions options) - throws ServiceException { - blobService.commitBlobBlocks(containerName, blob, blockList, options); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobRestProxy.java deleted file mode 100644 index a698b280f7ce9..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaBlobRestProxy.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import java.util.Arrays; - -import com.microsoft.windowsazure.services.blob.BlobContract; -import com.microsoft.windowsazure.services.blob.implementation.BlobOperationRestProxy; -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.sun.jersey.api.client.Client; - -/** - * Rest proxy for blob operations that's specialized for working - * with the blobs created by and for Media Services storage. - * - */ -class MediaBlobRestProxy extends BlobOperationRestProxy { - private final SASTokenFilter tokenFilter; - - /** - * Construct instance of MediaBlobRestProxy with given parameters. - * - * @param channel - * Jersey Client object used to communicate with blob service - * @param accountName - * Account name for blob storage - * @param url - * URL for blob storage - * @param tokenFilter - * filter used to add SAS tokens to requests. - */ - public MediaBlobRestProxy(Client channel, String accountName, String url, SASTokenFilter tokenFilter) { - super(channel, accountName, url); - - this.tokenFilter = tokenFilter; - channel.addFilter(tokenFilter); - } - - /** - * Construct instance of MediaBlobRestProxy with given parameters. - * - * @param channel - * Jersey Client object used to communicate with blob service - * @param filters - * Additional ServiceFilters to manipulate requests and responses - * @param accountName - * Account name for blob storage - * @param url - * URL for blob storage - * @param dateMapper - * date conversion helper object - */ - public MediaBlobRestProxy(Client channel, ServiceFilter[] filters, String accountName, String url, - SASTokenFilter tokenFilter, RFC1123DateConverter dateMapper) { - super(channel, filters, accountName, url, dateMapper); - - this.tokenFilter = tokenFilter; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.blob.implementation.BlobOperationRestProxy#withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) - */ - @Override - public BlobContract withFilter(ServiceFilter filter) { - ServiceFilter[] currentFilters = getFilters(); - ServiceFilter[] newFilters = Arrays.copyOf(currentFilters, currentFilters.length + 1); - newFilters[currentFilters.length] = filter; - return new MediaBlobRestProxy(getChannel(), newFilters, getAccountName(), getUrl(), this.tokenFilter, - getDateMapper()); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaContentProvider.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaContentProvider.java deleted file mode 100644 index eae063529e67d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaContentProvider.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - -import com.microsoft.windowsazure.services.media.implementation.content.MediaServiceDTO; -import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; - -/** - * Class to plug into Jersey to properly serialize - * raw Media Services DTO types. - * - */ -public class MediaContentProvider extends AbstractMessageReaderWriterProvider { - private final ODataAtomMarshaller marshaller; - - /** - * Creates the instance - * - * @throws JAXBException - * @throws ParserConfigurationException - */ - public MediaContentProvider() throws JAXBException, ParserConfigurationException { - marshaller = new ODataAtomMarshaller(); - } - - @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - // This class only does marshalling, not unmarshalling. - return false; - } - - @Override - public T readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return MediaServiceDTO.class.isAssignableFrom(type); - } - - @Override - public void writeTo(T t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { - try { - marshaller.marshalEntry(t, entityStream); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaExceptionProcessor.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaExceptionProcessor.java deleted file mode 100644 index cc2808e7bdc69..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaExceptionProcessor.java +++ /dev/null @@ -1,216 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import javax.inject.Inject; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.microsoft.windowsazure.services.media.MediaContract; -import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; -import com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation; -import com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation; -import com.microsoft.windowsazure.services.media.entityoperations.EntityDeleteOperation; -import com.microsoft.windowsazure.services.media.entityoperations.EntityGetOperation; -import com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation; -import com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation; -import com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.UniformInterfaceException; - -/** - * /** - * Wrapper implementation of MediaEntityContract that - * translates exceptions into ServiceExceptions. - * - */ -public class MediaExceptionProcessor implements MediaContract { - - /** The service. */ - private final MediaContract service; - - /** The log. */ - private static Log log = LogFactory.getLog(MediaContract.class); - - /** - * Instantiates a new media exception processor. - * - * @param service - * the service - */ - public MediaExceptionProcessor(MediaContract service) { - this.service = service; - } - - /** - * Instantiates a new media exception processor. - * - * @param service - * the service - */ - @Inject - public MediaExceptionProcessor(MediaRestProxy service) { - this.service = service; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.FilterableService#withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) - */ - @Override - public MediaContract withFilter(ServiceFilter filter) { - return new MediaExceptionProcessor(service.withFilter(filter)); - } - - /** - * Process a catch. - * - * @param e - * the e - * @return the service exception - */ - private ServiceException processCatch(ServiceException e) { - log.warn(e.getMessage(), e.getCause()); - return ServiceExceptionFactory.process("MediaServices", e); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#create(com.microsoft.windowsazure.services.media.entityoperations.EntityCreateOperation) - */ - @Override - public T create(EntityCreateOperation creator) throws ServiceException { - try { - return service.create(creator); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#get(com.microsoft.windowsazure.services.media.entityoperations.EntityGetOperation) - */ - @Override - public T get(EntityGetOperation getter) throws ServiceException { - try { - return service.get(getter); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#list(com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation) - */ - @Override - public ListResult list(EntityListOperation lister) throws ServiceException { - try { - return service.list(lister); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#update(com.microsoft.windowsazure.services.media.entityoperations.EntityUpdateOperation) - */ - @Override - public void update(EntityUpdateOperation updater) throws ServiceException { - try { - service.update(updater); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#delete(com.microsoft.windowsazure.services.media.entityoperations.EntityDeleteOperation) - */ - @Override - public void delete(EntityDeleteOperation deleter) throws ServiceException { - try { - service.delete(deleter); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#action(com.microsoft.windowsazure.services.media.entityoperations.EntityActionOperation) - */ - @Override - public void action(EntityActionOperation entityActionOperation) throws ServiceException { - try { - service.action(entityActionOperation); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityContract#action(com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation) - */ - @Override - public T action(EntityTypeActionOperation entityTypeActionOperation) throws ServiceException { - try { - return service.action(entityTypeActionOperation); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.MediaContract#createBlobWriter(com.microsoft.windowsazure.services.media.models.LocatorInfo) - */ - @Override - public WritableBlobContainerContract createBlobWriter(LocatorInfo locator) { - return service.createBlobWriter(locator); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaRestProxy.java deleted file mode 100644 index aa756c90f0c83..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/MediaRestProxy.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import java.net.URI; -import java.util.Arrays; - -import javax.inject.Inject; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.pipeline.ClientConfigSettings; -import com.microsoft.windowsazure.services.media.MediaContract; -import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; -import com.microsoft.windowsazure.services.media.entityoperations.EntityProxyData; -import com.microsoft.windowsazure.services.media.entityoperations.EntityRestProxy; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; -import com.microsoft.windowsazure.services.media.models.LocatorType; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; - -/** - * The Class MediaRestProxy. - */ -public class MediaRestProxy extends EntityRestProxy implements MediaContract { - /** The log. */ - static Log log = LogFactory.getLog(MediaContract.class); - - /** The redirect filter. */ - private RedirectFilter redirectFilter; - - private final ClientConfigSettings clientConfigSettings; - - /** - * Instantiates a new media rest proxy. - * - * @param channel - * the channel - * @param authFilter - * the auth filter - * @param redirectFilter - * the redirect filter - * @param versionHeadersFilter - * the version headers filter - * @param userAgentFilter - * the user agent filter - * @param clientConfigSettings - * Currently configured HTTP client settings - * - */ - @Inject - public MediaRestProxy(Client channel, OAuthFilter authFilter, RedirectFilter redirectFilter, - VersionHeadersFilter versionHeadersFilter, UserAgentFilter userAgentFilter, - ClientConfigSettings clientConfigSettings) { - super(channel, new ServiceFilter[0]); - - this.clientConfigSettings = clientConfigSettings; - this.redirectFilter = redirectFilter; - channel.addFilter(redirectFilter); - channel.addFilter(authFilter); - channel.addFilter(versionHeadersFilter); - channel.addFilter(userAgentFilter); - } - - /** - * Instantiates a new media rest proxy. - * - * @param channel - * the channel - * @param filters - * the filters - * @param clientConfigSettings - * currently configured HTTP client settings - */ - private MediaRestProxy(Client channel, ServiceFilter[] filters, ClientConfigSettings clientConfigSettings) { - super(channel, filters); - this.clientConfigSettings = clientConfigSettings; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.FilterableService#withFilter(com.microsoft.windowsazure.services.core.ServiceFilter) - */ - @Override - public MediaContract withFilter(ServiceFilter filter) { - ServiceFilter[] filters = getFilters(); - ServiceFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1); - newFilters[filters.length] = filter; - return new MediaRestProxy(getChannel(), newFilters, clientConfigSettings); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.EntityRestProxy#createProxyData() - */ - @Override - protected EntityProxyData createProxyData() { - return new EntityProxyData() { - @Override - public URI getServiceUri() { - return redirectFilter.getBaseURI(); - } - }; - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.MediaContract#createBlobWriter(com.microsoft.windowsazure.services.media.models.LocatorInfo) - */ - @Override - public WritableBlobContainerContract createBlobWriter(LocatorInfo locator) { - if (locator.getLocatorType() != LocatorType.SAS) { - throw new IllegalArgumentException("Can only write to SAS locators"); - } - - LocatorParser p = new LocatorParser(locator); - - return new MediaBlobContainerWriter(createUploaderClient(), p.getAccountName(), p.getStorageUri(), - p.getContainer(), p.getSASToken()); - } - - /** - * Helper class to encapsulate pulling information out of the locator. - */ - private static class LocatorParser { - URI locatorPath; - - LocatorParser(LocatorInfo locator) { - locatorPath = URI.create(locator.getPath()); - } - - String getAccountName() { - return locatorPath.getHost().split("\\.")[0]; - } - - String getStorageUri() { - return locatorPath.getScheme() + "://" + locatorPath.getAuthority(); - } - - String getContainer() { - return locatorPath.getPath().substring(1); - } - - String getSASToken() { - return locatorPath.getRawQuery(); - } - } - - private Client createUploaderClient() { - ClientConfig clientConfig = new DefaultClientConfig(); - clientConfigSettings.applyConfig(clientConfig); - Client client = Client.create(clientConfig); - clientConfigSettings.applyConfig(client); - return client; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxy.java deleted file mode 100644 index 77bc0ce745896..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxy.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.media.implementation; - -import java.io.IOException; -import java.net.URI; - -import javax.inject.Inject; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.type.TypeReference; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.representation.Form; - -/** - * The OAuth rest proxy. - * - */ -public class OAuthRestProxy implements OAuthContract { - Client channel; - - private final String grantType = "client_credentials"; - - static Log log = LogFactory.getLog(OAuthContract.class); - - @Inject - public OAuthRestProxy(Client channel, UserAgentFilter userAgentFilter) { - this.channel = channel; - channel.addFilter(userAgentFilter); - } - - /** - * Gets an OAuth access token with specified OAUTH URI, client ID, client secret, and scope. - * - * @param oAuthUri - * A URI object which represents an OAUTH URI. - * - * @param clientId - * A String object which represents a client ID. - * - * @param clientSecret - * A String object which represents a client secret. - * - * @param scope - * A String object which represents the scope. - * - * @return OAuthTokenResponse - * @throws ServiceException - */ - @Override - public OAuthTokenResponse getAccessToken(URI oAuthUri, String clientId, String clientSecret, String scope) - throws ServiceException { - OAuthTokenResponse response = null; - Form requestForm = new Form(); - ClientResponse clientResponse; - String responseJson; - - requestForm.add("grant_type", grantType); - requestForm.add("client_id", clientId); - requestForm.add("client_secret", clientSecret); - requestForm.add("scope", scope); - - try { - clientResponse = channel.resource(oAuthUri).accept(MediaType.APPLICATION_FORM_URLENCODED) - .type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, requestForm); - } - catch (UniformInterfaceException e) { - log.warn("OAuth server returned error acquiring access_token", e); - throw ServiceExceptionFactory.process("OAuth", new ServiceException( - "OAuth server returned error acquiring access_token", e)); - } - - responseJson = clientResponse.getEntity(String.class); - - try { - ObjectMapper mapper = new ObjectMapper(); - TypeReference typeReference = new TypeReference() { - }; - response = mapper.readValue(responseJson, typeReference); - } - catch (JsonParseException e) { - log.warn("The response from OAuth server cannot be parsed correctly", e); - throw ServiceExceptionFactory.process("OAuth", new ServiceException( - "The response from OAuth server cannot be parsed correctly", e)); - } - catch (JsonMappingException e) { - log.warn("The response from OAuth server cannot be mapped to OAuthResponse object", e); - throw ServiceExceptionFactory.process("OAuth", new ServiceException( - "The response from OAuth server cannot be mapped to OAuthResponse object", e)); - } - catch (IOException e) { - log.warn("Cannot map the response from OAuth server correctly.", e); - throw ServiceExceptionFactory.process("OAuth", new ServiceException( - "Cannot map the response from OAuth server correctly.", e)); - } - - return response; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityCollectionProvider.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityCollectionProvider.java deleted file mode 100644 index 1a63e2f3c99e3..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityCollectionProvider.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.xml.bind.JAXBException; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; - -/** - * Jersey provider to unmarshal lists of entities from Media Services. - * - */ -public class ODataEntityCollectionProvider extends AbstractMessageReaderWriterProvider>> { - private final ODataAtomUnmarshaller unmarshaller; - - public ODataEntityCollectionProvider() throws JAXBException { - unmarshaller = new ODataAtomUnmarshaller(); - } - - @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return ODataEntity.isODataEntityCollectionType(type, genericType); - } - - @SuppressWarnings("unchecked") - @Override - public ListResult> readFrom(Class>> type, Type genericType, - Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, - InputStream entityStream) throws IOException { - - String responseType = mediaType.getParameters().get("type"); - try { - if (responseType == null || responseType.equals("feed")) { - return unmarshaller.unmarshalFeed(entityStream, - (Class>) ODataEntity.getCollectedType(genericType)); - } - else { - throw new RuntimeException(); - } - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - catch (ServiceException e) { - throw new RuntimeException(e); - } - } - - /** - * Can this type be written by this provider? - * - * @return false - we don't support writing - */ - @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return false; - } - - /** - * Write the given object to the stream. - * This method implementation throws, we don't support writing. - * - * @throws UnsupportedOperationException - */ - @Override - public void writeTo(ListResult> t, Class type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws IOException { - - throw new UnsupportedOperationException(); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityProvider.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityProvider.java deleted file mode 100644 index c879f1e5ee947..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/ODataEntityProvider.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.List; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; - -/** - * An implementation of {@link AbstractMessageReaderWriterProvider } that - * is used to marshal and unmarshal instances of the ODataEntity type. - * - */ -public class ODataEntityProvider extends AbstractMessageReaderWriterProvider> { - private final ODataAtomUnmarshaller unmarshaller; - - public ODataEntityProvider() throws JAXBException, ParserConfigurationException { - unmarshaller = new ODataAtomUnmarshaller(); - } - - /* (non-Javadoc) - * @see javax.ws.rs.ext.MessageBodyReader#isReadable(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) - */ - @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return ODataEntity.isODataEntityType(type); - } - - /* (non-Javadoc) - * @see javax.ws.rs.ext.MessageBodyReader#readFrom(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, java.io.InputStream) - */ - @Override - public ODataEntity readFrom(Class> type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException { - - ODataEntity result = null; - String responseType = mediaType.getParameters().get("type"); - try { - if (responseType == null || responseType.equals("feed")) { - List> feedContents = unmarshaller.unmarshalFeed(entityStream, type); - return feedContents.get(0); - } - else if (responseType.equals("entry")) { - result = unmarshaller.unmarshalEntry(entityStream, type); - } - else { - throw new RuntimeException(); - } - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - catch (ServiceException e) { - throw new RuntimeException(e); - } - - return result; - } - - /* (non-Javadoc) - * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) - */ - @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return false; - } - - /* (non-Javadoc) - * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(java.lang.Object, java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, java.io.OutputStream) - */ - @Override - public void writeTo(ODataEntity t, Class type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws IOException { - throw new UnsupportedOperationException(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/VersionHeadersFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/VersionHeadersFilter.java deleted file mode 100644 index 80ebd577cce34..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/VersionHeadersFilter.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import javax.ws.rs.core.MultivaluedMap; - -import com.microsoft.windowsazure.services.core.IdempotentClientFilter; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; - -/** - * A small filter that adds the required Media services/OData 3 - * version headers to the request as it goes through. - * - */ -public class VersionHeadersFilter extends IdempotentClientFilter { - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.IdempotentClientFilter#doHandle(com.sun.jersey.api.client.ClientRequest) - */ - @Override - public ClientResponse doHandle(ClientRequest cr) { - MultivaluedMap headers = cr.getHeaders(); - headers.add("DataServiceVersion", "3.0"); - headers.add("MaxDataServiceVersion", "3.0"); - headers.add("x-ms-version", "2.2"); - return getNext().handle(cr); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ContentType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ContentType.java deleted file mode 100644 index d828ce6a922e0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ContentType.java +++ /dev/null @@ -1,240 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlMixed; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom content construct is defined in section 4.1.3 of the format spec. - * - * - *

Java class for contentType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="contentType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <attribute name="src" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
- *       <anyAttribute namespace='##other'/>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "contentType", propOrder = { - "content" -}) -public class ContentType { - - @XmlMixed - @XmlAnyElement(lax = true) - protected List content; - @XmlAttribute - protected String type; - @XmlAttribute - @XmlSchemaType(name = "anyURI") - protected String src; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * - * The Atom content construct is defined in section 4.1.3 of the format spec. - * Gets the value of the content property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the content property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getContent().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Object } - * {@link String } - * - * - */ - public List getContent() { - if (content == null) { - content = new ArrayList(); - } - return this.content; - } - - /** - * Gets the value of the type property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getType() { - return type; - } - - /** - * Sets the value of the type property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setType(String value) { - this.type = value; - } - - /** - * Gets the value of the src property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSrc() { - return src; - } - - /** - * Sets the value of the src property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSrc(String value) { - this.src = value; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/EntryType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/EntryType.java deleted file mode 100644 index 6b391b9cdd087..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/EntryType.java +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom entry construct is defined in section 4.1.2 of the format spec. - * - * - *

Java class for entryType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="entryType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <choice maxOccurs="unbounded">
- *         <element name="author" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="category" type="{http://www.w3.org/2005/Atom}categoryType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="content" type="{http://www.w3.org/2005/Atom}contentType" minOccurs="0"/>
- *         <element name="contributor" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="id" type="{http://www.w3.org/2005/Atom}idType"/>
- *         <element name="link" type="{http://www.w3.org/2005/Atom}linkType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="published" type="{http://www.w3.org/2005/Atom}dateTimeType" minOccurs="0"/>
- *         <element name="rights" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="source" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="summary" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="title" type="{http://www.w3.org/2005/Atom}textType"/>
- *         <element name="updated" type="{http://www.w3.org/2005/Atom}dateTimeType"/>
- *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
- *       </choice>
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <anyAttribute namespace='##other'/>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "entryType", propOrder = { - "entryChildren" -}) -public class EntryType { - - @XmlElementRefs({ - @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "published", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "summary", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "source", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "content", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) - }) - @XmlAnyElement(lax = true) - protected List entryChildren; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * Gets the value of the entryChildren property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the entryChildren property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getEntryChildren().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link CategoryType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link PersonType }{@code >} - * {@link JAXBElement }{@code <}{@link LinkType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link PersonType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link IdType }{@code >} - * {@link JAXBElement }{@code <}{@link ContentType }{@code >} - * {@link Object } - * - * - */ - public List getEntryChildren() { - if (entryChildren == null) { - entryChildren = new ArrayList(); - } - return this.entryChildren; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/FeedType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/FeedType.java deleted file mode 100644 index 38d8fd73331b4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/FeedType.java +++ /dev/null @@ -1,224 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.18 at 11:05:53 AM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom feed construct is defined in section 4.1.1 of the format spec. - * - * - *

Java class for feedType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="feedType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <choice maxOccurs="unbounded" minOccurs="3">
- *         <element name="author" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="category" type="{http://www.w3.org/2005/Atom}categoryType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="contributor" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="generator" type="{http://www.w3.org/2005/Atom}generatorType" minOccurs="0"/>
- *         <element name="icon" type="{http://www.w3.org/2005/Atom}iconType" minOccurs="0"/>
- *         <element name="id" type="{http://www.w3.org/2005/Atom}idType"/>
- *         <element name="link" type="{http://www.w3.org/2005/Atom}linkType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="logo" type="{http://www.w3.org/2005/Atom}logoType" minOccurs="0"/>
- *         <element name="rights" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="subtitle" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="title" type="{http://www.w3.org/2005/Atom}textType"/>
- *         <element name="updated" type="{http://www.w3.org/2005/Atom}dateTimeType"/>
- *         <element name="entry" type="{http://www.w3.org/2005/Atom}entryType" maxOccurs="unbounded" minOccurs="0"/>
- *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
- *       </choice>
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <anyAttribute namespace='##other'/>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "feedType", propOrder = { - "feedChildren" -}) -public class FeedType { - - @XmlElementRefs({ - @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "entry", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) - }) - @XmlAnyElement(lax = true) - protected List feedChildren; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * Gets the value of the feedChildren property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the feedChildren property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getFeedChildren().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link GeneratorType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link IdType }{@code >} - * {@link JAXBElement }{@code <}{@link LinkType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link PersonType }{@code >} - * {@link Object } - * {@link JAXBElement }{@code <}{@link EntryType }{@code >} - * {@link JAXBElement }{@code <}{@link LogoType }{@code >} - * {@link JAXBElement }{@code <}{@link IconType }{@code >} - * {@link JAXBElement }{@code <}{@link PersonType }{@code >} - * {@link JAXBElement }{@code <}{@link CategoryType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * - * - */ - public List getFeedChildren() { - if (feedChildren == null) { - feedChildren = new ArrayList(); - } - return this.feedChildren; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/GeneratorType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/GeneratorType.java deleted file mode 100644 index 884122c1dbe02..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/GeneratorType.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.util.HashMap; -import java.util.Map; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlValue; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom generator element is defined in section 4.2.4 of the format spec. - * - * - *

Java class for generatorType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="generatorType">
- *   <simpleContent>
- *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <attribute name="uri" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
- *       <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <anyAttribute namespace='##other'/>
- *     </extension>
- *   </simpleContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "generatorType", propOrder = { - "value" -}) -public class GeneratorType { - - @XmlValue - protected String value; - @XmlAttribute - @XmlSchemaType(name = "anyURI") - protected String uri; - @XmlAttribute - protected String version; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - - /** - * Gets the value of the uri property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getUri() { - return uri; - } - - /** - * Sets the value of the uri property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setUri(String value) { - this.uri = value; - } - - /** - * Gets the value of the version property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVersion() { - return version; - } - - /** - * Sets the value of the version property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVersion(String value) { - this.version = value; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LinkType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LinkType.java deleted file mode 100644 index 7352cb78504b4..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/LinkType.java +++ /dev/null @@ -1,339 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlValue; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom link construct is defined in section 3.4 of the format spec. - * - * - *

Java class for linkType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="linkType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <attribute name="href" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
- *       <attribute name="rel" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <attribute name="hreflang" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
- *       <attribute name="title" type="{http://www.w3.org/2001/XMLSchema}string" />
- *       <attribute name="length" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" />
- *       <anyAttribute namespace='##other'/>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "linkType", propOrder = { - "content" -}) -public class LinkType { - - @XmlValue - protected String content; - @XmlAttribute(required = true) - @XmlSchemaType(name = "anyURI") - protected String href; - @XmlAttribute - protected String rel; - @XmlAttribute - protected String type; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "NMTOKEN") - protected String hreflang; - @XmlAttribute - protected String title; - @XmlAttribute - @XmlSchemaType(name = "positiveInteger") - protected BigInteger length; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * - * The Atom link construct is defined in section 3.4 of the format spec. - * - * - * @return - * possible object is - * {@link String } - * - */ - public String getContent() { - return content; - } - - /** - * Sets the value of the content property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setContent(String value) { - this.content = value; - } - - /** - * Gets the value of the href property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getHref() { - return href; - } - - /** - * Sets the value of the href property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setHref(String value) { - this.href = value; - } - - /** - * Gets the value of the rel property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRel() { - return rel; - } - - /** - * Sets the value of the rel property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRel(String value) { - this.rel = value; - } - - /** - * Gets the value of the type property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getType() { - return type; - } - - /** - * Sets the value of the type property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setType(String value) { - this.type = value; - } - - /** - * Gets the value of the hreflang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getHreflang() { - return hreflang; - } - - /** - * Sets the value of the hreflang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setHreflang(String value) { - this.hreflang = value; - } - - /** - * Gets the value of the title property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTitle() { - return title; - } - - /** - * Sets the value of the title property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTitle(String value) { - this.title = value; - } - - /** - * Gets the value of the length property. - * - * @return - * possible object is - * {@link BigInteger } - * - */ - public BigInteger getLength() { - return length; - } - - /** - * Sets the value of the length property. - * - * @param value - * allowed object is - * {@link BigInteger } - * - */ - public void setLength(BigInteger value) { - this.length = value; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ObjectFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ObjectFactory.java deleted file mode 100644 index f0e1eb44f3ed1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/ObjectFactory.java +++ /dev/null @@ -1,571 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlElementDecl; -import javax.xml.bind.annotation.XmlRegistry; -import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.microsoft.windowsazure.services.media.implementation.atom package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - private final static QName _Entry_QNAME = new QName("http://www.w3.org/2005/Atom", "entry"); - private final static QName _Feed_QNAME = new QName("http://www.w3.org/2005/Atom", "feed"); - private final static QName _PersonTypeName_QNAME = new QName("http://www.w3.org/2005/Atom", "name"); - private final static QName _PersonTypeEmail_QNAME = new QName("http://www.w3.org/2005/Atom", "email"); - private final static QName _PersonTypeUri_QNAME = new QName("http://www.w3.org/2005/Atom", "uri"); - private final static QName _EntryTypeTitle_QNAME = new QName("http://www.w3.org/2005/Atom", "title"); - private final static QName _EntryTypeCategory_QNAME = new QName("http://www.w3.org/2005/Atom", "category"); - private final static QName _EntryTypeAuthor_QNAME = new QName("http://www.w3.org/2005/Atom", "author"); - private final static QName _EntryTypeSummary_QNAME = new QName("http://www.w3.org/2005/Atom", "summary"); - private final static QName _EntryTypeId_QNAME = new QName("http://www.w3.org/2005/Atom", "id"); - private final static QName _EntryTypeContent_QNAME = new QName("http://www.w3.org/2005/Atom", "content"); - private final static QName _EntryTypeLink_QNAME = new QName("http://www.w3.org/2005/Atom", "link"); - private final static QName _EntryTypeContributor_QNAME = new QName("http://www.w3.org/2005/Atom", "contributor"); - private final static QName _EntryTypeUpdated_QNAME = new QName("http://www.w3.org/2005/Atom", "updated"); - private final static QName _EntryTypeSource_QNAME = new QName("http://www.w3.org/2005/Atom", "source"); - private final static QName _EntryTypeRights_QNAME = new QName("http://www.w3.org/2005/Atom", "rights"); - private final static QName _EntryTypePublished_QNAME = new QName("http://www.w3.org/2005/Atom", "published"); - private final static QName _FeedTypeGenerator_QNAME = new QName("http://www.w3.org/2005/Atom", "generator"); - private final static QName _FeedTypeSubtitle_QNAME = new QName("http://www.w3.org/2005/Atom", "subtitle"); - private final static QName _FeedTypeLogo_QNAME = new QName("http://www.w3.org/2005/Atom", "logo"); - private final static QName _FeedTypeIcon_QNAME = new QName("http://www.w3.org/2005/Atom", "icon"); - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.microsoft.windowsazure.services.media.implementation.atom - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link PersonType } - * - */ - public PersonType createPersonType() { - return new PersonType(); - } - - /** - * Create an instance of {@link EntryType } - * - */ - public EntryType createEntryType() { - return new EntryType(); - } - - /** - * Create an instance of {@link IconType } - * - */ - public IconType createIconType() { - return new IconType(); - } - - /** - * Create an instance of {@link UriType } - * - */ - public UriType createUriType() { - return new UriType(); - } - - /** - * Create an instance of {@link TextType } - * - */ - public TextType createTextType() { - return new TextType(); - } - - /** - * Create an instance of {@link FeedType } - * - */ - public FeedType createFeedType() { - return new FeedType(); - } - - /** - * Create an instance of {@link DateTimeType } - * - */ - public DateTimeType createDateTimeType() { - return new DateTimeType(); - } - - /** - * Create an instance of {@link IdType } - * - */ - public IdType createIdType() { - return new IdType(); - } - - /** - * Create an instance of {@link SourceType } - * - */ - public SourceType createSourceType() { - return new SourceType(); - } - - /** - * Create an instance of {@link LinkType } - * - */ - public LinkType createLinkType() { - return new LinkType(); - } - - /** - * Create an instance of {@link LogoType } - * - */ - public LogoType createLogoType() { - return new LogoType(); - } - - /** - * Create an instance of {@link GeneratorType } - * - */ - public GeneratorType createGeneratorType() { - return new GeneratorType(); - } - - /** - * Create an instance of {@link ContentType } - * - */ - public ContentType createContentType() { - return new ContentType(); - } - - /** - * Create an instance of {@link CategoryType } - * - */ - public CategoryType createCategoryType() { - return new CategoryType(); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link EntryType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "entry") - public JAXBElement createEntry(EntryType value) { - return new JAXBElement(_Entry_QNAME, EntryType.class, null, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link FeedType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "feed") - public JAXBElement createFeed(FeedType value) { - return new JAXBElement(_Feed_QNAME, FeedType.class, null, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "name", scope = PersonType.class) - public JAXBElement createPersonTypeName(String value) { - return new JAXBElement(_PersonTypeName_QNAME, String.class, PersonType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "email", scope = PersonType.class) - @XmlJavaTypeAdapter(NormalizedStringAdapter.class) - public JAXBElement createPersonTypeEmail(String value) { - return new JAXBElement(_PersonTypeEmail_QNAME, String.class, PersonType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link UriType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "uri", scope = PersonType.class) - public JAXBElement createPersonTypeUri(UriType value) { - return new JAXBElement(_PersonTypeUri_QNAME, UriType.class, PersonType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "title", scope = EntryType.class) - public JAXBElement createEntryTypeTitle(TextType value) { - return new JAXBElement(_EntryTypeTitle_QNAME, TextType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CategoryType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "category", scope = EntryType.class) - public JAXBElement createEntryTypeCategory(CategoryType value) { - return new JAXBElement(_EntryTypeCategory_QNAME, CategoryType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link PersonType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "author", scope = EntryType.class) - public JAXBElement createEntryTypeAuthor(PersonType value) { - return new JAXBElement(_EntryTypeAuthor_QNAME, PersonType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "summary", scope = EntryType.class) - public JAXBElement createEntryTypeSummary(TextType value) { - return new JAXBElement(_EntryTypeSummary_QNAME, TextType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link IdType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "id", scope = EntryType.class) - public JAXBElement createEntryTypeId(IdType value) { - return new JAXBElement(_EntryTypeId_QNAME, IdType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link ContentType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "content", scope = EntryType.class) - public JAXBElement createEntryTypeContent(ContentType value) { - return new JAXBElement(_EntryTypeContent_QNAME, ContentType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link LinkType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "link", scope = EntryType.class) - public JAXBElement createEntryTypeLink(LinkType value) { - return new JAXBElement(_EntryTypeLink_QNAME, LinkType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link PersonType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "contributor", scope = EntryType.class) - public JAXBElement createEntryTypeContributor(PersonType value) { - return new JAXBElement(_EntryTypeContributor_QNAME, PersonType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "updated", scope = EntryType.class) - public JAXBElement createEntryTypeUpdated(DateTimeType value) { - return new JAXBElement(_EntryTypeUpdated_QNAME, DateTimeType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "source", scope = EntryType.class) - public JAXBElement createEntryTypeSource(TextType value) { - return new JAXBElement(_EntryTypeSource_QNAME, TextType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "rights", scope = EntryType.class) - public JAXBElement createEntryTypeRights(TextType value) { - return new JAXBElement(_EntryTypeRights_QNAME, TextType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "published", scope = EntryType.class) - public JAXBElement createEntryTypePublished(DateTimeType value) { - return new JAXBElement(_EntryTypePublished_QNAME, DateTimeType.class, EntryType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CategoryType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "category", scope = FeedType.class) - public JAXBElement createFeedTypeCategory(CategoryType value) { - return new JAXBElement(_EntryTypeCategory_QNAME, CategoryType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "title", scope = FeedType.class) - public JAXBElement createFeedTypeTitle(TextType value) { - return new JAXBElement(_EntryTypeTitle_QNAME, TextType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link PersonType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "author", scope = FeedType.class) - public JAXBElement createFeedTypeAuthor(PersonType value) { - return new JAXBElement(_EntryTypeAuthor_QNAME, PersonType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link IdType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "id", scope = FeedType.class) - public JAXBElement createFeedTypeId(IdType value) { - return new JAXBElement(_EntryTypeId_QNAME, IdType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link EntryType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "entry", scope = FeedType.class) - public JAXBElement createFeedTypeEntry(EntryType value) { - return new JAXBElement(_Entry_QNAME, EntryType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link PersonType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "contributor", scope = FeedType.class) - public JAXBElement createFeedTypeContributor(PersonType value) { - return new JAXBElement(_EntryTypeContributor_QNAME, PersonType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "updated", scope = FeedType.class) - public JAXBElement createFeedTypeUpdated(DateTimeType value) { - return new JAXBElement(_EntryTypeUpdated_QNAME, DateTimeType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link GeneratorType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "generator", scope = FeedType.class) - public JAXBElement createFeedTypeGenerator(GeneratorType value) { - return new JAXBElement(_FeedTypeGenerator_QNAME, GeneratorType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "subtitle", scope = FeedType.class) - public JAXBElement createFeedTypeSubtitle(TextType value) { - return new JAXBElement(_FeedTypeSubtitle_QNAME, TextType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link LogoType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "logo", scope = FeedType.class) - public JAXBElement createFeedTypeLogo(LogoType value) { - return new JAXBElement(_FeedTypeLogo_QNAME, LogoType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link IconType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "icon", scope = FeedType.class) - public JAXBElement createFeedTypeIcon(IconType value) { - return new JAXBElement(_FeedTypeIcon_QNAME, IconType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link LinkType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "link", scope = FeedType.class) - public JAXBElement createFeedTypeLink(LinkType value) { - return new JAXBElement(_EntryTypeLink_QNAME, LinkType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "rights", scope = FeedType.class) - public JAXBElement createFeedTypeRights(TextType value) { - return new JAXBElement(_EntryTypeRights_QNAME, TextType.class, FeedType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "title", scope = SourceType.class) - public JAXBElement createSourceTypeTitle(TextType value) { - return new JAXBElement(_EntryTypeTitle_QNAME, TextType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CategoryType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "category", scope = SourceType.class) - public JAXBElement createSourceTypeCategory(CategoryType value) { - return new JAXBElement(_EntryTypeCategory_QNAME, CategoryType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link IconType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "icon", scope = SourceType.class) - public JAXBElement createSourceTypeIcon(IconType value) { - return new JAXBElement(_FeedTypeIcon_QNAME, IconType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link PersonType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "author", scope = SourceType.class) - public JAXBElement createSourceTypeAuthor(PersonType value) { - return new JAXBElement(_EntryTypeAuthor_QNAME, PersonType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link LogoType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "logo", scope = SourceType.class) - public JAXBElement createSourceTypeLogo(LogoType value) { - return new JAXBElement(_FeedTypeLogo_QNAME, LogoType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link IdType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "id", scope = SourceType.class) - public JAXBElement createSourceTypeId(IdType value) { - return new JAXBElement(_EntryTypeId_QNAME, IdType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link LinkType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "link", scope = SourceType.class) - public JAXBElement createSourceTypeLink(LinkType value) { - return new JAXBElement(_EntryTypeLink_QNAME, LinkType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link PersonType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "contributor", scope = SourceType.class) - public JAXBElement createSourceTypeContributor(PersonType value) { - return new JAXBElement(_EntryTypeContributor_QNAME, PersonType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link DateTimeType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "updated", scope = SourceType.class) - public JAXBElement createSourceTypeUpdated(DateTimeType value) { - return new JAXBElement(_EntryTypeUpdated_QNAME, DateTimeType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link GeneratorType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "generator", scope = SourceType.class) - public JAXBElement createSourceTypeGenerator(GeneratorType value) { - return new JAXBElement(_FeedTypeGenerator_QNAME, GeneratorType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "rights", scope = SourceType.class) - public JAXBElement createSourceTypeRights(TextType value) { - return new JAXBElement(_EntryTypeRights_QNAME, TextType.class, SourceType.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link TextType }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://www.w3.org/2005/Atom", name = "subtitle", scope = SourceType.class) - public JAXBElement createSourceTypeSubtitle(TextType value) { - return new JAXBElement(_FeedTypeSubtitle_QNAME, TextType.class, SourceType.class, value); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/PersonType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/PersonType.java deleted file mode 100644 index b2899d730913e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/PersonType.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom person construct is defined in section 3.2 of the format spec. - * - * - *

Java class for personType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="personType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <choice maxOccurs="unbounded">
- *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="uri" type="{http://www.w3.org/2005/Atom}uriType" minOccurs="0"/>
- *         <element name="email" type="{http://www.w3.org/2005/Atom}emailType" minOccurs="0"/>
- *         <any namespace='##other'/>
- *       </choice>
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <anyAttribute namespace='##other'/>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "personType", propOrder = { - "nameOrUriOrEmail" -}) -public class PersonType { - - @XmlElementRefs({ - @XmlElementRef(name = "email", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "uri", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "name", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) - }) - @XmlAnyElement(lax = true) - protected List nameOrUriOrEmail; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * Gets the value of the nameOrUriOrEmail property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the nameOrUriOrEmail property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getNameOrUriOrEmail().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link String }{@code >} - * {@link Object } - * {@link JAXBElement }{@code <}{@link String }{@code >} - * {@link JAXBElement }{@code <}{@link UriType }{@code >} - * - * - */ - public List getNameOrUriOrEmail() { - if (nameOrUriOrEmail == null) { - nameOrUriOrEmail = new ArrayList(); - } - return this.nameOrUriOrEmail; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/SourceType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/SourceType.java deleted file mode 100644 index db8dcc0b393f7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/SourceType.java +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom source construct is defined in section 4.2.11 of the format spec. - * - * - *

Java class for sourceType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="sourceType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <choice maxOccurs="unbounded">
- *         <element name="author" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="category" type="{http://www.w3.org/2005/Atom}categoryType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="contributor" type="{http://www.w3.org/2005/Atom}personType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="generator" type="{http://www.w3.org/2005/Atom}generatorType" minOccurs="0"/>
- *         <element name="icon" type="{http://www.w3.org/2005/Atom}iconType" minOccurs="0"/>
- *         <element name="id" type="{http://www.w3.org/2005/Atom}idType" minOccurs="0"/>
- *         <element name="link" type="{http://www.w3.org/2005/Atom}linkType" maxOccurs="unbounded" minOccurs="0"/>
- *         <element name="logo" type="{http://www.w3.org/2005/Atom}logoType" minOccurs="0"/>
- *         <element name="rights" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="subtitle" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="title" type="{http://www.w3.org/2005/Atom}textType" minOccurs="0"/>
- *         <element name="updated" type="{http://www.w3.org/2005/Atom}dateTimeType" minOccurs="0"/>
- *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
- *       </choice>
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <anyAttribute namespace='##other'/>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "sourceType", propOrder = { - "authorOrCategoryOrContributor" -}) -public class SourceType { - - @XmlElementRefs({ - @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), - @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) - }) - @XmlAnyElement(lax = true) - protected List authorOrCategoryOrContributor; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * Gets the value of the authorOrCategoryOrContributor property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the authorOrCategoryOrContributor property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAuthorOrCategoryOrContributor().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link PersonType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link PersonType }{@code >} - * {@link JAXBElement }{@code <}{@link GeneratorType }{@code >} - * {@link JAXBElement }{@code <}{@link LogoType }{@code >} - * {@link JAXBElement }{@code <}{@link IdType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * {@link JAXBElement }{@code <}{@link DateTimeType }{@code >} - * {@link JAXBElement }{@code <}{@link CategoryType }{@code >} - * {@link Object } - * {@link JAXBElement }{@code <}{@link IconType }{@code >} - * {@link JAXBElement }{@code <}{@link LinkType }{@code >} - * {@link JAXBElement }{@code <}{@link TextType }{@code >} - * - * - */ - public List getAuthorOrCategoryOrContributor() { - if (authorOrCategoryOrContributor == null) { - authorOrCategoryOrContributor = new ArrayList(); - } - return this.authorOrCategoryOrContributor; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/TextType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/TextType.java deleted file mode 100644 index e9804d1ae3cd9..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/atom/TextType.java +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.09.17 at 02:31:28 PM PDT -// - - -package com.microsoft.windowsazure.services.media.implementation.atom; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyAttribute; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlMixed; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import javax.xml.namespace.QName; - - -/** - * - * The Atom text construct is defined in section 3.1 of the format spec. - * - * - *

Java class for textType complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="textType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <any namespace='http://www.w3.org/1999/xhtml' minOccurs="0"/>
- *       </sequence>
- *       <attGroup ref="{http://www.w3.org/2005/Atom}commonAttributes"/>
- *       <attribute name="type">
- *         <simpleType>
- *           <restriction base="{http://www.w3.org/2001/XMLSchema}token">
- *             <enumeration value="text"/>
- *             <enumeration value="html"/>
- *             <enumeration value="xhtml"/>
- *           </restriction>
- *         </simpleType>
- *       </attribute>
- *       <anyAttribute namespace='##other'/>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "textType", propOrder = { - "content" -}) -public class TextType { - - @XmlMixed - @XmlAnyElement(lax = true) - protected List content; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String type; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anyURI") - protected String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "language") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * - * The Atom text construct is defined in section 3.1 of the format spec. - * Gets the value of the content property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the content property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getContent().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Object } - * {@link String } - * - * - */ - public List getContent() { - if (content == null) { - content = new ArrayList(); - } - return this.content; - } - - /** - * Gets the value of the type property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getType() { - return type; - } - - /** - * Sets the value of the type property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setType(String value) { - this.type = value; - } - - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getBase() { - return base; - } - - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } - - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } - - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/Constants.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/Constants.java deleted file mode 100644 index a6e75b29512a0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/Constants.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation.content; - -import javax.xml.namespace.QName; - -/** - * This class provides a set of constants for element names - * and namespaces used throughout the serialization of - * media services entities. - */ - -public final class Constants { - - private Constants() { - } - - /** - * XML Namespace for Atom syndication format, as defined by IETF RFC 4287 - */ - public static final String ATOM_NS = "http://www.w3.org/2005/Atom"; - - /** - * XML Namespace for OData data as serialized inside Atom syndication format. - */ - public static final String ODATA_DATA_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices"; - - /** - * XML Namespace for OData metadata as serialized inside Atom syndication format. - */ - public static final String ODATA_METADATA_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; - - /** - * EDM namespace for Azure Media Services entities, as defined in Media Services EDMX file. - */ - public static final String MEDIA_SERVICES_EDM_NAMESPACE = "Microsoft.Cloud.Media.Vod.Rest.Data.Models"; - - /** - * Element name for Atom content element, including namespace - */ - public static final QName ATOM_CONTENT_ELEMENT_NAME = new QName("content", ATOM_NS); - - /** - * Element name for OData action elements, including namespace - */ - public static final QName ODATA_ACTION_ELEMENT_NAME = new QName("action", ODATA_METADATA_NS); - - /** - * Element name for the metadata properties element, including namespace. - */ - public static final QName ODATA_PROPERTIES_ELEMENT_NAME = new QName("properties", ODATA_METADATA_NS); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ObjectFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ObjectFactory.java deleted file mode 100644 index ae260c170fb33..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/implementation/content/ObjectFactory.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation.content; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * Class used by JAXB to instantiate the types in this package. - * - */ -@XmlRegistry -public class ObjectFactory { - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: - * com.microsoft.windowsazure.services.media.implementation.atom - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link AssetType }. - * - * @return a new AssetType instance. - */ - public AssetType createAssetType() { - return new AssetType(); - } - - /** - * Create an instance of {@link ODataActionType }. - * - * @return a new ODataActionType instance. - */ - public ODataActionType createODataActionType() { - return new ODataActionType(); - } - - /** - * Create an instance of {@link AccessPolicyType }. - * - * @return a new AccessPolicyType instance. - */ - public AccessPolicyType createAccessPolicyType() { - return new AccessPolicyType(); - } - - /** - * Create an instance of {@link LocatorRestType }. - * - * @return a new LocatorRestType instance. - */ - public LocatorRestType createLocatorRestType() { - return new LocatorRestType(); - } - - /** - * Create an instance of {@link MediaProcessorType }. - * - * @return a new MediaProcessorType instance. - */ - public MediaProcessorType createMediaProcessorType() { - return new MediaProcessorType(); - } - - /** - * Create an instance of {@link JobType}. - * - * @return a new JobType instance. - */ - public JobType createJobType() { - return new JobType(); - } - - /** - * Create an instance of {@link TaskType}. - * - * @return a new TaskType instance. - */ - public TaskType createTaskType() { - return new TaskType(); - } - - /** - * Creates a new Object object. - * - * @return the content key rest type - */ - public ContentKeyRestType createContentKeyRestType() { - return new ContentKeyRestType(); - } - - /** - * Create an instance of {@link AssetFileType}. - * - * @return a new AssetFileType instance. - */ - public AssetFileType createAssetFileType() { - return new AssetFileType(); - } - - /** - * Creates an instance of (@link RebindContentKeyType). - * - * @return the rebind content key type instance. - */ - public RebindContentKeyType createRebindContentKeyType() { - return new RebindContentKeyType(); - } - - /** - * Creates an instance of (@link JobNotificationSubscriptionType). - * - * @return the job notification subscription type. - */ - public JobNotificationSubscriptionType createJobNotificationSubscriptionType() { - return new JobNotificationSubscriptionType(); - } - - /** - * Creates an instance of (@link NotificationEndPointType). - * - * @return the notification end point type. - */ - public NotificationEndPointType createNotificationEndPointType() { - return new NotificationEndPointType(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscriptionListFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscriptionListFactory.java deleted file mode 100644 index 4d9b132a8b30c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/JobNotificationSubscriptionListFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.models; - -import java.util.ArrayList; -import java.util.List; - -import com.microsoft.windowsazure.services.media.implementation.content.JobNotificationSubscriptionType; - -/** - * The Class JobNotificationSubscription factory. - */ -public class JobNotificationSubscriptionListFactory { - - public static List create( - List jobNotificationSubscriptionTypeList) { - if (jobNotificationSubscriptionTypeList == null) { - throw new IllegalArgumentException("The jobNotificationSubscriptionTypeList cannot be null."); - } - List jobNotificationSubscriptionList = new ArrayList(); - for (JobNotificationSubscriptionType jobNotificationSubscriptionType : jobNotificationSubscriptionTypeList) { - jobNotificationSubscriptionList.add(new JobNotificationSubscription(jobNotificationSubscriptionType - .getNotificationEndPointId(), TargetJobState.fromCode(jobNotificationSubscriptionType - .getTargetJobState()))); - } - return jobNotificationSubscriptionList; - - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKey.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKey.java deleted file mode 100644 index 5ec69e13bf6aa..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/media/models/ProtectionKey.java +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.models; - -import java.io.InputStream; - -import javax.ws.rs.core.MediaType; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; - -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.microsoft.windowsazure.services.media.entityoperations.DefaultEntityTypeActionOperation; -import com.microsoft.windowsazure.services.media.entityoperations.EntityTypeActionOperation; -import com.microsoft.windowsazure.services.media.implementation.content.ProtectionKeyIdType; -import com.microsoft.windowsazure.services.media.implementation.content.ProtectionKeyRestType; -import com.sun.jersey.api.client.ClientResponse; - -/** - * Class for creating operations to manipulate protection key pseudo-entities. - * - */ -public class ProtectionKey { - - private ProtectionKey() { - } - - /** - * Gets the protection key id. - * - * @param contentKeyType - * the content key type - * @return the protection key id - */ - public static EntityTypeActionOperation getProtectionKeyId(ContentKeyType contentKeyType) { - return new GetProtectionKeyIdActionOperation("GetProtectionKeyId").addQueryParameter("contentKeyType", - String.format("%d", contentKeyType.getCode())).setAcceptType(MediaType.APPLICATION_XML_TYPE); - } - - /** - * Gets the protection key. - * - * @param protectionKeyId - * the protection key id - * @return the protection key - */ - public static EntityTypeActionOperation getProtectionKey(String protectionKeyId) { - return new GetProtectionKeyActionOperation("GetProtectionKey").addQueryParameter("ProtectionKeyId", - String.format("'%s'", protectionKeyId)).setAcceptType(MediaType.APPLICATION_XML_TYPE); - } - - /** - * The Class GetProtectionKeyIdActionOperation. - * - * @param - */ - private static class GetProtectionKeyIdActionOperation extends DefaultEntityTypeActionOperation { - - /** The jaxb context. */ - private final JAXBContext jaxbContext; - - /** The unmarshaller. */ - private final Unmarshaller unmarshaller; - - /** - * Instantiates a new gets the protection key id action operation. - * - * @param name - * the name - */ - public GetProtectionKeyIdActionOperation(String name) { - super(name); - try { - jaxbContext = JAXBContext.newInstance(ProtectionKeyIdType.class); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - - try { - unmarshaller = jaxbContext.createUnmarshaller(); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.DefaultActionOperation#processResponse(com.sun.jersey.api.client.ClientResponse) - */ - @Override - public String processTypeResponse(ClientResponse clientResponse) { - PipelineHelpers.ThrowIfNotSuccess(clientResponse); - ProtectionKeyIdType protectionKeyIdType; - try { - protectionKeyIdType = parseResponse(clientResponse); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - - return protectionKeyIdType.getProtectionKeyId(); - } - - /** - * Parses the response. - * - * @param clientResponse - * the client response - * @return the protection key id type - * @throws JAXBException - * the jAXB exception - */ - private ProtectionKeyIdType parseResponse(ClientResponse clientResponse) throws JAXBException { - - InputStream inputStream = clientResponse.getEntityInputStream(); - JAXBElement protectionKeyIdTypeJaxbElement = unmarshaller.unmarshal(new StreamSource( - inputStream), ProtectionKeyIdType.class); - return protectionKeyIdTypeJaxbElement.getValue(); - - } - - } - - /** - * The Class GetProtectionKeyActionOperation. - */ - private static class GetProtectionKeyActionOperation extends DefaultEntityTypeActionOperation { - - /** The jaxb context. */ - private final JAXBContext jaxbContext; - - /** The unmarshaller. */ - private final Unmarshaller unmarshaller; - - /** - * Instantiates a new gets the protection key action operation. - * - * @param name - * the name - */ - public GetProtectionKeyActionOperation(String name) { - super(name); - try { - jaxbContext = JAXBContext.newInstance(ProtectionKeyRestType.class); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - - try { - unmarshaller = jaxbContext.createUnmarshaller(); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.media.entityoperations.DefaultActionOperation#processResponse(com.sun.jersey.api.client.ClientResponse) - */ - @Override - public String processTypeResponse(ClientResponse clientResponse) { - PipelineHelpers.ThrowIfNotSuccess(clientResponse); - ProtectionKeyRestType protectionKeyRestType; - try { - protectionKeyRestType = parseResponse(clientResponse); - } - catch (JAXBException e) { - throw new RuntimeException(e); - } - - return protectionKeyRestType.getProtectionKey(); - } - - /** - * Parses the response. - * - * @param clientResponse - * the client response - * @return the protection key rest type - * @throws JAXBException - * the jAXB exception - */ - private ProtectionKeyRestType parseResponse(ClientResponse clientResponse) throws JAXBException { - InputStream inputStream = clientResponse.getEntityInputStream(); - JAXBElement protectionKeyTypeJaxbElement = unmarshaller.unmarshal(new StreamSource( - inputStream), ProtectionKeyRestType.class); - return protectionKeyTypeJaxbElement.getValue(); - - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/Exports.java deleted file mode 100644 index 3be2f2909feee..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/Exports.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.queue.implementation.QueueExceptionProcessor; -import com.microsoft.windowsazure.services.queue.implementation.QueueRestProxy; -import com.microsoft.windowsazure.services.queue.implementation.SharedKeyFilter; -import com.microsoft.windowsazure.services.queue.implementation.SharedKeyLiteFilter; - -public class Exports implements Builder.Exports { - @Override - public void register(Builder.Registry registry) { - registry.add(QueueContract.class, QueueExceptionProcessor.class); - registry.add(QueueExceptionProcessor.class); - registry.add(QueueRestProxy.class); - registry.add(SharedKeyLiteFilter.class); - registry.add(SharedKeyFilter.class); - registry.add(UserAgentFilter.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueConfiguration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueConfiguration.java deleted file mode 100644 index 73da72170a043..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueConfiguration.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue; - -/** - * A class that contains static strings used to identify parts of a service configuration instance associated with the - * Windows Azure Queue service. - *

- * These values must not be altered. - */ -public class QueueConfiguration { - public final static String ACCOUNT_NAME = "queue.accountName"; - public final static String ACCOUNT_KEY = "queue.accountKey"; - public final static String URI = "queue.uri"; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueContract.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueContract.java deleted file mode 100644 index 41e408d2dde6f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueContract.java +++ /dev/null @@ -1,431 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.FilterableService; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.queue.models.CreateMessageOptions; -import com.microsoft.windowsazure.services.queue.models.CreateQueueOptions; -import com.microsoft.windowsazure.services.queue.models.GetQueueMetadataResult; -import com.microsoft.windowsazure.services.queue.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.queue.models.ListMessagesOptions; -import com.microsoft.windowsazure.services.queue.models.ListMessagesResult; -import com.microsoft.windowsazure.services.queue.models.ListQueuesOptions; -import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; -import com.microsoft.windowsazure.services.queue.models.PeekMessagesOptions; -import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult; -import com.microsoft.windowsazure.services.queue.models.QueueServiceOptions; -import com.microsoft.windowsazure.services.queue.models.ServiceProperties; -import com.microsoft.windowsazure.services.queue.models.UpdateMessageResult; - -/** - * Defines the methods available on the Windows Azure storage queue service. Construct an object instance implementing - * QueueContract with one of the static create methods on {@link QueueService}. These methods - * associate a {@link Configuration} with the implementation, so the methods on the instance of - * QueueContract all work with a particular storage account. - */ -public interface QueueContract extends FilterableService { - /** - * Gets the service properties of the queue. - * - * @return - * A {@link GetServicePropertiesResult} reference to the queue service properties. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetServicePropertiesResult getServiceProperties() throws ServiceException; - - /** - * Gets the service properties of the queue, using the specified options. Use the {@link QueueServiceOptions - * options} parameter to specify the server timeout for the operation. - * - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @return - * A {@link GetServicePropertiesResult} reference to the queue service properties. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetServicePropertiesResult getServiceProperties(QueueServiceOptions options) throws ServiceException; - - /** - * Sets the service properties of the queue. - * - * @param serviceProperties - * A {@link ServiceProperties} instance containing the queue service properties to set. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException; - - /** - * Sets the service properties of the queue, using the specified options. Use the {@link QueueServiceOptions - * options} parameter to specify the server timeout for the operation. - * - * @param serviceProperties - * A {@link ServiceProperties} instance containing the queue service properties to set. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setServiceProperties(ServiceProperties serviceProperties, QueueServiceOptions options) throws ServiceException; - - /** - * Creates a queue in the storage account with the specified queue name. - * - * @param queue - * A {@link String} containing the name of the queue to create. - * - * @throws ServiceException - * if an error occurs in the storage service. - */ - void createQueue(String queue) throws ServiceException; - - /** - * Creates a queue in the storage account with the specified queue name, using the specified options. Use the - * {@link QueueServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param queue - * A {@link String} containing the name of the queue to create. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void createQueue(String queue, CreateQueueOptions options) throws ServiceException; - - /** - * Deletes the queue in the storage account with the specified queue name. - * - * @param queue - * A {@link String} containing the name of the queue to delete. - * - * @throws ServiceException - * if an error occurs in the storage service. - */ - void deleteQueue(String queue) throws ServiceException; - - /** - * Deletes the queue in the storage account with the specified queue name, using the specified options. Use the - * {@link QueueServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param queue - * A {@link String} containing the name of the queue to delete. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void deleteQueue(String queue, QueueServiceOptions options) throws ServiceException; - - /** - * Gets a list of the queues in the storage account. - * - * @return - * A {@link ListQueuesResult} reference to the queues returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - ListQueuesResult listQueues() throws ServiceException; - - /** - * Gets a list of the queues in the storage account, using the specified options. Use the {@link ListQueuesOptions - * options} parameter to specify the server timeout for the operation, the prefix for queue names to match, the - * marker for the beginning of the queues to list, the maximum number of results to return, and whether to include - * queue metadata with the results. - * - * @param options - * A {@link ListQueuesOptions} instance containing options for the request. - * @return - * A {@link ListQueuesResult} reference to the queues returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - ListQueuesResult listQueues(ListQueuesOptions options) throws ServiceException; - - /** - * Gets the metadata for the named queue in the storage account. Queue metadata is a user-defined collection of - * key-value {@link String} pairs that is opaque to the server. - * - * @param queue - * A {@link String} containing the name of the queue to get the metadata for. - * @return - * A {@link GetQueueMetadataResult} reference to the metadata for the queue. - * @throws ServiceException - * if an error occurs in the storage service. - */ - GetQueueMetadataResult getQueueMetadata(String queue) throws ServiceException; - - /** - * Gets the metadata for the named queue in the storage account, using the specified options. Use the - * {@link QueueServiceOptions options} parameter to specify the server timeout for the operation. Queue metadata is - * a user-defined collection of key-value {@link String} pairs that is opaque to the server. - * - * @param queue - * A {@link String} containing the name of the queue to get the metadata for. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @return - * A {@link ListQueuesResult} reference to the queues returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - GetQueueMetadataResult getQueueMetadata(String queue, QueueServiceOptions options) throws ServiceException; - - /** - * Sets the specified metadata on the named queue in the storage account. Queue metadata is a user-defined - * collection of key-value {@link String} pairs that is opaque to the server. - * - * @param queue - * A {@link String} containing the name of the queue to set the metadata on. - * @param metadata - * A {@link java.util.HashMap} of metadata key-value {@link String} pairs to set on the queue. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void setQueueMetadata(String queue, HashMap metadata) throws ServiceException; - - /** - * Sets the specified metadata on the named queue in the storage account, using the specified options. Use the - * {@link QueueServiceOptions options} parameter to specify the server timeout for the operation. Queue metadata is - * a user-defined collection of key-value {@link String} pairs that is opaque to the server. - * - * @param queue - * A {@link String} containing the name of the queue to set the metadata on. - * @param metadata - * A {@link java.util.HashMap} of metadata key-value {@link String} pairs to set on the queue. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void setQueueMetadata(String queue, HashMap metadata, QueueServiceOptions options) - throws ServiceException; - - /** - * Appends a message with the specified text to the tail of the named queue in the storage account. - * - * @param queue - * A {@link String} containing the name of the queue to append the message to. - * @param messageText - * A {@link String} containing the text of the message to append to the queue. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void createMessage(String queue, String messageText) throws ServiceException; - - /** - * Appends a message with the specified text to the tail of the named queue in the storage account, using the - * specified options. Use the {@link CreateMessageOptions options} parameter to specify the server timeout for the - * operation, the message visibility timeout, and the message time to live in the queue. - * - * @param queue - * A {@link String} containing the name of the queue to append the message to. - * @param messageText - * A {@link String} containing the text of the message to append to the queue. - * @param options - * A {@link CreateMessageOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void createMessage(String queue, String messageText, CreateMessageOptions options) throws ServiceException; - - /** - * Updates the message in the named queue with the specified message ID and pop receipt value to have the specified - * message text and visibility timeout value. - * - * @param queue - * A {@link String} containing the name of the queue with the message to update. - * @param messageId - * A {@link String} containing the ID of the message to update. - * @param popReceipt - * A {@link String} containing the pop receipt for the message returned by a call to updateMessage or - * listMessages. - * @param messageText - * A {@link String} containing the updated text to set for the message. - * @param visibilityTimeoutInSeconds - * The new visibility timeout to set on the message, in seconds. - * @return - * An {@link UpdateMessageResult} reference to the updated message result returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - UpdateMessageResult updateMessage(String queue, String messageId, String popReceipt, String messageText, - int visibilityTimeoutInSeconds) throws ServiceException; - - /** - * Updates the message in the named queue with the specified message ID and pop receipt value to have the specified - * message text and visibility timeout value, using the specified options. Use the {@link QueueServiceOptions - * options} parameter to specify the server timeout for the operation. - * - * @param queue - * A {@link String} containing the name of the queue with the message to update. - * @param messageId - * A {@link String} containing the ID of the message to update. - * @param popReceipt - * A {@link String} containing the pop receipt for the message returned by a call to updateMessage or - * listMessages. - * @param messageText - * A {@link String} containing the updated text to set for the message. - * @param visibilityTimeoutInSeconds - * The new visibility timeout to set on the message, in seconds. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @return - * An {@link UpdateMessageResult} reference to the updated message result returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - UpdateMessageResult updateMessage(String queue, String messageId, String popReceipt, String messageText, - int visibilityTimeoutInSeconds, QueueServiceOptions options) throws ServiceException; - - /** - * Deletes the message in the named queue with the specified message ID and pop receipt value. - * - * @param queue - * A {@link String} containing the name of the queue with the message to delete. - * @param messageId - * A {@link String} containing the ID of the message to delete. - * @param popReceipt - * A {@link String} containing the pop receipt for the message returned by a call to updateMessage or - * listMessages. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void deleteMessage(String queue, String messageId, String popReceipt) throws ServiceException; - - /** - * Deletes the message in the named queue with the specified message ID and popReceipt value, using the specified - * options. Use the {@link QueueServiceOptions options} parameter to specify the server timeout for the operation. - * - * @param queue - * A {@link String} containing the name of the queue with the message to delete. - * @param messageId - * A {@link String} containing the ID of the message to delete. - * @param popReceipt - * A {@link String} containing the pop receipt for the message returned by a call to updateMessage or - * listMessages. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void deleteMessage(String queue, String messageId, String popReceipt, QueueServiceOptions options) - throws ServiceException; - - /** - * Retrieves the first message from head of the named queue in the storage account. This marks the message as - * invisible for the default visibility timeout period. When message processing is complete, the message must be - * deleted with a call to {@link QueueContract#deleteMessage(String, String, String, QueueServiceOptions) - * deleteMessage}. If message processing will take longer than the visibility timeout period, - * use the {@link QueueContract#updateMessage(String, String, String, String, int, QueueServiceOptions) - * updateMessage} method to extend the visibility timeout. The message will become visible in the queue again - * when the timeout completes if it is not deleted. - *

- * To get a list of multiple messages from the head of the queue, call the - * {@link QueueContract#listMessages(String, ListMessagesOptions)} method with options set specifying the number of - * messages to return. - * - * @param queue - * A {@link String} containing the name of the queue to get the message from. - * @return - * A {@link ListMessagesResult} reference to the message result returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - ListMessagesResult listMessages(String queue) throws ServiceException; - - /** - * Retrieves up to 32 messages from the head of the named queue in the storage account, using the specified options. - * Use the {@link ListMessagesOptions options} parameter to specify the server timeout for the operation, the number - * of messages to retrieve, and the visibility timeout to set on the retrieved messages. When message processing is - * complete, each message must be deleted with a call to - * {@link QueueContract#deleteMessage(String, String, String, QueueServiceOptions) deleteMessage}. If message - * processing takes longer than the default timeout period, use the - * {@link QueueContract#updateMessage(String, String, String, String, int, QueueServiceOptions) updateMessage} - * method to extend the visibility timeout. Each message will become - * visible in the queue again when the timeout completes if it is not deleted. - * - * @param queue - * A {@link String} containing the name of the queue to get the messages from. - * @param options - * A {@link ListMessagesOptions} instance containing options for the request. - * @return - * A {@link ListMessagesResult} reference to the message result returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - ListMessagesResult listMessages(String queue, ListMessagesOptions options) throws ServiceException; - - /** - * Peeks a message from the named queue. A peek request retrieves a message from the head of the queue without - * changing its visibility. - * - * @param queue - * A {@link String} containing the name of the queue to peek the message from. - * @return - * A {@link PeekMessagesResult} reference to the message result returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - PeekMessagesResult peekMessages(String queue) throws ServiceException; - - /** - * Peeks messages from the named queue, using the specified options. A peek request retrieves messages from the - * head of the queue without changing their visibility. Use the {@link PeekMessagesOptions options} parameter to - * specify the server timeout for the operation and the number of messages to retrieve. - * - * @param queue - * A {@link String} containing the name of the queue to peek the message from. - * @param options - * A {@link PeekMessagesOptions} instance containing options for the request. - * @return - * A {@link PeekMessagesResult} reference to the message result returned. - * @throws ServiceException - * if an error occurs in the storage service. - */ - PeekMessagesResult peekMessages(String queue, PeekMessagesOptions options) throws ServiceException; - - /** - * Deletes all messages in the named queue. - * - * @param queue - * A {@link String} containing the name of the queue to delete all messages from. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void clearMessages(String queue) throws ServiceException; - - /** - * Deletes all messages in the named queue, using the specified options. Use the {@link QueueServiceOptions options} - * parameter to specify the server timeout for the operation. - * - * @param queue - * A {@link String} containing the name of the queue to delete all messages from. - * @param options - * A {@link QueueServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs in the storage service. - */ - void clearMessages(String queue, QueueServiceOptions options) throws ServiceException; - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java deleted file mode 100644 index b60aacd417907..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue; - -import com.microsoft.windowsazure.services.core.Configuration; - -/** - * A class for static factory methods that return instances implementing {@link QueueContract}. - */ -public class QueueService { - /** - * Private default constructor. - */ - private QueueService() { - } - - /** - * A static factory method that returns an instance implementing {@link QueueContract} using default values for - * initializing a {@link Configuration} instance. Note that the returned interface will not work unless storage - * account credentials have been added to the "META-INF/com.microsoft.windowsazure.properties" resource file. - * - * @return - * An instance implementing {@link QueueContract} for interacting with the queue service. - */ - public static QueueContract create() { - return create(null, Configuration.getInstance()); - } - - /** - * A static factory method that returns an instance implementing {@link QueueContract} using the specified - * {@link Configuration} instance. The {@link Configuration} instance must have storage account information and - * credentials set before this method is called for the returned interface to work. - * - * @param config - * A {@link Configuration} instance configured with storage account information and credentials. - * - * @return - * An instance implementing {@link QueueContract} for interacting with the queue service. - */ - public static QueueContract create(Configuration config) { - return create(null, config); - } - - /** - * A static factory method that returns an instance implementing {@link QueueContract} using default values for - * initializing a {@link Configuration} instance, and using the specified profile prefix for service settings. Note - * that the returned interface will not work unless storage account settings and credentials have been added to the - * "META-INF/com.microsoft.windowsazure.properties" resource file with the specified profile prefix. - * - * @param profile - * A string prefix for the account name and credentials settings in the {@link Configuration} instance. - * @return - * An instance implementing {@link QueueContract} for interacting with the queue service. - */ - public static QueueContract create(String profile) { - return create(profile, Configuration.getInstance()); - } - - /** - * A static factory method that returns an instance implementing {@link QueueContract} using the specified - * {@link Configuration} instance and profile prefix for service settings. The {@link Configuration} instance must - * have storage account information and credentials set with the specified profile prefix before this method is - * called for the returned interface to work. - * - * @param profile - * A string prefix for the account name and credentials settings in the {@link Configuration} instance. - * @param config - * A {@link Configuration} instance configured with storage account information and credentials. - * - * @return - * An instance implementing {@link QueueContract} for interacting with the queue service. - */ - public static QueueContract create(String profile, Configuration config) { - return config.create(profile, QueueContract.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueue.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueue.java deleted file mode 100644 index 4190dd58ac73f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueue.java +++ /dev/null @@ -1,1694 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import java.io.OutputStream; -import java.io.StringWriter; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.blob.core.storage.SharedAccessSignatureHelper; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.StorageExtendedErrorInformation; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseResponse; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * This class represents a queue in the Windows Azure Queue service. - */ -public final class CloudQueue { - - /** - * Gets the first message from a list of queue messages, if any. - * - * @param messages - * The Iterable collection of {@link CloudQueueMessage} objects to get the first message - * from. - * - * @return The first {@link CloudQueueMessage} from the list of queue messages, or null if the list is - * empty. - */ - static CloudQueueMessage getFirstOrNull(final Iterable messages) { - for (final CloudQueueMessage m : messages) { - return m; - } - - return null; - } - - /** - * The name of the queue. - */ - private String name; - - /** - * The absolute URI of the queue. - */ - URI uri; - - /** - * A reference to the queue's associated service client. - */ - CloudQueueClient queueServiceClient; - - /** - * The queue's Metadata collection. - */ - HashMap metadata; - - /** - * The queue's approximate message count, as reported by the server. - */ - long approximateMessageCount; - - /** - * The CloudQueue class using the specified address and client. - * - * @param queueAddress - * A String that represents either the absolute URI to the queue, or the queue name. - * @param client - * A {@link CloudQueueClient} object that represents the associated service client, and that specifies - * the endpoint for the Queue service. - * - * @throws URISyntaxException - * If the resource URI is invalid. - * @throws StorageException - */ - public CloudQueue(final String queueAddress, final CloudQueueClient client) throws URISyntaxException, - StorageException { - this(PathUtility.appendPathToUri(client.getEndpoint(), queueAddress), client); - } - - /** - * Creates an instance of the CloudQueue class using the specified queue URI and client. - * - * @param uri - * A java.net.URI object that represents the absolute URI of the queue. - * @param client - * A {@link CloudQueueClient} object that represents the associated service client, and that specifies - * the endpoint for the Queue service. - * @throws StorageException - * @throws URISyntaxException - */ - public CloudQueue(final URI uri, final CloudQueueClient client) throws URISyntaxException, StorageException { - this.uri = uri; - this.name = PathUtility.getQueueNameFromUri(uri, client.isUsePathStyleUris()); - this.queueServiceClient = client; - this.shouldEncodeMessage = true; - this.parseQueryAndVerify(this.uri, client, client.isUsePathStyleUris()); - } - - /** - * Adds a message to the back of the queue with the default options. - * - * @param message - * A {@link CloudQueueMessage} object that specifies the message to add. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void addMessage(final CloudQueueMessage message) throws StorageException { - this.addMessage(message, 0, 0, null, null); - } - - /** - * Adds a message to the back of the queue with the specified options. - * - * @param message - * A {@link CloudQueueMessage} object that specifies the message to add. - * - * @param timeToLiveInSeconds - * The maximum time to allow the message to be in the queue. A value of zero will set the time-to-live to - * the service default value of seven days. - * - * @param initialVisibilityDelayInSeconds - * The length of time during which the message will be invisible, starting when it is added to the queue, - * or 0 to make the message visible immediately. This value must be greater than or equal to zero and - * less than or equal to the time-to-live value. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void addMessage(final CloudQueueMessage message, final int timeToLiveInSeconds, - final int initialVisibilityDelayInSeconds, QueueRequestOptions options, OperationContext opContext) - throws StorageException { - Utility.assertNotNull("message", message); - Utility.assertNotNull("messageContent", message.getMessageContentAsByte()); - Utility.assertInBounds("timeToLiveInSeconds", timeToLiveInSeconds, 0, - QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS); - - final int realTimeToLiveInSeconds = timeToLiveInSeconds == 0 ? QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS - : timeToLiveInSeconds; - Utility.assertInBounds("initialVisibilityDelayInSeconds", initialVisibilityDelayInSeconds, 0, - realTimeToLiveInSeconds - 1); - - final String stringToSend = message.getMessageContentForTransfer(this.shouldEncodeMessage); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = QueueRequest.putMessage(queue.getMessageRequestAddress(opContext), - this.getRequestOptions().getTimeoutIntervalInMs(), initialVisibilityDelayInSeconds, - timeToLiveInSeconds, opContext); - this.setConnection(request); - - final byte[] messageBytes = QueueRequest.generateMessageRequestBody(stringToSend); - - this.signRequest(client, request, messageBytes.length, null); - - final OutputStream outStreamRef = request.getOutputStream(); - outStreamRef.write(messageBytes); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Clears all messages from the queue, using the default request options. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void clear() throws StorageException { - this.clear(null, null); - } - - /** - * Clears all messages from the queue, using the specified request options and operation context. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void clear(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = QueueRequest.clearMessages(queue.getMessageRequestAddress(opContext), - this.getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Creates the queue in the storage service with default request options. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void create() throws StorageException { - this.create(null, null); - } - - /** - * Creates the queue in the storage service using the specified request options and operation context. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void create(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - final HttpURLConnection request = QueueRequest.create(queue.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - QueueRequest.addMetadata(request, queue.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED - && this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Creates the queue in the storage service using default request options if it does not already exist. - * - * @return A value of true if the queue is created in the storage service, otherwise false - * . - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean createIfNotExist() throws StorageException { - return this.createIfNotExist(null, null); - } - - /** - * Creates the queue in the storage service with the specified request options and operation context if it does not - * already exist. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A value of true if the queue is created in the storage service, otherwise false - * . - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean createIfNotExist(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Boolean execute(final CloudQueueClient client, final CloudQueue queue, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = QueueRequest.create(queue.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - QueueRequest.addMetadata(request, queue.metadata, opContext); - - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CREATED) { - return true; - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return false; - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - final StorageException potentialConflictException = StorageException.translateException(request, - null, opContext); - - StorageExtendedErrorInformation extendedInfo = potentialConflictException - .getExtendedErrorInformation(); - if (extendedInfo == null) { - // If we cant validate the error then the error must be surfaced to the user. - throw potentialConflictException; - } - - if (!extendedInfo.getErrorCode().equals(StorageErrorCodeStrings.QUEUE_ALREADY_EXISTS)) { - this.setException(potentialConflictException); - this.setNonExceptionedRetryableFailure(true); - } - } - else { - this.setNonExceptionedRetryableFailure(true); - } - - return false; - } - }; - - return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Deletes the queue from the storage service. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void delete() throws StorageException { - this.delete(null, null); - } - - /** - * Deletes the queue from the storage service, using the specified request options and operation context. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void delete(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - final HttpURLConnection request = QueueRequest.delete(queue.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - - } - - /** - * Deletes the queue from the storage service if it exists. - * - * @return A value of true if the queue existed in the storage service and has been deleted, otherwise - * false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean deleteIfExists() throws StorageException { - return this.deleteIfExists(null, null); - } - - /** - * Deletes the queue from the storage service using the specified request options and operation context, if it - * exists. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A value of true if the queue existed in the storage service and has been deleted, otherwise - * false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean deleteIfExists(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public Boolean execute(final CloudQueueClient client, final CloudQueue queue, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = QueueRequest.delete(queue.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return true; - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return false; - } - else { - this.setNonExceptionedRetryableFailure(true); - return false; - } - } - }; - - return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - - } - - /** - * Deletes the specified message from the queue. - * - * @param message - * A {@link CloudQueueMessage} object that specifies the message to delete. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void deleteMessage(final CloudQueueMessage message) throws StorageException { - this.deleteMessage(message, null, null); - } - - /** - * Deletes the specified message from the queue, using the specified request options and operation context. - * - * @param message - * A {@link CloudQueueMessage} object that specifies the message to delete. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void deleteMessage(final CloudQueueMessage message, QueueRequestOptions options, OperationContext opContext) - throws StorageException { - Utility.assertNotNull("message", message); - Utility.assertNotNullOrEmpty("messageId", message.id); - Utility.assertNotNullOrEmpty("popReceipt", message.popReceipt); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final String messageId = message.getId(); - final String messagePopReceipt = message.getPopReceipt(); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = QueueRequest.deleteMessage(queue.getIndividualMessageAddress( - messageId, opContext), this.getRequestOptions().getTimeoutIntervalInMs(), messagePopReceipt, - opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Downloads the queue's metadata and approximate message count value. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void downloadAttributes() throws StorageException { - this.downloadAttributes(null, null); - } - - /** - * Downloads the queue's metadata and approximate message count value, using the specified request options and - * operation context. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueue}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void downloadAttributes(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - final HttpURLConnection request = QueueRequest.downloadAttributes( - queue.getTransformedAddress(opContext), this.getRequestOptions().getTimeoutIntervalInMs(), - opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - queue.metadata = BaseResponse.getMetadata(request); - queue.approximateMessageCount = QueueResponse.getApproximateMessageCount(request); - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Returns a value that indicates whether the queue exists in the storage service. - * - * @return true if the queue exists in the storage service, otherwise false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean exists() throws StorageException { - return this.exists(null, null); - } - - /** - * Returns a value that indicates whether the queue exists in the storage service, using the specified request - * options and operation context. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return true if the queue exists in the storage service, otherwise false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean exists(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Boolean execute(final CloudQueueClient client, final CloudQueue queue, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = QueueRequest.downloadAttributes( - queue.getTransformedAddress(opContext), this.getRequestOptions().getTimeoutIntervalInMs(), - opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { - return Boolean.valueOf(true); - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return Boolean.valueOf(false); - } - else { - this.setNonExceptionedRetryableFailure(true); - // return false instead of null to avoid SCA issues - return false; - } - } - }; - - return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Gets the approximate messages count of the queue. This value is initialized by a request to - * {@link #downloadAttributes} and represents the approximate message count when that request completed. - * - * @return A Long object that represents the approximate messages count of the queue. - */ - public long getApproximateMessageCount() { - return this.approximateMessageCount; - } - - /** - * Get a single message request (Used internally only). - * - * @return The URI for a single message request. - * - * @throws URISyntaxException - * If the resource URI is invalid. - * @throws StorageException - */ - URI getIndividualMessageAddress(final String messageId, final OperationContext opContext) - throws URISyntaxException, StorageException { - return PathUtility.appendPathToUri(this.getMessageRequestAddress(opContext), messageId); - } - - /** - * Get the message request base address (Used internally only). - * - * @return The message request URI. - * - * @throws URISyntaxException - * If the resource URI is invalid. - * @throws StorageException - */ - URI getMessageRequestAddress(final OperationContext opContext) throws URISyntaxException, StorageException { - if (this.messageRequestAddress == null) { - this.messageRequestAddress = PathUtility.appendPathToUri(this.getTransformedAddress(opContext), - QueueConstants.MESSAGES); - } - - return this.messageRequestAddress; - } - - /** - * Gets the metadata collection for the queue as stored in this CloudQueue object. This value is - * initialized with the metadata from the queue by a call to {@link #downloadAttributes}, and is set on the queue - * with a call to {@link #uploadMetadata}. - * - * @return A java.util.HashMap object that represents the metadata for the queue. - */ - public HashMap getMetadata() { - return this.metadata; - } - - /** - * Gets the name of the queue. - * - * @return A String object that represents the name of the queue. - */ - public String getName() { - return this.name; - } - - /** - * Gets the queue service client associated with this queue. - * - * @return A {@link CloudQueueClient} object that represents the service client associated with this queue. - */ - public CloudQueueClient getServiceClient() { - return this.queueServiceClient; - } - - /** - * Gets the value indicating whether the message should be base-64 encoded. - * - * @return A Boolean that represents whether the message should be base-64 encoded. - */ - public boolean getShouldEncodeMessage() { - return this.shouldEncodeMessage; - } - - /** - * Gets the absolute URI for this queue. - * - * @return A java.net.URI object that represents the URI for this queue. - */ - public URI getUri() { - return this.uri; - } - - /** - * Peeks a message from the queue. A peek request retrieves a message from the front of the queue without changing - * its visibility. - * - * @return An {@link CloudQueueMessage} object that represents a message in this queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public CloudQueueMessage peekMessage() throws StorageException { - return this.peekMessage(null, null); - } - - /** - * Peeks a message from the queue, using the specified request options and operation context. A peek request - * retrieves a message from the front of the queue without changing its visibility. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An {@link CloudQueueMessage} object that represents the requested message from the queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public CloudQueueMessage peekMessage(final QueueRequestOptions options, final OperationContext opContext) - throws StorageException { - return getFirstOrNull(this.peekMessages(1, null, null)); - } - - /** - * Peeks a specified number of messages from the queue. A peek request retrieves messages from the front of the - * queue without changing their visibility. - * - * @param numberOfMessages - * The number of messages to retrieve. - * - * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the requested messages from - * the queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public Iterable peekMessages(final int numberOfMessages) throws StorageException { - return this.peekMessages(numberOfMessages, null, null); - } - - /** - * Peeks a set of messages from the queue, using the specified request options and operation context. A peek request - * retrieves messages from the front of the queue without changing their visibility. - * - * @param numberOfMessages - * The number of messages to retrieve. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the requested messages from - * the queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public Iterable peekMessages(final int numberOfMessages, QueueRequestOptions options, - OperationContext opContext) throws StorageException { - Utility.assertInBounds("numberOfMessages", numberOfMessages, 1, QueueConstants.MAX_NUMBER_OF_MESSAGES_TO_PEEK); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation> impl = new StorageOperation>( - options) { - - @Override - public ArrayList execute(final CloudQueueClient client, final CloudQueue queue, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = QueueRequest.peekMessages(queue.getMessageRequestAddress(opContext), - this.getRequestOptions().getTimeoutIntervalInMs(), numberOfMessages, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - else { - return QueueDeserializationHelper.readMessages(request.getInputStream(), queue.shouldEncodeMessage); - } - } - }; - - return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Retrieves a message from the front of the queue using the default request options. This operation marks the - * retrieved message as invisible in the queue for the default visibility timeout period. - * - * @return An {@link CloudQueueMessage} object that represents a message in this queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public CloudQueueMessage retrieveMessage() throws StorageException { - return this.retrieveMessage(QueueConstants.DEFAULT_VISIBILITY_MESSAGE_TIMEOUT_IN_SECONDS, null, null); - } - - /** - * Retrieves a message from the front of the queue, using the specified request options and operation context. This - * operation marks the retrieved message as invisible in the queue for the specified visibility timeout period. - * - * @param visibilityTimeoutInSeconds - * Specifies the visibility timeout for the message, in seconds. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An {@link CloudQueueMessage} object that represents a message in this queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public CloudQueueMessage retrieveMessage(final int visibilityTimeoutInSeconds, final QueueRequestOptions options, - final OperationContext opContext) throws StorageException { - return getFirstOrNull(this.retrieveMessages(1, visibilityTimeoutInSeconds, options, opContext)); - } - - /** - * Retrieves the specified number of messages from the front of the queue using the default request options. This - * operation marks the retrieved messages as invisible in the queue for the default visibility timeout period. - * - * @param numberOfMessages - * The number of messages to retrieve. - * - * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the retrieved messages from - * the queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public Iterable retrieveMessages(final int numberOfMessages) throws StorageException { - return this.retrieveMessages(numberOfMessages, QueueConstants.DEFAULT_VISIBILITY_MESSAGE_TIMEOUT_IN_SECONDS, - null, null); - } - - /** - * Retrieves the specified number of messages from the front of the queue using the specified request options and - * operation context. This operation marks the retrieved messages as invisible in the queue for the default - * visibility timeout period. - * - * @param numberOfMessages - * The number of messages to retrieve. - * - * @param visibilityTimeoutInSeconds - * Specifies the visibility timeout for the retrieved messages, in seconds. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return An enumerable collection of {@link CloudQueueMessage} objects that represents the messages retrieved from - * the queue. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public Iterable retrieveMessages(final int numberOfMessages, - final int visibilityTimeoutInSeconds, QueueRequestOptions options, OperationContext opContext) - throws StorageException { - Utility.assertInBounds("numberOfMessages", numberOfMessages, 1, QueueConstants.MAX_NUMBER_OF_MESSAGES_TO_PEEK); - Utility.assertInBounds("visibilityTimeoutInSeconds", visibilityTimeoutInSeconds, 0, - QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation> impl = new StorageOperation>( - options) { - - @Override - public ArrayList execute(final CloudQueueClient client, final CloudQueue queue, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = QueueRequest.retrieveMessages( - queue.getMessageRequestAddress(opContext), this.getRequestOptions().getTimeoutIntervalInMs(), - numberOfMessages, visibilityTimeoutInSeconds, opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - else { - return QueueDeserializationHelper.readMessages(request.getInputStream(), queue.shouldEncodeMessage); - } - } - }; - - return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Sets the metadata collection of name-value pairs to be set on the queue with an {@link #uploadMetadata} call. - * This collection will overwrite any existing queue metadata. If this is set to an empty collection, the queue - * metadata will be cleared on an {@link #uploadMetadata} call. - * - * @param metadata - * A java.util.HashMap object that represents the metadata being assigned to the queue. - */ - public void setMetadata(final HashMap metadata) { - this.metadata = metadata; - } - - /** - * Sets the flag indicating whether the message should be base-64 encoded. - * - * @param shouldEncodeMessage - * The value indicates whether the message should be base-64 encoded. - */ - public void setShouldEncodeMessage(final boolean shouldEncodeMessage) { - this.shouldEncodeMessage = shouldEncodeMessage; - } - - /** - * Sets the name of the queue. - * - * @param name - * A String that represents the name being assigned to the queue. - */ - void setName(final String name) { - this.name = name; - } - - /** - * Updates the specified message in the queue with a new visibility timeout value in seconds. - * - * @param message - * The {@link CloudQueueMessage} to update in the queue. - * - * @param visibilityTimeoutInSeconds - * Specifies the new visibility timeout for the message, in seconds. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public void updateMessage(final CloudQueueMessage message, final int visibilityTimeoutInSeconds) - throws StorageException { - this.updateMessage(message, visibilityTimeoutInSeconds, EnumSet.of(MessageUpdateFields.VISIBILITY), null, null); - } - - /** - * Updates a message in the queue, using the specified request options and operation context. - * - * @param message - * The {@link CloudQueueMessage} to update in the queue. - * - * @param visibilityTimeoutInSeconds - * Specifies the new visibility timeout for the message, in seconds. - * - * @param messageUpdateFields - * An EnumSet of {@link MessageUpdateFields} values that specifies which parts of the - * message are to be updated. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void updateMessage(final CloudQueueMessage message, final int visibilityTimeoutInSeconds, - final EnumSet messageUpdateFields, QueueRequestOptions options, - OperationContext opContext) throws StorageException { - Utility.assertNotNull("message", message); - Utility.assertNotNullOrEmpty("messageId", message.id); - Utility.assertNotNullOrEmpty("popReceipt", message.popReceipt); - - Utility.assertInBounds("visibilityTimeoutInSeconds", visibilityTimeoutInSeconds, 0, - QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS); - - final String stringToSend = message.getMessageContentForTransfer(this.shouldEncodeMessage); - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = QueueRequest.updateMessage(queue.getIndividualMessageAddress( - message.getId(), opContext), this.getRequestOptions().getTimeoutIntervalInMs(), message - .getPopReceipt(), visibilityTimeoutInSeconds, opContext); - this.setConnection(request); - - if (messageUpdateFields.contains(MessageUpdateFields.CONTENT)) { - final byte[] messageBytes = QueueRequest.generateMessageRequestBody(stringToSend); - - this.signRequest(client, request, messageBytes.length, null); - - final OutputStream outStreamRef = request.getOutputStream(); - outStreamRef.write(messageBytes); - } - else { - request.setFixedLengthStreamingMode(0); - - this.signRequest(client, request, 0L, null); - } - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - message.popReceipt = request.getHeaderField("x-ms-popreceipt"); - message.nextVisibleTime = Utility.parseRFC1123DateFromStringInGMT(request - .getHeaderField("x-ms-time-next-visible")); - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Uploads the metadata in the CloudQueue object to the queue, using the default request options. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void uploadMetadata() throws StorageException { - this.uploadMetadata(null, null); - } - - /** - * Uploads the metadata in the CloudQueue object to the queue, using the specified request options and - * operation context. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void uploadMetadata(QueueRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = QueueRequest.setMetadata(queue.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - QueueRequest.addMetadata(request, queue.metadata, opContext); - this.signRequest(client, request, 0L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - - } - - /** - * Uploads the queue's permissions. - * - * @param permissions - * A {@link QueuePermissions} object that represents the permissions to upload. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPermissions(final QueuePermissions permissions) throws StorageException { - this.uploadPermissions(permissions, null, null); - } - - /** - * Uploads the queue's permissions using the specified request options and operation context. - * - * @param permissions - * A {@link QueuePermissions} object that represents the permissions to upload. - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPermissions(final QueuePermissions permissions, QueueRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudQueueClient client, final CloudQueue queue, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = QueueRequest.setAcl(queue.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - final StringWriter outBuffer = new StringWriter(); - - QueueRequest.writeSharedAccessIdentifiersToStream(permissions.getSharedAccessPolicies(), outBuffer); - - final byte[] aclBytes = outBuffer.toString().getBytes("UTF8"); - - this.signRequest(client, request, aclBytes.length, null); - - final OutputStream outStreamRef = request.getOutputStream(); - outStreamRef.write(aclBytes); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Downloads the permission settings for the queue. - * - * @return A {@link QueuePermissions} object that represents the queue's permissions. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public QueuePermissions downloadPermissions() throws StorageException { - return this.downloadPermissions(null, null); - } - - /** - * Downloads the permissions settings for the queue using the specified request options and operation context. - * - * @param options - * A {@link QueueRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link QueuePermissions} object that represents the container's permissions. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public QueuePermissions downloadPermissions(QueueRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.queueServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public QueuePermissions execute(final CloudQueueClient client, final CloudQueue queue, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = QueueRequest.getAcl(queue.getTransformedAddress(opContext), this - .getRequestOptions().getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signRequest(client, request, -1L, null); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - } - - final QueuePermissions permissions = new QueuePermissions(); - final QueueAccessPolicyResponse response = new QueueAccessPolicyResponse(request.getInputStream()); - - for (final String key : response.getAccessIdentifiers().keySet()) { - permissions.getSharedAccessPolicies().put(key, response.getAccessIdentifiers().get(key)); - } - - return permissions; - } - }; - - return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Returns a shared access signature for the queue. - * - * @param policy - * The access policy for the shared access signature. - * @param groupPolicyIdentifier - * A queue-level access policy. - * @return A shared access signature for the queue. - * @throws InvalidKeyException - * If an invalid key was passed. - * @throws StorageException - * If a storage service error occurred. - * @throws IllegalArgumentException - * If an unexpected value is passed. - */ - public String generateSharedAccessSignature(final SharedAccessQueuePolicy policy, final String groupPolicyIdentifier) - throws InvalidKeyException, StorageException { - - if (!this.queueServiceClient.getCredentials().canCredentialsSignRequest()) { - final String errorMessage = "Cannot create Shared Access Signature unless the Account Key credentials are used by the QueueServiceClient."; - throw new IllegalArgumentException(errorMessage); - } - - final String resourceName = this.getSharedAccessCanonicalName(); - - final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHash(policy, - groupPolicyIdentifier, resourceName, this.queueServiceClient, null); - - final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignature(policy, - groupPolicyIdentifier, signature); - - return builder.toString(); - } - - /** - * Returns the canonical name for shared access. - * - * @return the canonical name for shared access. - */ - private String getSharedAccessCanonicalName() { - if (this.queueServiceClient.isUsePathStyleUris()) { - return this.getUri().getPath(); - } - else { - return PathUtility.getCanonicalPathFromCredentials(this.queueServiceClient.getCredentials(), this.getUri() - .getPath()); - } - } - - /** - * Returns the transformed URI for the resource if the given credentials require transformation. - * - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A java.net.URI object that represents the transformed URI. - * - * @throws IllegalArgumentException - * If the URI is not absolute. - * @throws StorageException - * If a storage service error occurred. - * @throws URISyntaxException - * If the resource URI is invalid. - */ - protected final URI getTransformedAddress(final OperationContext opContext) throws URISyntaxException, - StorageException { - if (this.queueServiceClient.getCredentials().doCredentialsNeedTransformUri()) { - if (this.getUri().isAbsolute()) { - return this.queueServiceClient.getCredentials().transformUri(this.getUri(), opContext); - } - else { - final StorageException ex = Utility.generateNewUnexpectedStorageException(null); - ex.getExtendedErrorInformation().setErrorMessage("Queue Object relative URIs not supported."); - throw ex; - } - } - else { - return this.getUri(); - } - } - - /** - * Parse Uri for SAS (Shared access signature) information. - * - * Validate that no other query parameters are passed in. Any SAS information will be recorded as corresponding - * credentials instance. If existingClient is passed in, any SAS information found will not be supported. Otherwise - * a new client is created based on SAS information or as anonymous credentials. - * - * @param completeUri - * The complete Uri. - * @param existingClient - * The client to use. - * @param usePathStyleUris - * If true, path style Uris are used. - * @throws URISyntaxException - * @throws StorageException - */ - private void parseQueryAndVerify(final URI completeUri, final CloudQueueClient existingClient, - final boolean usePathStyleUris) throws URISyntaxException, StorageException { - Utility.assertNotNull("completeUri", completeUri); - - if (!completeUri.isAbsolute()) { - final String errorMessage = String.format( - "Address '%s' is not an absolute address. Relative addresses are not permitted in here.", - completeUri.toString()); - throw new IllegalArgumentException(errorMessage); - } - - this.uri = PathUtility.stripURIQueryAndFragment(completeUri); - - final HashMap queryParameters = PathUtility.parseQueryString(completeUri.getQuery()); - final StorageCredentialsSharedAccessSignature sasCreds = SharedAccessSignatureHelper - .parseQuery(queryParameters); - - if (sasCreds == null) { - return; - } - - final Boolean sameCredentials = existingClient == null ? false : Utility.areCredentialsEqual(sasCreds, - existingClient.getCredentials()); - - if (existingClient == null || !sameCredentials) { - this.queueServiceClient = new CloudQueueClient(new URI(PathUtility.getServiceClientBaseAddress( - this.getUri(), usePathStyleUris)), sasCreds); - } - - if (existingClient != null && !sameCredentials) { - this.queueServiceClient.setRetryPolicyFactory(existingClient.getRetryPolicyFactory()); - this.queueServiceClient.setTimeoutInMs(existingClient.getTimeoutInMs()); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClient.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClient.java deleted file mode 100644 index b4b1f97c2bed2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClient.java +++ /dev/null @@ -1,404 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.blob.client.CloudBlobClient; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.RequestOptions; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.ResultContinuationType; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.ServiceClient; -import com.microsoft.windowsazure.services.core.storage.ServiceProperties; -import com.microsoft.windowsazure.services.core.storage.StorageCredentials; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LazySegmentedIterable; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ListingContext; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.SegmentedStorageOperation; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * Provides a service client for accessing the Windows Azure Queue service. - */ -public final class CloudQueueClient extends ServiceClient { - - /** - * Initializes a new instance of the CloudQueueClient class - * using the specified Queue service endpoint and account credentials. - * - * @param baseUri - * The Queue service endpoint to use to create the client - * @param credentials - * The account credentials. - */ - public CloudQueueClient(final URI baseUri, final StorageCredentials credentials) { - super(baseUri, credentials); - this.setTimeoutInMs(QueueConstants.DEFAULT_QUEUE_CLIENT_TIMEOUT_IN_MS); - - if (credentials == null) { - throw new IllegalArgumentException("StorageCredentials can't be null for the queue service."); - } - } - - /** - * Gets a {@link CloudQueue} object that represents the storage service - * queue for the specified address. - * - * @param queueAddress - * A String that represents the name of the queue, - * or the absolute URI to the queue. - * - * @return A {@link CloudQueue} object that represents a reference to the - * queue. - * - * @throws URISyntaxException - * If the resource URI is invalid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public CloudQueue getQueueReference(final String queueAddress) throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("queueAddress", queueAddress); - return new CloudQueue(queueAddress, this); - } - - /** - * Gets an iterable collection of queues for this queue service client. - * - * @return An iterable collection of {@link CloudQueue} objects that - * represent the queues in this client. - */ - @DoesServiceRequest - public Iterable listQueues() { - return this.listQueues(null, QueueListingDetails.NONE, null, null); - } - - /** - * Returns an iterable collection of queues whose names begin with the - * specified prefix in this Queue service client. - * - * @param prefix - * A String that represents the queue name prefix. - * - * @return An iterable collection of {@link CloudQueue} objects that - * represent the queues in this client whose names begin with the - * specified prefix. - */ - @DoesServiceRequest - public Iterable listQueues(final String prefix) { - return this.listQueues(prefix, QueueListingDetails.NONE, null, null); - } - - /** - * Returns an iterable collection of queues whose names begin with the - * specified prefix for this Queue service client, using the specified - * details setting, request options, and operation context. - * - * @param prefix - * A String that represents the queue name prefix. - * @param detailsIncluded - * A {@link QueueListingDetails} value that indicates whether - * queue metadata will be returned. - * @param options - * A {@link QueueRequestOptions} object that specifies any - * additional options for the request. Specifying null will use the default request options - * from - * the associated service client ( {@link CloudQueue}). - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An iterable collection of {@link CloudQueue} objects that - * represents the specified queues for this client. - */ - @DoesServiceRequest - public Iterable listQueues(final String prefix, final QueueListingDetails detailsIncluded, - QueueRequestOptions options, OperationContext opContext) { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this); - - final SegmentedStorageOperation> impl = new SegmentedStorageOperation>( - options, null) { - @Override - public ResultSegment execute(final CloudQueueClient client, final Void dontCare, - final OperationContext opContext) throws Exception { - - final ResultSegment result = CloudQueueClient.this.listQueuesCore(prefix, detailsIncluded, - -1, this.getToken(), this.getRequestOptions(), this, opContext); - - this.setToken(result.getContinuationToken()); - return result; - } - }; - - return new LazySegmentedIterable(impl, this, null, - options.getRetryPolicyFactory(), opContext); - } - - /** - * Gets a result segment containing a collection of queues from the storage - * service with the specified parameters. - * - * @param prefix - * A String containing the queue name prefix to - * filter the results with. - * @param detailsIncluded - * A {@link QueueListingDetails} value that indicates whether - * queue metadata will be returned. - * @param maxResults - * The maximum number of queue results to retrieve. - * @param continuationToken - * A {@link ResultContinuation} object that represents a - * continuation token returned by a previous listing operation. - * @param options - * A {@link QueueRequestOptions} object that specifies any - * additional options for the request. Specifying null will use the default request options - * from - * the associated service client ( {@link CloudQueue}). - * @param taskReference - * A {@link StorageOperation} reference to the encapsulating - * task. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return A {@link ResultSegment} of {@link CloudQueue} objects that - * contains a segment of the iterable collection of {@link CloudQueue} objects that represent the requested - * queues in - * the storage service. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws XMLStreamException - * @throws InvalidKeyException - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - ResultSegment listQueuesCore(final String prefix, final QueueListingDetails detailsIncluded, - final int maxResults, final ResultContinuation continuationToken, final RequestOptions options, - final StorageOperation> taskReference, - final OperationContext opContext) throws IOException, URISyntaxException, XMLStreamException, - InvalidKeyException, StorageException { - - Utility.assertContinuationType(continuationToken, ResultContinuationType.QUEUE); - - final ListingContext listingContext = new ListingContext(prefix, maxResults); - listingContext.setMarker(continuationToken != null ? continuationToken.getNextMarker() : null); - - final HttpURLConnection listQueueRequest = QueueRequest.list(this.getEndpoint(), - options.getTimeoutIntervalInMs(), listingContext, detailsIncluded, opContext); - taskReference.setConnection(listQueueRequest); - - taskReference.signRequest(this, listQueueRequest, -1L, null); - - ExecutionEngine.processRequest(listQueueRequest, opContext, taskReference.getResult()); - - if (taskReference.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - taskReference.setNonExceptionedRetryableFailure(true); - return null; - } - - final ListQueuesResponse response = new ListQueuesResponse(listQueueRequest.getInputStream()); - response.parseResponse(this); - - ResultContinuation newToken = null; - - if (response.getNextMarker() != null) { - newToken = new ResultContinuation(); - newToken.setNextMarker(response.getNextMarker()); - newToken.setContinuationType(ResultContinuationType.QUEUE); - } - - final ResultSegment resSegment = new ResultSegment(response.getQueues(this), - maxResults, newToken); - - return resSegment; - } - - /** - * Gets a result segment of an iterable collection of queues for this Queue - * service client. - * - * @return A {@link ResultSegment} of {@link CloudQueue} objects that - * contains a segment of the iterable collection of {@link CloudQueue} objects that represent the requested - * queues in - * the storage service. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment listQueuesSegmented() throws StorageException { - return this.listQueuesSegmented(null, QueueListingDetails.NONE, 0, null, null, null); - } - - /** - * Gets a result segment of an iterable collection of queues whose names - * begin with the specified prefix for this Queue service client. - * - * @return A {@link ResultSegment} of {@link CloudQueue} objects that - * contains a segment of the iterable collection of {@link CloudQueue} objects that represent the requested - * queues in - * the storage service. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment listQueuesSegmented(final String prefix) throws StorageException { - return this.listQueuesSegmented(prefix, QueueListingDetails.NONE, 0, null, null, null); - } - - /** - * Gets a result segment of an iterable collection of queues whose names - * begin with the specified prefix for this queue, using the specified - * listing details options, request options, and operation context. - * - * @param prefix - * A String that represents the prefix of the queue - * name to match. - * @param detailsIncluded - * A {@link QueueListingDetails} value that indicates whether - * queue metadata will be returned. - * @param maxResults - * The maximum number of queue results to retrieve. - * @param continuationToken - * A {@link ResultContinuation} object that represents a - * continuation token returned by a previous listing operation. - * @param options - * A {@link QueueRequestOptions} object that specifies any - * additional options for the request. Specifying null will use the default request options - * from - * the associated service client ( {@link CloudQueue}). - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return A {@link ResultSegment} of {@link CloudQueue} objects that - * contains a segment of the iterable collection of {@link CloudQueue} objects that represent the requested - * queues in - * the storage service. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment listQueuesSegmented(final String prefix, - final QueueListingDetails detailsIncluded, final int maxResults, - final ResultContinuation continuationToken, QueueRequestOptions options, OperationContext opContext) - throws StorageException { - - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new QueueRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this); - - Utility.assertContinuationType(continuationToken, ResultContinuationType.QUEUE); - - final StorageOperation> impl = new StorageOperation>( - options) { - @Override - public ResultSegment execute(final CloudQueueClient client, final Void dontCare, - final OperationContext opContext) throws Exception { - return CloudQueueClient.this.listQueuesCore(prefix, detailsIncluded, maxResults, continuationToken, - this.getRequestOptions(), this, opContext); - } - }; - - return ExecutionEngine.executeWithRetry(this, null, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Uploads a new configuration of service properties to the storage service, - * using the default request options. This includes Metrics and Logging - * Configuration. - * - * @param properties - * The {@link ServiceProperties} to upload. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - @Override - public void uploadServiceProperties(final ServiceProperties properties) throws StorageException { - this.uploadServiceProperties(properties, null, null); - } - - /** - * Uploads a new configuration of service properties to the storage service, - * using the specified request options and operation context. This includes - * Metrics and Logging Configuration. - * - * @param properties - * The {@link ServiceProperties} to upload. - * @param options - * A {@link RequestOptions} object that specifies any additional - * options for the request. Specifying null will use - * the default request options from the associated service client - * ( {@link CloudBlobClient}{@link CloudQueueClient}). - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - @Override - public void uploadServiceProperties(final ServiceProperties properties, final RequestOptions options, - final OperationContext opContext) throws StorageException { - if (!Utility.isNullOrEmpty(properties.getDefaultServiceVersion())) { - throw new IllegalArgumentException( - "DefaultServiceVersion can only be set for the Blob service and the request must be made using the 2011-08-18 version"); - } - super.uploadServiceProperties(properties, options, opContext); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueueMessage.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueueMessage.java deleted file mode 100644 index 496002375947a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/CloudQueueMessage.java +++ /dev/null @@ -1,276 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.io.UnsupportedEncodingException; -import java.util.Date; - -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Represents a message in the Windows Azure Queue service. - */ -public class CloudQueueMessage { - - /** - * Holds the message ID. - */ - protected String id; - - /** - * Holds the message's pop receipt. - */ - protected String popReceipt; - - /** - * Holds the time that the message was added to the queue. - */ - protected Date insertionTime; - - /** - * Holds the time that the message expires. - */ - protected Date expirationTime; - - /** - * Holds the time that the message will next be visible. - */ - protected Date nextVisibleTime; - - /** - * Holds the message content. - */ - protected String messageContent; - - /** - * Holds the dequeue count. - */ - protected int dequeueCount; - - /** - * Holds the message type. - */ - protected QueueMessageType messageType; - - /** - * Initializes a new instance of the CloudQueueMessage class (used - * internally). - */ - CloudQueueMessage() { - // no op - } - - /** - * Initializes a new instance of the CloudQueueMessage class with an array - * of byte containing the message. - * - * @param content - * The array of byte that contains the message. - */ - public CloudQueueMessage(final byte[] content) { - this.setMessageContent(content); - } - - /** - * Initializes a new instance of the CloudQueueMessage class with a string - * containing the message. - * - * @param content - * The String that contains the message. - */ - public CloudQueueMessage(final String content) { - this.setMessageContent(content); - } - - /** - * Gets the dequeue count. - * - * @return The dequeue count. - */ - public final int getDequeueCount() { - return this.dequeueCount; - } - - /** - * Gets the time that the message expires. - * - * @return The time that the message expires. - */ - public final Date getExpirationTime() { - return this.expirationTime; - } - - /** - * Gets the message ID. - * - * @return A String that contains the message ID. - */ - public final String getId() { - return this.id; - } - - /** - * Gets the time that the message was added to the queue. - * - * @return The time that the message was added to the queue. - */ - public final Date getInsertionTime() { - return this.insertionTime; - } - - /** - * Gets the content of the message as a byte array. - * - * @return An array of byte with the content of the message. - * - * @throws StorageException - * If a storage service error occurred. - */ - public final byte[] getMessageContentAsByte() throws StorageException { - if (Utility.isNullOrEmpty(this.messageContent)) { - return new byte[0]; - } - - if (this.messageType == QueueMessageType.RAW_STRING) { - try { - return this.messageContent.getBytes("UTF8"); - } - catch (final UnsupportedEncodingException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - else { - return Base64.decode(this.messageContent); - } - } - - /** - * Gets the content of the message as a string. - * - * @return A String with the content of the message. - * - * @throws StorageException - * If a storage service error occurred. - */ - public final String getMessageContentAsString() throws StorageException { - if (this.messageType == QueueMessageType.RAW_STRING) { - return this.messageContent; - } - else { - if (Utility.isNullOrEmpty(this.messageContent)) { - return null; - } - - try { - return new String(Base64.decode(this.messageContent), "UTF-8"); - } - catch (final UnsupportedEncodingException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - } - - /** - * Gets the content of the message for transfer (internal use only). - * - * @return A String with the content of the message. - * - * @throws StorageException - */ - protected final String getMessageContentForTransfer(final boolean shouldEncodeMessage) throws StorageException { - String result = null; - if (this.messageType == QueueMessageType.RAW_STRING && shouldEncodeMessage) { - result = Base64.encode(this.getMessageContentAsByte()); - - } - else { - result = this.messageContent; - } - - if (result != null && result.length() > QueueConstants.MAX_MESSAGE_SIZE) { - throw new IllegalArgumentException(String.format("The message size can't be larger than %s bytes. ", - QueueConstants.MAX_MESSAGE_SIZE)); - } - - return result; - } - - /** - * Gets the time that the message will next be visible. - * - * @return A java.util.Date with the time that the message will - * next be visible. - */ - public final Date getNextVisibleTime() { - return this.nextVisibleTime; - } - - /** - * Gets the message's pop receipt. - * - * @return A String containing the message's pop receipt. - */ - public final String getPopReceipt() { - return this.popReceipt; - } - - /** - * Sets the expiration time for the message. - * - * @param expirationTime - * The java.util.Date representing the expiration - * time to set on the message. - */ - public final void setExpirationTime(final Date expirationTime) { - this.expirationTime = expirationTime; - } - - /** - * Sets the content of the message as an array of byte. - * - * @param content - * The content of the message. - */ - public final void setMessageContent(final byte[] content) { - Utility.assertNotNull("content", content); - - this.messageContent = Base64.encode(content); - this.messageType = QueueMessageType.BASE_64_ENCODED; - } - - /** - * Sets the content of the message as a String. - * - * @param content - * The content of the message. - */ - public final void setMessageContent(final String content) { - this.messageContent = content; - this.messageType = QueueMessageType.RAW_STRING; - } - - /** - * Sets the time for the message to become visible in the queue. - * - * @param nextVisibleTime - * The java.util.Date representing the time to set - * for the message to be visible. - */ - public final void setNextVisibleTime(final Date nextVisibleTime) { - this.nextVisibleTime = nextVisibleTime; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/ListQueuesResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/ListQueuesResponse.java deleted file mode 100644 index 2d0d4c0d3b97f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/ListQueuesResponse.java +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import java.io.InputStream; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. Provides methods for parsing the response stream - * from a queue listing operation. - */ -final class ListQueuesResponse { - - /** - * The list of queues from the response to a list queues operation. - */ - private ArrayList queues = new ArrayList(); - - /** - * A value indicating if the response has been fully parsed. - */ - private boolean isParsed; - - /** - * The marker value from the response. - */ - private String marker; - - /** - * The max results value from the response. - */ - private int maxResults; - - /** - * The next marker value from the response, to be passed as the marker value - * in the next queue listing request. - */ - private String nextMarker; - - /** - * The container prefix value from the response. - */ - private String prefix; - - /** - * The InputStream containing the response body from a queue - * listing operation. - */ - private final InputStream streamRef; - - /** - * Class constructor specifying an input stream created from the response - * body to a list queues operation. - * - * @param stream - * An InputStream to parse for the results of a list - * queues operation. - */ - public ListQueuesResponse(final InputStream stream) { - this.streamRef = stream; - } - - /** - * Gets the value of the Marker element in the response to a list queues - * operation. This value is not initialized until {@link #getQueues(CloudQueueClient)} or - * {@link #parseResponse(CloudQueueClient)} has been called, and is only - * present if the list queues request specified the marker. - * - * @return A String containing the value of the Marker element - * in the response. - */ - public String getMarker() { - return this.marker; - } - - /** - * Gets the value of the MaxResults element in the response to a list queues - * operation. This value is not initialized until {@link #getQueues(CloudQueueClient)} or - * {@link #parseResponse(CloudQueueClient)} has been called, and is only - * present if the request specified a maxresults value. - * - * @return An int containing the value of the MaxResults - * element in the response. - */ - public int getMaxResults() { - return this.maxResults; - } - - /** - * Gets the value of the NextMarker element in the response to a list queues - * operation. This value is not initialized until {@link #getQueues(CloudQueueClient)} or - * {@link #parseResponse(CloudQueueClient)} has been called, and is only - * present when maxresults was specified in the request, and more results - * are available that have not yet been returned. This value may be sent as - * the marker value in a list queues request to retrieve the next set of - * queues. - * - * @return A String containing the value of the NextMarker - * element in the response. - */ - public String getNextMarker() { - return this.nextMarker; - } - - /** - * Gets the value of the Prefix element in the response to a list queues - * operation. This value is not initialized until {@link #getQueues(CloudQueueClient)} or - * {@link #parseResponse(CloudQueueClient)} has been called, and is only - * present if the request specified a prefix value. The list queues result - * is filtered to return only queues with names that begin with the - * specified prefix. - * - * @return A String containing the value of the Prefix element - * in the response. - */ - public String getPrefix() { - return this.prefix; - } - - /** - * Gets the list of queues returned by the list queues request as an ArrayList of (@link CloudQueue} - * objects. - * - * @param serviceClient - * A {@link CloudQueueClient} object associated with the storage - * service. - * - * @return an ArrayList of {@link CloudQueue} objects returned - * by the list queues operation. - * - * @throws XMLStreamException - * @throws StorageException - */ - public ArrayList getQueues(final CloudQueueClient serviceClient) throws XMLStreamException, - StorageException { - if (!this.isParsed) { - this.parseResponse(serviceClient); - } - - return this.queues; - } - - /** - * Parses the input stream containing the response body of the list queues - * request result and populates the class data. - * - * @param serviceClient - * A {@link CloudQueueClient} object associated with the storage - * service. - * - * @throws XMLStreamException - * If the input stream cannot be read or parsed as a list queues - * response. - * @throws StorageException - */ - public void parseResponse(final CloudQueueClient serviceClient) throws XMLStreamException, StorageException { - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(this.streamRef); - String tempParseString = null; - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - // 1. get enumerationResults Header - eventType = xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, "EnumerationResults"); - - // check if there are more events in the input stream - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.MAX_RESULTS_ELEMENT)) { - tempParseString = Utility.readElementFromXMLReader(xmlr, Constants.MAX_RESULTS_ELEMENT); - this.maxResults = Integer.parseInt(tempParseString); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.MARKER_ELEMENT)) { - this.marker = Utility.readElementFromXMLReader(xmlr, Constants.MARKER_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.NEXT_MARKER_ELEMENT)) { - this.nextMarker = Utility.readElementFromXMLReader(xmlr, Constants.NEXT_MARKER_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.PREFIX_ELEMENT)) { - this.prefix = Utility.readElementFromXMLReader(xmlr, Constants.PREFIX_ELEMENT); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(QueueConstants.QUEUES_ELEMENT)) { - try { - this.queues = QueueDeserializationHelper.readQueues(xmlr, serviceClient); - } - catch (final URISyntaxException e) { - throw new XMLStreamException(e); - } - catch (final ParseException e) { - throw new XMLStreamException(e); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, QueueConstants.QUEUES_ELEMENT); - // eventType = xmlr.next(); - } - else if (eventType == XMLStreamConstants.END_ELEMENT && "EnumerationResults".equals(name)) { - break; - } - } - } - - this.isParsed = true; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/MessageUpdateFields.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/MessageUpdateFields.java deleted file mode 100644 index d01b1cf268635..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/MessageUpdateFields.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -/** - * Flags for the values to set when updating messages. - */ -public enum MessageUpdateFields { - /** - * Set to update the message visibility timeout. - */ - VISIBILITY(1), - - /** - * Set to update the message content. - */ - CONTENT(2); - - /** - * Returns the value of this enum. - */ - public int value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - MessageUpdateFields(final int val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueAccessPolicyResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueAccessPolicyResponse.java deleted file mode 100644 index 3c3a7d56dae9f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueAccessPolicyResponse.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.io.InputStream; -import java.text.ParseException; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.AccessPolicyResponseBase; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse SharedAccessPolicies from an input stream. - */ -final class QueueAccessPolicyResponse extends AccessPolicyResponseBase { - - /** - * Initializes the AccessPolicyResponse object - * - * @param stream - * the input stream to read error details from. - */ - public QueueAccessPolicyResponse(final InputStream stream) { - super(stream); - } - - /** - * Populates the object from the XMLStreamReader, reader must be at Start element of AccessPolicy. - * - * @param xmlr - * the XMLStreamReader object - * @throws XMLStreamException - * if there is a parsing exception - * @throws ParseException - * if a date value is not correctly encoded - */ - @Override - protected SharedAccessQueuePolicy readPolicyFromXML(final XMLStreamReader xmlr) throws XMLStreamException, - ParseException { - int eventType = xmlr.getEventType(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.ACCESS_POLICY); - final SharedAccessQueuePolicy retPolicy = new SharedAccessQueuePolicy(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.PERMISSION)) { - retPolicy.setPermissions(SharedAccessQueuePolicy.permissionsFromString(Utility - .readElementFromXMLReader(xmlr, Constants.PERMISSION))); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.START)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.START); - retPolicy.setSharedAccessStartTime(Utility.parseISO8061LongDateFromString(tempString)); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.EXPIRY)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.EXPIRY); - retPolicy.setSharedAccessExpiryTime(Utility.parseISO8061LongDateFromString(tempString)); - } - else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(Constants.ACCESS_POLICY)) { - break; - } - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.ACCESS_POLICY); - return retPolicy; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueConstants.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueConstants.java deleted file mode 100644 index d82fb09e4d05c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueConstants.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -/** - * RESERVED FOR INTERNAL USE. Holds the Constants used for the Queue Service. - */ -final class QueueConstants { - /** - * Default client side timeout, in milliseconds, for queue service. - */ - public static final int DEFAULT_QUEUE_CLIENT_TIMEOUT_IN_MS = 30 * 1000; - - /** - * The maximum message size in bytes. - */ - public static final long MAX_MESSAGE_SIZE = 64 * com.microsoft.windowsazure.services.core.storage.Constants.KB; - - /** - * The maximum number of messages that can be peeked or retrieved at a time. - */ - public static final int MAX_NUMBER_OF_MESSAGES_TO_PEEK = 32; - - /** - * Default visibility time out for the retrieve message operation. - */ - public static final int DEFAULT_VISIBILITY_MESSAGE_TIMEOUT_IN_SECONDS = 30; - - /** - * The maximum amount of time a message is kept inside the queue, in seconds. - */ - public static final int MAX_TIME_TO_LIVE_IN_SECONDS = 7 * 24 * 60 * 60; - - /** - * XML element for a queue. - */ - public static final String QUEUE_ELEMENT = "Queue"; - - /** - * XML element for queues. - */ - public static final String QUEUES_ELEMENT = "Queues"; - - /** - * XML element for QueueMessagesList. - */ - public static final String QUEUE_MESSAGES_LIST_ELEMENT = "QueueMessagesList"; - - /** - * XML element for QueueMessage. - */ - public static final String QUEUE_MESSAGE_ELEMENT = "QueueMessage"; - - /** - * XML element for MessageId. - */ - public static final String MESSAGE_ID_ELEMENT = "MessageId"; - - /** - * XML element for InsertionTime. - */ - public static final String INSERTION_TIME_ELEMENT = "InsertionTime"; - - /** - * XML element for ExpirationTime. - */ - public static final String EXPIRATION_TIME_ELEMENT = "ExpirationTime"; - - /** - * XML element for PopReceipt. - */ - public static final String POP_RECEIPT_ELEMENT = "PopReceipt"; - - /** - * XML element for TimeNextVisible. - */ - public static final String TIME_NEXT_VISIBLE_ELEMENT = "TimeNextVisible"; - - /** - * XML element for DequeueCount. - */ - public static final String DEQUEUE_COUNT_ELEMENT = "DequeueCount"; - - /** - * XML element for MessageText. - */ - public static final String MESSAGE_TEXT_ELEMENT = "MessageText"; - - /** - * The URI path component to access the messages in a queue. - */ - public static final String MESSAGES = "messages"; - - /** - * The header that specifies the approximate message count of a queue. - */ - public static final String APPROXIMATE_MESSAGES_COUNT = com.microsoft.windowsazure.services.core.storage.Constants.PREFIX_FOR_STORAGE_HEADER - + "approximate-messages-count"; - - /** - * Private Default Ctor. - */ - private QueueConstants() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueDeserializationHelper.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueDeserializationHelper.java deleted file mode 100644 index 22c01e64a4926..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueDeserializationHelper.java +++ /dev/null @@ -1,261 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.DeserializationHelper; - -/** - * RESERVED FOR INTERNAL USE. Class to provide object deserialization for - * queues. - */ -final class QueueDeserializationHelper { - /** - * Populates the message from an XMLStreamReader. - * - * @param xmlr - * The XMLStreamReader to read from. - * @param shouldEncodeMessage - * A flag indicating whether messages should be base-64 encoded. - * - * @return A {@link CloudQueueMessage} from the stream. - * - * @throws XMLStreamException - * if there is an error parsing the stream - * @throws ParseException - * if there is an error in parsing a date - * @throws URISyntaxException - * if the uri is invalid - * @throws StorageException - * If a storage service error occurred during the operation. - */ - protected static CloudQueueMessage readMessage(final XMLStreamReader xmlr, final boolean shouldEncodeMessage) - throws XMLStreamException, ParseException, URISyntaxException, StorageException { - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, QueueConstants.QUEUE_MESSAGE_ELEMENT); - - final CloudQueueMessage message = new CloudQueueMessage(); - message.messageType = shouldEncodeMessage ? QueueMessageType.BASE_64_ENCODED : QueueMessageType.RAW_STRING; - - int eventType = xmlr.getEventType(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(QueueConstants.MESSAGE_ID_ELEMENT)) { - message.id = Utility.readElementFromXMLReader(xmlr, QueueConstants.MESSAGE_ID_ELEMENT); - } - else if (name.equals(QueueConstants.INSERTION_TIME_ELEMENT)) { - message.insertionTime = Utility.parseRFC1123DateFromStringInGMT(Utility.readElementFromXMLReader( - xmlr, QueueConstants.INSERTION_TIME_ELEMENT)); - } - else if (name.equals(QueueConstants.EXPIRATION_TIME_ELEMENT)) { - message.expirationTime = Utility.parseRFC1123DateFromStringInGMT(Utility.readElementFromXMLReader( - xmlr, QueueConstants.EXPIRATION_TIME_ELEMENT)); - } - else if (name.equals(QueueConstants.POP_RECEIPT_ELEMENT)) { - message.popReceipt = Utility.readElementFromXMLReader(xmlr, QueueConstants.POP_RECEIPT_ELEMENT); - } - else if (name.equals(QueueConstants.TIME_NEXT_VISIBLE_ELEMENT)) { - message.nextVisibleTime = Utility.parseRFC1123DateFromStringInGMT(Utility.readElementFromXMLReader( - xmlr, QueueConstants.TIME_NEXT_VISIBLE_ELEMENT)); - } - else if (name.equals(QueueConstants.DEQUEUE_COUNT_ELEMENT)) { - message.dequeueCount = Integer.parseInt(Utility.readElementFromXMLReader(xmlr, - QueueConstants.DEQUEUE_COUNT_ELEMENT)); - } - else if (name.equals(QueueConstants.MESSAGE_TEXT_ELEMENT)) { - message.messageContent = Utility - .readElementFromXMLReader(xmlr, QueueConstants.MESSAGE_TEXT_ELEMENT); - } - - } - else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(QueueConstants.QUEUE_MESSAGE_ELEMENT)) { - break; - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, QueueConstants.QUEUE_MESSAGE_ELEMENT); - return message; - } - - /** - * Populates CloudQueueMessage objects from the XMLStreamReader; the reader - * must be at the Start element of QueuesElement. - * - * @param stream - * The InputStream object to deserialize from. - * @param shouldEncodeMessage - * A flag indicating whether messages should be base-64 encoded. - * - * @return An ArrayList of {@link CloudQueueMessage} from the - * stream. - * - * @throws XMLStreamException - * If there is a parsing exception. - * @throws ParseException - * If a date value is not correctly encoded. - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static ArrayList readMessages(final InputStream stream, final boolean shouldEncodeMessage) - throws XMLStreamException, ParseException, URISyntaxException, StorageException { - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(stream); - - // Start document - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - - eventType = xmlr.next(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, QueueConstants.QUEUE_MESSAGES_LIST_ELEMENT); - - final ArrayList messages = new ArrayList(); - - eventType = xmlr.next(); - while (eventType == XMLStreamConstants.START_ELEMENT && xmlr.hasName() - && QueueConstants.QUEUE_MESSAGE_ELEMENT.equals(xmlr.getName().toString())) { - messages.add(QueueDeserializationHelper.readMessage(xmlr, shouldEncodeMessage)); - eventType = xmlr.next(); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, QueueConstants.QUEUE_MESSAGES_LIST_ELEMENT); - return messages; - } - - /** - * Reserved for internal use. - * - * Populates the queue from an XMLStreamReader - * - * @param xmlr - * The XMLStreamReader to read from. - * @param serviceClient - * The {@link CloudQueueClient} to create the return value with. - * - * @return A {@link CloudQueue} populated with the deserialized data. - * - * @throws XMLStreamException - * If there is a parsing exception. - * @throws ParseException - * If a date value is not correctly encoded. - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - protected static CloudQueue readQueue(final XMLStreamReader xmlr, final CloudQueueClient serviceClient) - throws XMLStreamException, ParseException, URISyntaxException, StorageException { - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, QueueConstants.QUEUE_ELEMENT); - - String queueName = null; - URI queueUri = null; - HashMap queueMetadata = null; - - int eventType = xmlr.getEventType(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - final String name = xmlr.getName().toString(); - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(Constants.URL_ELEMENT)) { - queueUri = new URI(Utility.readElementFromXMLReader(xmlr, Constants.URL_ELEMENT)); - } - else if (name.equals(Constants.NAME_ELEMENT)) { - queueName = Utility.readElementFromXMLReader(xmlr, Constants.NAME_ELEMENT); - } - else if (name.equals(Constants.METADATA_ELEMENT)) { - // parse metadata - queueMetadata = DeserializationHelper.parseMetadateFromXML(xmlr); - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.METADATA_ELEMENT); - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(QueueConstants.QUEUE_ELEMENT)) { - break; - } - } - - final CloudQueue queue = new CloudQueue(queueUri, serviceClient); - queue.setMetadata(queueMetadata); - queue.setName(queueName); - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, QueueConstants.QUEUE_ELEMENT); - return queue; - } - - /** - * Populates CloudQueue objects from the XMLStreamReader; the reader must be - * at the Start element of QueuesElement. - * - * @param xmlr - * The XMLStreamReader to read from. - * @param serviceClient - * The {@link CloudQueueClient} to create the return value with. - * - * @return An ArrayList of{@link CloudQueue} populated with the - * deserialized data. - * - * @throws XMLStreamException - * If there is a parsing exception. - * @throws ParseException - * If a date value is not correctly encoded. - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static ArrayList readQueues(final XMLStreamReader xmlr, final CloudQueueClient serviceClient) - throws XMLStreamException, ParseException, URISyntaxException, StorageException { - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, QueueConstants.QUEUES_ELEMENT); - - final ArrayList queues = new ArrayList(); - - eventType = xmlr.next(); - while (eventType == XMLStreamConstants.START_ELEMENT && xmlr.hasName() - && QueueConstants.QUEUE_ELEMENT.equals(xmlr.getName().toString())) { - queues.add(readQueue(xmlr, serviceClient)); - eventType = xmlr.next(); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, QueueConstants.QUEUES_ELEMENT); - return queues; - } - - /** - * Private Default Ctor. - */ - private QueueDeserializationHelper() { - // No op - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueListingDetails.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueListingDetails.java deleted file mode 100644 index 0a17cda55bc1f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueListingDetails.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -/** - * Specifies which details to include when listing the queues in this storage - * account. - */ -public enum QueueListingDetails { - /** - * Specifies including all available details. - */ - ALL(1), - - /** - * Specifies including queue metadata. - */ - METADATA(1), - - /** - * Specifies including no additional details. - */ - NONE(0); - - /** - * Returns the value of this enum. - */ - public int value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - QueueListingDetails(final int val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueMessageType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueMessageType.java deleted file mode 100644 index 6712d9e62e946..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueMessageType.java +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -/** - * Reserved for internal use. Specifies queue message type. - */ -public enum QueueMessageType { - /** - * Indicates the message object stores the raw text string. - */ - RAW_STRING, - - /** - * Indicates the message object stores the Base64-Encoded representation of - * the raw data. - */ - BASE_64_ENCODED -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueuePermissions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueuePermissions.java deleted file mode 100644 index 958968cb0b912..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueuePermissions.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import java.util.HashMap; - -/** - * Represents the permissions for a container. - */ - -public final class QueuePermissions { - - /** - * Gets the set of shared access policies for the queue. - */ - private HashMap sharedAccessPolicies; - - /** - * Creates an instance of the QueuePermissions class. - */ - public QueuePermissions() { - this.sharedAccessPolicies = new HashMap(); - } - - /** - * Returns the set of shared access policies for the queue. - * - * @return A HashMap object of {@link SharedAccessQueuePolicy} objects that represent the set of shared - * access policies for the queue. - */ - public HashMap getSharedAccessPolicies() { - return this.sharedAccessPolicies; - } - - /** - * Sets the set of shared access policies for the queue. - * - * @param sharedAccessPolicies - * The set of shared access policies to set for the queue, represented by a HashMap object - * of {@link SharedAccessQueuePolicy} objects. - */ - public void setSharedAccessPolicies(final HashMap sharedAccessPolicies) { - this.sharedAccessPolicies = sharedAccessPolicies; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueRequest.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueRequest.java deleted file mode 100644 index c00315de54436..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueRequest.java +++ /dev/null @@ -1,740 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map.Entry; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseRequest; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ListingContext; - -/** - * RESERVED FOR INTERNAL USE. Provides a set of methods for constructing web - * requests for queue operations. - */ -final class QueueRequest { - /** - * Adds user-defined metadata to the web request as one or more name-value - * pairs. - * - * @param request - * The HttpURLConnection web request to add the - * metadata to. - * @param metadata - * A HashMap containing the user-defined metadata to - * add. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - */ - public static void addMetadata(final HttpURLConnection request, final HashMap metadata, - final OperationContext opContext) { - BaseRequest.addMetadata(request, metadata, opContext); - } - - /** - * Constructs a web request to clear all the messages in the queue. Sign the - * web request with a length of -1L. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection clearMessages(final URI uri, final int timeout, final OperationContext opContext) - throws URISyntaxException, IOException, StorageException { - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, null, opContext); - - request.setRequestMethod("DELETE"); - - return request; - } - - /** - * Constructs a web request to create a new queue. Sign the web request with - * a length of 0. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection create(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - return BaseRequest.create(uri, timeout, null, opContext); - } - - /** - * Constructs a web request to delete the queue. Sign the web request with a - * length of -1L. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection delete(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - return BaseRequest.delete(uri, timeout, null, opContext); - } - - /** - * Constructs a web request to delete a message from the queue. Sign the web - * request with a length of -1L. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param popReceipt - * A String that contains the pop receipt value - * returned from an earlier call to {@link CloudQueueMessage#getPopReceipt} for the message to - * delete. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws URISyntaxException - * If the URI is not valid. - * @throws IOException - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection deleteMessage(final URI uri, final int timeout, final String popReceipt, - final OperationContext opContext) throws URISyntaxException, IOException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("popreceipt", popReceipt); - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("DELETE"); - - return request; - } - - /** - * Constructs a web request to download user-defined metadata and the - * approximate message count for the queue. Sign the web request with a - * length of -1L. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection downloadAttributes(final URI uri, final int timeout, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - return BaseRequest.getMetadata(uri, timeout, null, opContext); - } - - /** - * Generates the message request body from a string containing the message. - * The message must be encodable as UTF-8. To be included in a web request, - * this message request body must be written to the output stream of the web - * request. - * - * @param message - * A String containing the message to wrap in a message request body. - * - * @return An array of byte containing the message request body - * encoded as UTF-8. - * - * @throws XMLStreamException - * @throws StorageException - * If the message cannot be encoded as UTF-8. - */ - public static byte[] generateMessageRequestBody(final String message) throws XMLStreamException, StorageException { - final StringWriter outWriter = new StringWriter(); - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outWriter); - - // default is UTF8 - xmlw.writeStartDocument(); - xmlw.writeStartElement(QueueConstants.QUEUE_MESSAGE_ELEMENT); - - xmlw.writeStartElement(QueueConstants.MESSAGE_TEXT_ELEMENT); - xmlw.writeCharacters(message); - xmlw.writeEndElement(); - - // end QueueMessage_ELEMENT - xmlw.writeEndElement(); - - // end doc - xmlw.writeEndDocument(); - try { - return outWriter.toString().getBytes("UTF8"); - } - catch (final UnsupportedEncodingException e) { - throw Utility.generateNewUnexpectedStorageException(e); - } - } - - /** - * Constructs a web request to return a listing of all queues in this - * storage account. Sign the web request with a length of -1L. - * - * @param uri - * A URI object that specifies the absolute URI to - * the storage account. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param listingContext - * A {@link ListingContext} object that specifies parameters for - * the listing operation, if any. May be null. - * @param detailsIncluded - * A {@link QueueListingDetails} object that specifies additional - * details to return with the listing, if any. May be null. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection list(final URI uri, final int timeout, final ListingContext listingContext, - final QueueListingDetails detailsIncluded, final OperationContext opContext) throws URISyntaxException, - IOException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "list"); - - if (listingContext != null) { - if (!Utility.isNullOrEmpty(listingContext.getPrefix())) { - builder.add("prefix", listingContext.getPrefix()); - } - - if (!Utility.isNullOrEmpty(listingContext.getMarker())) { - builder.add("marker", listingContext.getMarker()); - } - - if (listingContext.getMaxResults() != null && listingContext.getMaxResults() > 0) { - builder.add("maxresults", listingContext.getMaxResults().toString()); - } - } - - if (detailsIncluded == QueueListingDetails.ALL || detailsIncluded == QueueListingDetails.METADATA) { - builder.add("include", "metadata"); - } - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("GET"); - - return request; - } - - /** - * Constructs a web request to retrieve a specified number of messages from - * the front of the queue without changing their visibility. Sign the web - * request with a length of -1L. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param numberOfMessages - * A nonzero value that specifies the number of messages to - * retrieve from the queue, up to a maximum of 32. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection peekMessages(final URI uri, final int timeout, final int numberOfMessages, - final OperationContext opContext) throws URISyntaxException, IOException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("peekonly", "true"); - - if (numberOfMessages != 0) { - builder.add("numofmessages", Integer.toString(numberOfMessages)); - } - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("GET"); - - return request; - } - - /** - * Constructs a web request to add a message to the back of the queue. Write - * the encoded message request body generated with a call to {@link #generateMessageRequestBody(String)} to the - * output stream of the - * request. Sign the web request with the length of the encoded message - * request body. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param visibilityTimeoutInSeconds - * Specifies the length of time for the message to be invisible - * in seconds, starting when it is added to the queue. A value of - * 0 will make the message visible immediately. The value must be - * greater than or equal to 0, and cannot be larger than 7 days. - * The visibility timeout of a message cannot be set to a value - * greater than the time-to-live time. - * @param timeToLiveInSeconds - * Specifies the time-to-live interval for the message, in - * seconds. The maximum time-to-live allowed is 7 days. If this - * parameter is 0, the default time-to-live of 7 days is used. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection putMessage(final URI uri, final int timeout, final int visibilityTimeoutInSeconds, - final int timeToLiveInSeconds, final OperationContext opContext) throws IOException, URISyntaxException, - StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - - if (visibilityTimeoutInSeconds != 0) { - builder.add("visibilitytimeout", Integer.toString(visibilityTimeoutInSeconds)); - } - - if (timeToLiveInSeconds != 0) { - builder.add("messagettl", Integer.toString(timeToLiveInSeconds)); - } - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setDoOutput(true); - request.setRequestMethod("POST"); - - return request; - } - - /** - * Constructs a web request to retrieve messages from the front of the - * queue. Sign the web request with a length of -1L. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param numberOfMessages - * A nonzero value that specifies the number of messages to - * retrieve from the queue, up to a maximum of 32. - * @param visibilityTimeoutInSeconds - * Specifies the visibility timeout value in seconds, relative to - * server time, to make the retrieved messages invisible until - * the visibility timeout expires. The value must be larger than - * or equal to 0, and cannot be larger than 7 days. The - * visibility timeout of a message can be set to a value later - * than the expiry time, which will prevent the message from - * being retrieved again whether it is processed or not. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection retrieveMessages(final URI uri, final int timeout, final int numberOfMessages, - final int visibilityTimeoutInSeconds, final OperationContext opContext) throws URISyntaxException, - IOException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - - if (numberOfMessages != 0) { - builder.add("numofmessages", Integer.toString(numberOfMessages)); - } - - builder.add("visibilitytimeout", Integer.toString(visibilityTimeoutInSeconds)); - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("GET"); - - return request; - } - - /** - * Constructs a web request to set user-defined metadata for the queue. Each - * call to this operation replaces all existing metadata attached to the - * queue. Use the {@link #addMetadata} method to specify the metadata to set - * on the queue. To remove all metadata from the queue, call this web - * request with no metadata added. Sign the web request with a length of 0. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection setMetadata(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - return BaseRequest.setMetadata(uri, timeout, null, opContext); - } - - /** - * Constructs a web request to update the visibility timeout of a message in - * the queue. Optionally updates the message content if a message request - * body is written to the output stream of the web request. The web request - * should be signed with the length of the encoded message request body if - * one is included, or a length of 0 if no message request body is included. - * - * @param uri - * A URI object that specifies the absolute URI to - * the queue. - * @param timeout - * The server response timeout interval in milliseconds. If the - * operation does not complete within the specified timeout - * interval, a timeout error is returned by the server. If the - * timeout value is 0, the maximum timeout of 30 seconds is used. - * @param popReceipt - * A String that contains the pop receipt value - * returned from an earlier call to {@link CloudQueueMessage#getPopReceipt} for the message to - * update. - * @param visibilityTimeoutInSeconds - * Specifies the new visibility timeout value in seconds, - * relative to server time, to make the retrieved messages - * invisible until the visibility timeout expires. The value must - * be larger than or equal to 0, and cannot be larger than 7 - * days. The visibility timeout of a message can be set to a - * value later than the expiry time, which will prevent the - * message from being retrieved again whether it is processed or - * not. - * @param opContext - * An {@link OperationContext} object that represents the context - * for the current operation. This object is used to track - * requests to the storage service, and to provide additional - * runtime information about the operation. - * - * @return An HttpURLConnection configured for the specified - * operation. - * - * @throws IOException - * @throws URISyntaxException - * If the URI is not valid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public static HttpURLConnection updateMessage(final URI uri, final int timeout, final String popReceipt, - final int visibilityTimeoutInSeconds, final OperationContext opContext) throws URISyntaxException, - IOException, StorageException { - - final UriQueryBuilder builder = new UriQueryBuilder(); - - builder.add("popreceipt", popReceipt); - - builder.add("visibilitytimeout", Integer.toString(visibilityTimeoutInSeconds)); - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setRequestProperty(Constants.HeaderConstants.STORAGE_VERSION_HEADER, "2011-08-18"); - - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - return request; - } - - /** - * Sets the ACL for the queue. , Sign with length of aclBytes. - * - * @param uri - * The absolute URI to the queue. - * @param timeout - * The server timeout interval. - * @param publicAccess - * The type of public access to allow for the queue. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * */ - public static HttpURLConnection setAcl(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "acl"); - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setDoOutput(true); - request.setRequestMethod("PUT"); - - return request; - } - - /** - * Writes a collection of shared access policies to the specified stream in XML format. - * - * @param sharedAccessPolicies - * A collection of shared access policies - * @param outWriter - * an sink to write the output to. - * @throws XMLStreamException - */ - public static void writeSharedAccessIdentifiersToStream( - final HashMap sharedAccessPolicies, final StringWriter outWriter) - throws XMLStreamException { - Utility.assertNotNull("sharedAccessPolicies", sharedAccessPolicies); - Utility.assertNotNull("outWriter", outWriter); - - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outWriter); - - if (sharedAccessPolicies.keySet().size() > Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS) { - final String errorMessage = String - .format("Too many %d shared access policy identifiers provided. Server does not support setting more than %d on a single queue.", - sharedAccessPolicies.keySet().size(), Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS); - - throw new IllegalArgumentException(errorMessage); - } - - // default is UTF8 - xmlw.writeStartDocument(); - xmlw.writeStartElement(Constants.SIGNED_IDENTIFIERS_ELEMENT); - - for (final Entry entry : sharedAccessPolicies.entrySet()) { - final SharedAccessQueuePolicy policy = entry.getValue(); - xmlw.writeStartElement(Constants.SIGNED_IDENTIFIER_ELEMENT); - - // Set the identifier - xmlw.writeStartElement(Constants.ID); - xmlw.writeCharacters(entry.getKey()); - xmlw.writeEndElement(); - - xmlw.writeStartElement(Constants.ACCESS_POLICY); - - // Set the Start Time - xmlw.writeStartElement(Constants.START); - xmlw.writeCharacters(Utility.getUTCTimeOrEmpty(policy.getSharedAccessStartTime())); - // end Start - xmlw.writeEndElement(); - - // Set the Expiry Time - xmlw.writeStartElement(Constants.EXPIRY); - xmlw.writeCharacters(Utility.getUTCTimeOrEmpty(policy.getSharedAccessExpiryTime())); - // end Expiry - xmlw.writeEndElement(); - - // Set the Permissions - xmlw.writeStartElement(Constants.PERMISSION); - xmlw.writeCharacters(SharedAccessQueuePolicy.permissionsToString(policy.getPermissions())); - // end Permission - xmlw.writeEndElement(); - - // end AccessPolicy - xmlw.writeEndElement(); - // end SignedIdentifier - xmlw.writeEndElement(); - } - - // end SignedIdentifiers - xmlw.writeEndElement(); - // end doc - xmlw.writeEndDocument(); - } - - /** - * Constructs a web request to return the ACL for this queue. Sign with no length specified. - * - * @param uri - * The absolute URI to the container. - * @param timeout - * The server timeout interval. - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - */ - public static HttpURLConnection getAcl(final URI uri, final int timeout, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final UriQueryBuilder builder = new UriQueryBuilder(); - builder.add("comp", "acl"); - - final HttpURLConnection request = BaseRequest.createURLConnection(uri, timeout, builder, opContext); - - request.setRequestMethod("GET"); - - return request; - } - - /** - * Private Default Ctor. - */ - private QueueRequest() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueRequestOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueRequestOptions.java deleted file mode 100644 index 7df4d6a48b49d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueRequestOptions.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import com.microsoft.windowsazure.services.core.storage.RequestOptions; - -/** - * Represents a set of options that may be specified on a queue request. - */ -public final class QueueRequestOptions extends RequestOptions { - /** - * Initializes a new instance of the QueueRequestOptions class. - */ - public QueueRequestOptions() { - // no op - } - - /** - * Initializes a new instance of the QueueRequestOptions class as a copy of - * another QueueRequestOptions instance. - * - * @param other - * The {@link QueueRequestOptions} object to copy the values - * from. - */ - public QueueRequestOptions(final QueueRequestOptions other) { - super(other); - } - - /** - * Populates the default timeout and retry policy from client if they are - * not set. - * - * @param client - * The {@link CloudQueueClient} service client to populate the - * default values from. - */ - protected void applyDefaults(final CloudQueueClient client) { - super.applyBaseDefaults(client); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueResponse.java deleted file mode 100644 index 05f041690d98e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/QueueResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.queue.client; - -import java.net.HttpURLConnection; - -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseResponse; - -/** - * RESERVED FOR INTERNAL USE. A class for parsing various responses from the queue service. - */ -final class QueueResponse extends BaseResponse { - - /** - * Gets the approximate messages count from the headers of a server response to a get metadata request. - * - * @param request - * The HttpURLConnection containing a web request with a response from the server. - * @return The long value of the approximate messages count header field. - */ - public static long getApproximateMessageCount(final HttpURLConnection request) { - return Long.parseLong(request.getHeaderField("x-ms-approximate-messages-count")); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/SharedAccessQueuePermissions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/SharedAccessQueuePermissions.java deleted file mode 100644 index 6ab135fd8c98a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/SharedAccessQueuePermissions.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.util.EnumSet; - -/** - * Specifies the set of possible permissions for a shared access queue policy. - */ -public enum SharedAccessQueuePermissions { - - /** - * No shared access granted. - */ - NONE((byte) 0x0), - - /** - * Permission to peek messages and get queue metadata granted. - */ - READ((byte) 0x1), - - /** - * Permission to add messages granted. - */ - ADD((byte) 0x2), - - /** - * Permissions to update messages granted. - */ - UPDATE((byte) 0x4), - - /** - * Permission to get and delete messages granted. - */ - PROCESSMESSAGES((byte) 0x8); - - /** - * Returns the enum set representing the shared access permissions for the specified byte value. - * - * @param value - * The byte value to convert to the corresponding enum set. - * @return A java.util.EnumSet object that contains the SharedAccessQueuePermissions values - * corresponding to the specified byte value. - */ - protected static EnumSet fromByte(final byte value) { - final EnumSet retSet = EnumSet.noneOf(SharedAccessQueuePermissions.class); - - if (value == READ.value) { - retSet.add(READ); - } - - if (value == PROCESSMESSAGES.value) { - retSet.add(PROCESSMESSAGES); - } - if (value == ADD.value) { - retSet.add(ADD); - } - if (value == UPDATE.value) { - retSet.add(UPDATE); - } - - return retSet; - } - - /** - * Returns the value of this enum. - */ - private byte value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - SharedAccessQueuePermissions(final byte val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/SharedAccessQueuePolicy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/SharedAccessQueuePolicy.java deleted file mode 100644 index 77ffca21efd7b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/SharedAccessQueuePolicy.java +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.util.Date; -import java.util.EnumSet; - -import com.microsoft.windowsazure.services.core.storage.Constants; - -/** - * Represents a shared access policy, which specifies the start time, expiry time, and permissions for a shared access - * signature. - */ -public final class SharedAccessQueuePolicy { - - /** - * Assigns shared access permissions using the specified permissions string. - * - * @param value - * A String that represents the shared access permissions. The string must contain one or - * more of the following values. Note that they must be lower case, and the order that they are specified - * must be in the order of "rwdl". - *

    - *
  • d: Delete access.
  • - *
  • l: List access.
  • - *
  • r: Read access.
  • - *
  • w: Write access.
  • - *
- * - * @return A java.util.EnumSet object that contains {@link SharedAccessQueuePermissions} values that - * represents the set of shared access permissions. - */ - public static EnumSet permissionsFromString(final String value) { - final char[] chars = value.toCharArray(); - final EnumSet retSet = EnumSet.noneOf(SharedAccessQueuePermissions.class); - - for (final char c : chars) { - switch (c) { - case 'r': - retSet.add(SharedAccessQueuePermissions.READ); - break; - case 'a': - retSet.add(SharedAccessQueuePermissions.ADD); - break; - case 'u': - retSet.add(SharedAccessQueuePermissions.UPDATE); - break; - case 'p': - retSet.add(SharedAccessQueuePermissions.PROCESSMESSAGES); - break; - default: - throw new IllegalArgumentException("value"); - } - } - - return retSet; - } - - /** - * Converts the permissions specified for the shared access policy to a string. - * - * @param permissions - * A {@link SharedAccessQueuePermissions} object that represents the shared access permissions. - * - * @return A String that represents the shared access permissions in the "rwdl" format, which is - * described at {@link SharedAccessQueuePolicy#permissionsFromString(String)}. - */ - public static String permissionsToString(final EnumSet permissions) { - if (permissions == null) { - return Constants.EMPTY_STRING; - } - - // The service supports a fixed order => rwdl - final StringBuilder builder = new StringBuilder(); - - if (permissions.contains(SharedAccessQueuePermissions.READ)) { - builder.append("r"); - } - - if (permissions.contains(SharedAccessQueuePermissions.ADD)) { - builder.append("a"); - } - - if (permissions.contains(SharedAccessQueuePermissions.UPDATE)) { - builder.append("u"); - } - - if (permissions.contains(SharedAccessQueuePermissions.PROCESSMESSAGES)) { - builder.append("p"); - } - - return builder.toString(); - } - - /** - * The permissions for a shared access signature associated with this shared access policy. - */ - private EnumSet permissions; - - /** - * The expiry time for a shared access signature associated with this shared access policy. - */ - private Date sharedAccessExpiryTime; - - /** - * The start time for a shared access signature associated with this shared access policy. - */ - private Date sharedAccessStartTime; - - /** - * Creates an instance of the SharedAccessQueuePolicy class. - * */ - public SharedAccessQueuePolicy() { - // Empty Default Ctor - } - - /** - * Gets the permissions for a shared access signature associated with this shared access policy. - * - * @return A java.util.EnumSet object that contains {@link SharedAccessQueuePermissions} values that - * represents the set of shared access permissions. - */ - public EnumSet getPermissions() { - return this.permissions; - } - - /** - * Gets the expiry time for a shared access signature associated with this shared access policy. - * - * @return A Date object that contains the shared access signature expiry time. - */ - public Date getSharedAccessExpiryTime() { - return this.sharedAccessExpiryTime; - } - - /** - * Gets the start time for a shared access signature associated with this shared access policy. - * - * @return A Date object that contains the shared access signature start time. - */ - public Date getSharedAccessStartTime() { - return this.sharedAccessStartTime; - } - - /** - * Sets the permissions for a shared access signature associated with this shared access policy. - * - * @param permissions - * The permissions, represented by a java.util.EnumSet object that contains - * {@link SharedAccessQueuePermissions} values, to set for the shared access signature. - */ - public void setPermissions(final EnumSet permissions) { - this.permissions = permissions; - } - - /** - * Sets the expiry time for a shared access signature associated with this shared access policy. - * - * @param sharedAccessExpiryTime - * The expiry time to set for the shared access signature. - */ - public void setSharedAccessExpiryTime(final Date sharedAccessExpiryTime) { - this.sharedAccessExpiryTime = sharedAccessExpiryTime; - } - - /** - * Sets the start time for a shared access signature associated with this shared access policy. - * - * @param sharedAccessStartTime - * The start time to set for the shared access signature. - */ - public void setSharedAccessStartTime(final Date sharedAccessStartTime) { - this.sharedAccessStartTime = sharedAccessStartTime; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/package.html deleted file mode 100644 index 72c5aac9b9f36..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/client/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the integrated queue service client classes and implementation. - - diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueExceptionProcessor.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueExceptionProcessor.java deleted file mode 100644 index c1ef1e075d19c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueExceptionProcessor.java +++ /dev/null @@ -1,383 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.implementation; - -import java.util.HashMap; - -import javax.inject.Inject; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.microsoft.windowsazure.services.queue.QueueContract; -import com.microsoft.windowsazure.services.queue.models.CreateMessageOptions; -import com.microsoft.windowsazure.services.queue.models.CreateQueueOptions; -import com.microsoft.windowsazure.services.queue.models.GetQueueMetadataResult; -import com.microsoft.windowsazure.services.queue.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.queue.models.ListMessagesOptions; -import com.microsoft.windowsazure.services.queue.models.ListMessagesResult; -import com.microsoft.windowsazure.services.queue.models.ListQueuesOptions; -import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; -import com.microsoft.windowsazure.services.queue.models.PeekMessagesOptions; -import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult; -import com.microsoft.windowsazure.services.queue.models.QueueServiceOptions; -import com.microsoft.windowsazure.services.queue.models.ServiceProperties; -import com.microsoft.windowsazure.services.queue.models.UpdateMessageResult; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.UniformInterfaceException; - -public class QueueExceptionProcessor implements QueueContract { - private static Log log = LogFactory.getLog(QueueExceptionProcessor.class); - private final QueueContract service; - - @Inject - public QueueExceptionProcessor(QueueRestProxy service) { - this.service = service; - } - - public QueueExceptionProcessor(QueueContract service) { - this.service = service; - } - - public QueueContract withFilter(ServiceFilter filter) { - return new QueueExceptionProcessor(service.withFilter(filter)); - } - - private ServiceException processCatch(ServiceException e) { - log.warn(e.getMessage(), e.getCause()); - return ServiceExceptionFactory.process("queue", e); - } - - public GetServicePropertiesResult getServiceProperties() throws ServiceException { - try { - return service.getServiceProperties(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public GetServicePropertiesResult getServiceProperties(QueueServiceOptions options) throws ServiceException { - try { - return service.getServiceProperties(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException { - try { - service.setServiceProperties(serviceProperties); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void setServiceProperties(ServiceProperties serviceProperties, QueueServiceOptions options) - throws ServiceException { - try { - service.setServiceProperties(serviceProperties, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void createQueue(String queue) throws ServiceException { - try { - service.createQueue(queue); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void createQueue(String queue, CreateQueueOptions options) throws ServiceException { - try { - service.createQueue(queue, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void deleteQueue(String queue) throws ServiceException { - try { - service.deleteQueue(queue); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void deleteQueue(String queue, QueueServiceOptions options) throws ServiceException { - try { - service.deleteQueue(queue, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public ListQueuesResult listQueues() throws ServiceException { - try { - return service.listQueues(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public ListQueuesResult listQueues(ListQueuesOptions options) throws ServiceException { - try { - return service.listQueues(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public GetQueueMetadataResult getQueueMetadata(String queue) throws ServiceException { - try { - return service.getQueueMetadata(queue); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public GetQueueMetadataResult getQueueMetadata(String queue, QueueServiceOptions options) throws ServiceException { - try { - return service.getQueueMetadata(queue, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void setQueueMetadata(String queue, HashMap metadata) throws ServiceException { - try { - service.setQueueMetadata(queue, metadata); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void setQueueMetadata(String queue, HashMap metadata, QueueServiceOptions options) - throws ServiceException { - try { - service.setQueueMetadata(queue, metadata, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void createMessage(String queue, String messageText) throws ServiceException { - try { - service.createMessage(queue, messageText); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void createMessage(String queue, String messageText, CreateMessageOptions options) throws ServiceException { - try { - service.createMessage(queue, messageText, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public UpdateMessageResult updateMessage(String queue, String messageId, String popReceipt, String messageText, - int visibilityTimeoutInSeconds) throws ServiceException { - try { - return service.updateMessage(queue, messageId, popReceipt, messageText, visibilityTimeoutInSeconds); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public UpdateMessageResult updateMessage(String queue, String messageId, String popReceipt, String messageText, - int visibilityTimeoutInSeconds, QueueServiceOptions options) throws ServiceException { - try { - return service - .updateMessage(queue, messageId, popReceipt, messageText, visibilityTimeoutInSeconds, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public ListMessagesResult listMessages(String queue) throws ServiceException { - try { - return service.listMessages(queue); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public ListMessagesResult listMessages(String queue, ListMessagesOptions options) throws ServiceException { - try { - return service.listMessages(queue, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public PeekMessagesResult peekMessages(String queue) throws ServiceException { - try { - return service.peekMessages(queue); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public PeekMessagesResult peekMessages(String queue, PeekMessagesOptions options) throws ServiceException { - try { - return service.peekMessages(queue, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void deleteMessage(String queue, String messageId, String popReceipt) throws ServiceException { - try { - service.deleteMessage(queue, messageId, popReceipt); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void deleteMessage(String queue, String messageId, String popReceipt, QueueServiceOptions options) - throws ServiceException { - try { - service.deleteMessage(queue, messageId, popReceipt, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void clearMessages(String queue) throws ServiceException { - try { - service.clearMessages(queue); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - public void clearMessages(String queue, QueueServiceOptions options) throws ServiceException { - try { - service.clearMessages(queue, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueRestProxy.java deleted file mode 100644 index 27d2576bbd9f0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/QueueRestProxy.java +++ /dev/null @@ -1,391 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.implementation; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Named; - -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.pipeline.ClientFilterAdapter; -import com.microsoft.windowsazure.services.core.utils.pipeline.HttpURLConnectionClient; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.microsoft.windowsazure.services.queue.QueueConfiguration; -import com.microsoft.windowsazure.services.queue.QueueContract; -import com.microsoft.windowsazure.services.queue.models.CreateMessageOptions; -import com.microsoft.windowsazure.services.queue.models.CreateQueueOptions; -import com.microsoft.windowsazure.services.queue.models.GetQueueMetadataResult; -import com.microsoft.windowsazure.services.queue.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.queue.models.ListMessagesOptions; -import com.microsoft.windowsazure.services.queue.models.ListMessagesResult; -import com.microsoft.windowsazure.services.queue.models.ListQueuesOptions; -import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; -import com.microsoft.windowsazure.services.queue.models.PeekMessagesOptions; -import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult; -import com.microsoft.windowsazure.services.queue.models.QueueServiceOptions; -import com.microsoft.windowsazure.services.queue.models.ServiceProperties; -import com.microsoft.windowsazure.services.queue.models.UpdateMessageResult; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; - -public class QueueRestProxy implements QueueContract { - //private static Log log = LogFactory.getLog(QueueRestProxy.class); - - private static final String API_VERSION = "2011-08-18"; - private final HttpURLConnectionClient channel; - private final String accountName; - private final String url; - private final RFC1123DateConverter dateMapper; - private final ServiceFilter[] filters; - private final SharedKeyFilter sharedKeyFilter; - - @Inject - public QueueRestProxy(HttpURLConnectionClient channel, @Named(QueueConfiguration.ACCOUNT_NAME) String accountName, - @Named(QueueConfiguration.URI) String url, SharedKeyFilter sharedKeyFilter, UserAgentFilter userAgentFilter) { - - this.channel = channel; - this.accountName = accountName; - this.url = url; - this.sharedKeyFilter = sharedKeyFilter; - this.dateMapper = new RFC1123DateConverter(); - this.filters = new ServiceFilter[0]; - channel.addFilter(sharedKeyFilter); - channel.addFilter(userAgentFilter); - } - - public QueueRestProxy(HttpURLConnectionClient channel, ServiceFilter[] filters, String accountName, String url, - SharedKeyFilter filter, RFC1123DateConverter dateMapper) { - - this.channel = channel; - this.filters = filters; - this.accountName = accountName; - this.url = url; - this.sharedKeyFilter = filter; - this.dateMapper = dateMapper; - } - - @Override - public QueueContract withFilter(ServiceFilter filter) { - ServiceFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1); - newFilters[filters.length] = filter; - return new QueueRestProxy(this.channel, newFilters, this.accountName, this.url, this.sharedKeyFilter, - this.dateMapper); - } - - private void ThrowIfError(ClientResponse r) { - PipelineHelpers.ThrowIfError(r); - } - - private WebResource addOptionalQueryParam(WebResource webResource, String key, Object value) { - return PipelineHelpers.addOptionalQueryParam(webResource, key, value); - } - - private WebResource addOptionalQueryParam(WebResource webResource, String key, int value, int defaultValue) { - return PipelineHelpers.addOptionalQueryParam(webResource, key, value, defaultValue); - } - - private Builder addOptionalMetadataHeader(Builder builder, Map metadata) { - return PipelineHelpers.addOptionalMetadataHeader(builder, metadata); - } - - private HashMap getMetadataFromHeaders(ClientResponse response) { - return PipelineHelpers.getMetadataFromHeaders(response); - } - - private WebResource getResource(QueueServiceOptions options) { - WebResource webResource = channel.resource(url).path("/"); - webResource = addOptionalQueryParam(webResource, "timeout", options.getTimeout()); - for (ServiceFilter filter : filters) { - webResource.addFilter(new ClientFilterAdapter(filter)); - } - - return webResource; - } - - @Override - public GetServicePropertiesResult getServiceProperties() throws ServiceException { - return getServiceProperties(new QueueServiceOptions()); - } - - @Override - public GetServicePropertiesResult getServiceProperties(QueueServiceOptions options) throws ServiceException { - WebResource webResource = getResource(options).path("/").queryParam("resType", "service") - .queryParam("comp", "properties"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - - GetServicePropertiesResult result = new GetServicePropertiesResult(); - result.setValue(builder.get(ServiceProperties.class)); - return result; - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException { - setServiceProperties(serviceProperties, new QueueServiceOptions()); - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties, QueueServiceOptions options) - throws ServiceException { - WebResource webResource = getResource(options).path("/").queryParam("resType", "service") - .queryParam("comp", "properties"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - - builder.put(serviceProperties); - } - - @Override - public void createQueue(String queue) throws ServiceException { - createQueue(queue, new CreateQueueOptions()); - - } - - @Override - public void createQueue(String queue, CreateQueueOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalMetadataHeader(builder, options.getMetadata()); - - builder.put(); - } - - @Override - public void deleteQueue(String queue) throws ServiceException { - deleteQueue(queue, new QueueServiceOptions()); - } - - @Override - public void deleteQueue(String queue, QueueServiceOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - - builder.delete(); - } - - @Override - public ListQueuesResult listQueues() throws ServiceException { - return listQueues(new ListQueuesOptions()); - } - - @Override - public ListQueuesResult listQueues(ListQueuesOptions options) throws ServiceException { - WebResource webResource = getResource(options).path("/").queryParam("comp", "list"); - webResource = addOptionalQueryParam(webResource, "prefix", options.getPrefix()); - webResource = addOptionalQueryParam(webResource, "marker", options.getMarker()); - webResource = addOptionalQueryParam(webResource, "maxresults", options.getMaxResults(), 0); - if (options.isIncludeMetadata()) { - webResource = webResource.queryParam("include", "metadata"); - } - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - return builder.get(ListQueuesResult.class); - } - - @Override - public GetQueueMetadataResult getQueueMetadata(String queue) throws ServiceException { - return getQueueMetadata(queue, new QueueServiceOptions()); - } - - @Override - public GetQueueMetadataResult getQueueMetadata(String queue, QueueServiceOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue).queryParam("comp", "metadata"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - GetQueueMetadataResult result = new GetQueueMetadataResult(); - result.setApproximateMessageCount(Integer.parseInt(response.getHeaders().getFirst( - "x-ms-approximate-messages-count"))); - result.setMetadata(getMetadataFromHeaders(response)); - - return result; - } - - @Override - public void setQueueMetadata(String queue, HashMap metadata) throws ServiceException { - setQueueMetadata(queue, metadata, new QueueServiceOptions()); - } - - @Override - public void setQueueMetadata(String queue, HashMap metadata, QueueServiceOptions options) - throws ServiceException { - if (queue == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue).queryParam("comp", "metadata"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - builder = addOptionalMetadataHeader(builder, metadata); - - builder.put(); - } - - @Override - public void createMessage(String queue, String messageText) throws ServiceException { - createMessage(queue, messageText, new CreateMessageOptions()); - } - - @Override - public void createMessage(String queue, String messageText, CreateMessageOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException("queue"); - if (messageText == null) { - throw new NullPointerException("messageText"); - } - - WebResource webResource = getResource(options).path(queue).path("messages"); - webResource = addOptionalQueryParam(webResource, "visibilitytimeout", options.getVisibilityTimeoutInSeconds()); - webResource = addOptionalQueryParam(webResource, "messagettl", options.getTimeToLiveInSeconds()); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - QueueMessage queueMessage = new QueueMessage(); - queueMessage.setMessageText(messageText); - - builder.post(queueMessage); - } - - @Override - public UpdateMessageResult updateMessage(String queue, String messageId, String popReceipt, String messageText, - int visibilityTimeoutInSeconds) throws ServiceException { - return updateMessage(queue, messageId, popReceipt, messageText, visibilityTimeoutInSeconds, - new QueueServiceOptions()); - } - - @Override - public UpdateMessageResult updateMessage(String queue, String messageId, String popReceipt, String messageText, - int visibilityTimeoutInSeconds, QueueServiceOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException("queue"); - if (messageId == null) - throw new NullPointerException("messageId"); - if (messageText == null) - throw new NullPointerException("messageText"); - - WebResource webResource = getResource(options).path(queue).path("messages").path(messageId); - webResource = addOptionalQueryParam(webResource, "popreceipt", popReceipt); - webResource = addOptionalQueryParam(webResource, "visibilitytimeout", visibilityTimeoutInSeconds); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - QueueMessage queueMessage = new QueueMessage(); - queueMessage.setMessageText(messageText); - - ClientResponse response = builder.put(ClientResponse.class, queueMessage); - ThrowIfError(response); - - UpdateMessageResult result = new UpdateMessageResult(); - result.setPopReceipt(response.getHeaders().getFirst("x-ms-popreceipt")); - result.setTimeNextVisible(dateMapper.parse(response.getHeaders().getFirst("x-ms-time-next-visible"))); - return result; - } - - @Override - public ListMessagesResult listMessages(String queue) throws ServiceException { - return listMessages(queue, new ListMessagesOptions()); - } - - @Override - public ListMessagesResult listMessages(String queue, ListMessagesOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue).path("messages"); - webResource = addOptionalQueryParam(webResource, "visibilitytimeout", options.getVisibilityTimeoutInSeconds()); - webResource = addOptionalQueryParam(webResource, "numofmessages", options.getNumberOfMessages()); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - return builder.get(ListMessagesResult.class); - } - - @Override - public PeekMessagesResult peekMessages(String queue) throws ServiceException { - return peekMessages(queue, new PeekMessagesOptions()); - } - - @Override - public PeekMessagesResult peekMessages(String queue, PeekMessagesOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue).path("messages").queryParam("peekonly", "true"); - webResource = addOptionalQueryParam(webResource, "numofmessages", options.getNumberOfMessages()); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - return builder.get(PeekMessagesResult.class); - } - - @Override - public void deleteMessage(String queue, String messageId, String popReceipt) throws ServiceException { - deleteMessage(queue, messageId, popReceipt, new QueueServiceOptions()); - } - - @Override - public void deleteMessage(String queue, String messageId, String popReceipt, QueueServiceOptions options) - throws ServiceException { - if (queue == null) - throw new NullPointerException(); - if (messageId == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue).path("messages").path(messageId); - webResource = addOptionalQueryParam(webResource, "popreceipt", popReceipt); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - builder.delete(); - } - - @Override - public void clearMessages(String queue) throws ServiceException { - clearMessages(queue, new QueueServiceOptions()); - } - - @Override - public void clearMessages(String queue, QueueServiceOptions options) throws ServiceException { - if (queue == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(queue).path("messages"); - - Builder builder = webResource.header("x-ms-version", API_VERSION); - - builder.delete(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyFilter.java deleted file mode 100644 index da9a6d15658a2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyFilter.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.implementation; - -import javax.inject.Named; - -import com.microsoft.windowsazure.services.queue.QueueConfiguration; - -public class SharedKeyFilter extends com.microsoft.windowsazure.services.blob.implementation.SharedKeyFilter { - public SharedKeyFilter(@Named(QueueConfiguration.ACCOUNT_NAME) String accountName, - @Named(QueueConfiguration.ACCOUNT_KEY) String accountKey) { - super(accountName, accountKey); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyLiteFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyLiteFilter.java deleted file mode 100644 index bd1cecd8aec2c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/implementation/SharedKeyLiteFilter.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.implementation; - -import javax.inject.Named; - -import com.microsoft.windowsazure.services.queue.QueueConfiguration; - -public class SharedKeyLiteFilter extends com.microsoft.windowsazure.services.blob.implementation.SharedKeyLiteFilter { - public SharedKeyLiteFilter(@Named(QueueConfiguration.ACCOUNT_NAME) String accountName, - @Named(QueueConfiguration.ACCOUNT_KEY) String accountKey) { - super(accountName, accountKey); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateMessageOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateMessageOptions.java deleted file mode 100644 index 6dd5941aed8b1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateMessageOptions.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * Represents the options that may be set on the Queue service for - * {@link QueueContract#createMessage(String, String, CreateMessageOptions) createMessage} requests. These options - * include a server response timeout for the request, the visibility timeout to set on the created message, and the - * time-to-live value to set on the message. - */ -public class CreateMessageOptions extends QueueServiceOptions { - private Integer visibilityTimeoutInSeconds; - private Integer timeToLiveInSeconds; - - /** - * Sets the server request timeout value associated with this {@link CreateMessageOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CreateMessageOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CreateMessageOptions} instance. - */ - @Override - public CreateMessageOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the message visibility timeout in seconds value in this {@link CreateMessageOptions} instance. - * to set on messages when making a {@link QueueContract#createMessage(String, String, CreateMessageOptions) - * createMessage} request. - * - * @return - * The message visibility timeout in seconds. - */ - public Integer getVisibilityTimeoutInSeconds() { - return visibilityTimeoutInSeconds; - } - - /** - * Sets the message visibility timeout in seconds value to set on messages when making a - * {@link QueueContract#createMessage(String, String, CreateMessageOptions) createMessage} request. This allows - * messages to be loaded into the queue but not become visible until the visibility timeout has passed. - * Valid visibility timeout values range from 0 to 604800 seconds (0 to 7 days), and must be less than the - * time-to-live value. - *

- * The visibilityTimeoutInSeconds value only affects calls made on methods where this - * {@link CreateMessageOptions} instance is passed as a parameter. - * - * @param visibilityTimeoutInSeconds - * The length of time during which the message will be invisible, starting when it is added to the queue, - * or 0 to make the message visible immediately. This value must be greater than or equal to zero and - * less than or equal to the time-to-live value. - * @return - * A reference to this {@link CreateMessageOptions} instance. - */ - public CreateMessageOptions setVisibilityTimeoutInSeconds(Integer visibilityTimeoutInSeconds) { - this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds; - return this; - } - - /** - * Gets the message time-to-live in seconds value associated with this {@link CreateMessageOptions} instance. - * - * @return - * The message time-to-live value in seconds. - */ - public Integer getTimeToLiveInSeconds() { - return timeToLiveInSeconds; - } - - /** - * Sets the message time-to-live timeout value to set on messages when making a - * {@link QueueContract#createMessage(String, String, CreateMessageOptions) createMessage} request. This is the - * maximum duration in seconds for the message to remain in the queue after it is created. - * Valid timeToLiveInSeconds values range from 0 to 604800 seconds (0 to 7 days), with the default value - * set to seven days. - *

- * The timeToLiveInSeconds value only affects calls made on methods where this {@link CreateMessageOptions} - * instance is passed as a parameter. - * - * @param timeToLiveInSeconds - * The maximum time to allow the message to be in the queue, in seconds. - * @return - * A reference to this {@link CreateMessageOptions} instance. - */ - public CreateMessageOptions setTimeToLiveInSeconds(Integer timeToLiveInSeconds) { - this.timeToLiveInSeconds = timeToLiveInSeconds; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateQueueOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateQueueOptions.java deleted file mode 100644 index d9ea78c12d6e9..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/CreateQueueOptions.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * Represents the options that may be set on a queue when created in the storage service with a - * {@link QueueContract#createQueue(String, CreateQueueOptions) createQueue} request. These options include a server - * response timeout for the request and the metadata to associate with the created queue. - */ -public class CreateQueueOptions extends QueueServiceOptions { - private HashMap metadata = new HashMap(); - - /** - * Sets the server request timeout value associated with this {@link CreateQueueOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link CreateQueueOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link CreateQueueOptions} instance. - */ - @Override - public CreateQueueOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the metadata collection of key-value {@link String} pairs to set on a queue when the queue is created. - * - * @return - * A {@link java.util.HashMap} of key-value {@link String} pairs containing the metadata to set on the - * queue. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Sets the metadata collection of key-value {@link String} pairs to set on a queue when the queue is created. Queue - * metadata is a user-defined collection of key-value pairs that is opaque to the server. - *

- * The metadata value is only added to a newly created queue where this {@link CreateQueueOptions} instance - * is passed as a parameter. - * - * @param metadata - * The {@link java.util.HashMap} of key-value {@link String} pairs containing the metadata to set on the - * queue. - * @return - * A reference to this {@link CreateQueueOptions} instance. - */ - public CreateQueueOptions setMetadata(HashMap metadata) { - this.metadata = metadata; - return this; - } - - /** - * Adds a key-value pair of {@link String} to the metadata collection to set on a queue when the queue is created. - * Queue metadata is a user-defined collection of key-value pairs that is opaque to the server. If the key already - * exists in the metadata collection, the value parameter will overwrite the existing value paired with that key - * without notification. - *

- * The updated metadata is only added to a newly created queue where this {@link CreateQueueOptions} instance is - * passed as a parameter. - * - * @param key - * A {@link String} containing the key part of the key-value pair to add to the metadata. - * @param value - * A {@link String} containing the value part of the key-value pair to add to the metadata. - * @return - * A reference to this {@link CreateQueueOptions} instance. - */ - public CreateQueueOptions addMetadata(String key, String value) { - this.metadata.put(key, value); - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/GetQueueMetadataResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/GetQueueMetadataResult.java deleted file mode 100644 index a6d69b660306e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/GetQueueMetadataResult.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * A wrapper class for the result returned from a Queue Service REST API operation to get queue metadata. This is - * returned by calls to implementations of {@link QueueContract#getQueueMetadata(String)} and - * {@link QueueContract#getQueueMetadata(String, QueueServiceOptions)}. - *

- * See the Get Queue Metadata - * documentation on MSDN for details of the underlying Queue Service REST API operation. - */ -public class GetQueueMetadataResult { - private long approximateMessageCount; - private HashMap metadata; - - /** - * Gets the queue's approximate message count, as reported by the server. - * - * @return - * The queue's approximate message count. - */ - public long getApproximateMessageCount() { - return approximateMessageCount; - } - - /** - * Reserved for internal use. This method is invoked by the API as part of the response generation from the - * Queue Service REST API operation to set the value for the approximate message count returned by the server. - * - * @param approximateMessageCount - * The queue's approximate message count to set. - */ - public void setApproximateMessageCount(long approximateMessageCount) { - this.approximateMessageCount = approximateMessageCount; - } - - /** - * Gets the metadata collection of key-value {@link String} pairs currently set on a queue. Queue metadata is a - * user-defined collection of key-value pairs that is opaque to the server. - * - * @return - * A {@link java.util.HashMap} of key-value {@link String} pairs containing the metadata set on the - * queue. - */ - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. This method is invoked by the API as part of the response generation from the - * Queue Service REST API operation to set the value from the queue metadata returned by the server. - * - * @param metadata - * A {@link java.util.HashMap} of key-value {@link String} pairs containing the metadata set on the - * queue. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/GetServicePropertiesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/GetServicePropertiesResult.java deleted file mode 100644 index 0ee5567e9a71f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/GetServicePropertiesResult.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * A wrapper class for the service properties returned in response to Queue Service REST API operations. This is - * returned by calls to implementations of {@link QueueContract#getServiceProperties()} and - * {@link QueueContract#getServiceProperties(QueueServiceOptions)}. - *

- * See the Get Queue Service Properties - * documentation on MSDN for details of the underlying Queue Service REST API operation. - */ -public class GetServicePropertiesResult { - private ServiceProperties value; - - /** - * Gets a {@link ServiceProperties} instance containing the service property values associated with the storage - * account. - *

- * Modifying the values in the {@link ServiceProperties} instance returned does not affect the values associated - * with the storage account. To change the values in the storage account, call the - * {@link QueueContract#setServiceProperties} method and pass the modified {@link ServiceProperties} instance as a - * parameter. - * - * @return - * A {@link ServiceProperties} instance containing the property values associated with the storage account. - */ - public ServiceProperties getValue() { - return value; - } - - /** - * Reserved for internal use. Sets the value of the {@link ServiceProperties} instance associated with a - * storage service call result. This method is invoked by the API to store service properties returned by - * a call to a REST operation and is not intended for public use. - * - * @param value - * A {@link ServiceProperties} instance containing the property values associated with the storage - * account. - */ - public void setValue(ServiceProperties value) { - this.value = value; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesOptions.java deleted file mode 100644 index ffb13754185b9..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesOptions.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * Represents the options that may be set on a {@link QueueContract#listMessages(String, ListMessagesOptions) - * listMessages} request. These options include a server response timeout for the request, the number of messages to - * retrieve from the queue, and the visibility timeout to set on the retrieved messages. - */ -public class ListMessagesOptions extends QueueServiceOptions { - private Integer numberOfMessages; - private Integer visibilityTimeoutInSeconds; - - /** - * Sets the server request timeout value associated with this {@link ListMessagesOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link ListMessagesOptions} instance is - * passed as a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link ListMessagesOptions} instance. - */ - @Override - public ListMessagesOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the number of messages to request from the queue with this {@link ListMessagesOptions} instance. - * - * @return - * The number of messages requested. - */ - public Integer getNumberOfMessages() { - return numberOfMessages; - } - - /** - * Sets the number of messages to request from the queue with this {@link ListMessagesOptions} instance. - *

- * The numberOfMessages value is only used for requests where this {@link ListMessagesOptions} instance is - * passed as a parameter. - * - * @param numberOfMessages - * The number of messages to request. The valid range of values is 0 to 32. - * @return - * A reference to this {@link ListMessagesOptions} instance. - */ - public ListMessagesOptions setNumberOfMessages(Integer numberOfMessages) { - this.numberOfMessages = numberOfMessages; - return this; - } - - /** - * Gets the visibility timeout to set on the messages requested from the queue with this {@link ListMessagesOptions} - * instance. - * - * @return - * The visibility timeout to set on the messages requested from the queue. - */ - public Integer getVisibilityTimeoutInSeconds() { - return visibilityTimeoutInSeconds; - } - - /** - * Sets the visibility timeout value to set on the messages requested from the queue with this - * {@link ListMessagesOptions} instance. - *

- * The visibilityTimeoutInSeconds value is only used for requests where this {@link ListMessagesOptions} - * instance is passed as a parameter. - * - * @param visibilityTimeoutInSeconds - * The visibility timeout to set on the messages requested from the queue. The valid range of values is 0 - * to 604800 seconds. - * @return - * A reference to this {@link ListMessagesOptions} instance. - */ - public ListMessagesOptions setVisibilityTimeoutInSeconds(Integer visibilityTimeoutInSeconds) { - this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesResult.java deleted file mode 100644 index 4c83ca513ee4b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListMessagesResult.java +++ /dev/null @@ -1,245 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.core.RFC1123DateAdapter; -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * A wrapper class for the result returned from a Queue Service REST API operation to get a list of messages. This is - * returned by calls to implementations of {@link QueueContract#listMessages(String)} and - * {@link QueueContract#listMessages(String, ListMessagesOptions)}. - *

- * See the Get Messages documentation - * on MSDN for details of the underlying Queue Service REST API operation. - */ -@XmlRootElement(name = "QueueMessagesList") -public class ListMessagesResult { - private List queueMessages = new ArrayList(); - - /** - * Gets the list of queue messages returned by a {@link QueueContract}.listMessages request. The queue - * messages returned have their visibility timeout set to allow for processing by the client. The client must - * delete the messages once processing is complete, or they will become visible in the queue when the visibility - * timeout period is over. - * - * @return - * A {@link List} of {@link QueueMessage} instances representing the messages returned by the request. - */ - @XmlElement(name = "QueueMessage") - public List getQueueMessages() { - return queueMessages; - } - - /** - * Reserved for internal use. Sets the list of queue messages returned by a {@link QueueContract} - * .listMessages request. This method is invoked by the API as part of the response generation from the - * Queue Service REST API operation to set the value from the queue message list returned by the server. - * - * @param queueMessages - * A {@link List} of {@link QueueMessage} instances representing the messages returned by the request. - */ - public void setQueueMessages(List queueMessages) { - this.queueMessages = queueMessages; - } - - /** - * Represents a message in the queue returned by the server. A {@link QueueMessage} instance contains a copy of the - * queue message data in the storage service as of the time the message was requested. - */ - public static class QueueMessage { - private String messageId; - private Date insertionDate; - private Date expirationDate; - private String popReceipt; - private Date timeNextVisible; - private int dequeueCount; - private String messageText; - - /** - * Gets the message ID for the message in the queue. The message ID is a value that is opaque to the client - * that must be used along with the pop receipt to validate an update message or delete message operation. - * - * @return - * A {@link String} containing the message ID. - */ - @XmlElement(name = "MessageId") - public String getMessageId() { - return messageId; - } - - /** - * Reserved for internal use. Sets the value of the message ID for the queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the message ID returned by the server. - * - * @param messageId - * A {@link String} containing the message ID. - */ - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - /** - * Gets the {@link Date} when this message was added to the queue. - * - * @return - * The {@link Date} when this message was added to the queue. - */ - @XmlElement(name = "InsertionTime") - @XmlJavaTypeAdapter(RFC1123DateAdapter.class) - public Date getInsertionDate() { - return insertionDate; - } - - /** - * Reserved for internal use. Sets the value of the insertion time for the queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the insertion time returned by the server. - * - * @param insertionDate - * The {@link Date} when this message was added to the queue. - */ - public void setInsertionDate(Date insertionDate) { - this.insertionDate = insertionDate; - } - - /** - * Gets the {@link Date} when this message will expire and be automatically removed from the queue. - * - * @return - * The {@link Date} when this message will expire. - */ - @XmlElement(name = "ExpirationTime") - @XmlJavaTypeAdapter(RFC1123DateAdapter.class) - public Date getExpirationDate() { - return expirationDate; - } - - /** - * Reserved for internal use. Sets the value of the expiration time for the queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the expiration time returned by the server. - * - * @param expirationDate - * The {@link Date} when this message will expire. - */ - public void setExpirationDate(Date expirationDate) { - this.expirationDate = expirationDate; - } - - /** - * Gets the pop receipt value for the queue message. The pop receipt is a value that is opaque to the client - * that must be used along with the message ID to validate an update message or delete message operation. - * - * @return - * A {@link String} containing the pop receipt value for the queue message. - */ - @XmlElement(name = "PopReceipt") - public String getPopReceipt() { - return popReceipt; - } - - /** - * Reserved for internal use. Sets the value of the pop receipt for the queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the pop receipt returned by the server. - * - * @param popReceipt - * A {@link String} containing the pop receipt value for the queue message. - */ - public void setPopReceipt(String popReceipt) { - this.popReceipt = popReceipt; - } - - /** - * Gets the {@link Date} when this message will become visible in the queue. - * - * @return - * The {@link Date} when this message will become visible in the queue. - */ - @XmlElement(name = "TimeNextVisible") - @XmlJavaTypeAdapter(RFC1123DateAdapter.class) - public Date getTimeNextVisible() { - return timeNextVisible; - } - - /** - * Reserved for internal use. Sets the value of the time the message will become visible. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the time next visible returned by the server. - * - * @param timeNextVisible - * The {@link Date} when this message will become visible in the queue. - */ - public void setTimeNextVisible(Date timeNextVisible) { - this.timeNextVisible = timeNextVisible; - } - - /** - * Gets the number of times this queue message has been retrieved with a list messages operation. - * - * @return - * The number of times this queue message has been retrieved. - */ - @XmlElement(name = "DequeueCount") - public int getDequeueCount() { - return dequeueCount; - } - - /** - * Reserved for internal use. Sets the value of the dequeue count of the message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the queue message dequeue count returned by the server. - * - * @param dequeueCount - * The number of times this queue message has been retrieved. - */ - public void setDequeueCount(int dequeueCount) { - this.dequeueCount = dequeueCount; - } - - /** - * Gets the {@link String} containing the content of the queue message. - * - * @return - * A {@link String} containing the content of the queue message. - */ - @XmlElement(name = "MessageText") - public String getMessageText() { - return messageText; - } - - /** - * Reserved for internal use. Sets the {@link String} containing the content of the message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the queue message content returned by the server. - * - * @param messageText - * A {@link String} containing the content of the message. - */ - public void setMessageText(String messageText) { - this.messageText = messageText; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesOptions.java deleted file mode 100644 index d3a6b30b47661..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesOptions.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * Represents the options that may be set on the Queue service for {@link QueueContract#listQueues(ListQueuesOptions)} - * requests. These options include a server response timeout for the request, a prefix to match queue names to return, a - * marker to specify where to resume a list queues query, the maximum number of queues to return in a single response, - * and whether to include queue metadata with the response. - */ -public class ListQueuesOptions extends QueueServiceOptions { - private String prefix; - private String marker; - private int maxResults; - private boolean includeMetadata; - - /** - * Sets the server request timeout value associated with this {@link ListQueuesOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link ListQueuesOptions} instance is passed as a - * parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link ListQueuesOptions} instance. - */ - @Override - public ListQueuesOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the prefix {@link String} used to match queue names to return in a - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. - * - * @return - * The prefix {@link String} used to match queue names to return in a - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. - */ - public String getPrefix() { - return prefix; - } - - /** - * Sets the prefix {@link String} to use to match queue names to return in a - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. - *

- * The prefix value only affects calls made on methods where this {@link ListQueuesOptions} instance is passed as a - * parameter. - * - * @param prefix - * The prefix {@link String} to use to match queue names to return in a - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. - * @return - * A reference to this {@link ListQueuesOptions} instance. - */ - public ListQueuesOptions setPrefix(String prefix) { - this.prefix = prefix; - return this; - } - - /** - * Gets a {@link String} value that identifies the beginning of the list of queues to be returned with a - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. - *

- * The {@link QueueContract#listQueues(ListQueuesOptions) listQueues} method returns a NextMarker - * element within the response if the list returned was not complete, which can be accessed with the - * {@link ListQueuesResult#getNextMarker()} method. This opaque value may then be set on a {@link ListQueuesOptions} - * instance with a call to {@link ListQueuesOptions#setMarker(String) setMarker} to be used in a subsequent - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} call to request the next portion of the list of - * queues. - * - * @return - * The marker value that identifies the beginning of the list of queues to be returned. - */ - public String getMarker() { - return marker; - } - - /** - * Sets a {@link String} marker value that identifies the beginning of the list of queues to be returned with a - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. - *

- * The {@link QueueContract#listQueues(ListQueuesOptions) listQueues} method returns a NextMarker - * element within the response if the list returned was not complete, which can be accessed with the - * {@link ListQueuesResult#getNextMarker()} method. This opaque value may then be set on a {@link ListQueuesOptions} - * instance with a call to {@link ListQueuesOptions#setMarker(String) setMarker} to be used in a subsequent - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} call to request the next portion of the list of - * queues. - * - * @param marker - * The {@link String} marker value to set. - * @return - * A reference to this {@link ListQueuesOptions} instance. - */ - public ListQueuesOptions setMarker(String marker) { - this.marker = marker; - return this; - } - - /** - * Gets the maximum number of queues to return with a {@link QueueContract#listQueues(ListQueuesOptions) listQueues} - * request. If the value is not specified, the server will return up to 5,000 items. - * - * @return - * The maximum number of queues to return. - */ - public int getMaxResults() { - return maxResults; - } - - /** - * Sets the maximum number of queues to return with a {@link QueueContract#listQueues(ListQueuesOptions) listQueues} - * request. If the value is not specified, by default the server will return up to 5,000 items. - *

- * The maxResults value only affects calls made on methods where this {@link ListQueuesOptions} instance is passed - * as a parameter. - * - * @param maxResults - * The maximum number of queues to return. - * @return - * A reference to this {@link ListQueuesOptions} instance. - */ - public ListQueuesOptions setMaxResults(int maxResults) { - this.maxResults = maxResults; - return this; - } - - /** - * Gets a flag indicating whether to return metadata with a {@link QueueContract#listQueues(ListQueuesOptions) - * listQueues} request. - * - * @return - * true to return metadata. - */ - public boolean isIncludeMetadata() { - return includeMetadata; - } - - /** - * Sets a flag indicating whether to return metadata with a {@link QueueContract#listQueues(ListQueuesOptions) - * listQueues} request. - * - * @param includeMetadata - * true to return metadata. - * @return - * A reference to this {@link ListQueuesOptions} instance. - */ - public ListQueuesOptions setIncludeMetadata(boolean includeMetadata) { - this.includeMetadata = includeMetadata; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesResult.java deleted file mode 100644 index 22b92b40444b2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ListQueuesResult.java +++ /dev/null @@ -1,293 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.blob.implementation.MetadataAdapter; -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * A wrapper class for the results returned in response to Queue service REST API operations to list queues. This - * is returned by calls to implementations of {@link QueueContract#listQueues()} and - * {@link QueueContract#listQueues(ListQueuesOptions)}. - *

- * See the List Queues documentation on - * MSDN for details of the underlying Queue service REST API operation. - */ -@XmlRootElement(name = "EnumerationResults") -public class ListQueuesResult { - private List queues = new ArrayList(); - private String accountName; - private String prefix; - private String marker; - private String nextMarker; - private int maxResults; - - /** - * Gets the list of queues returned by a {@link QueueContract}.listQueues request. - * - * @return - * A {@link List} of {@link Queue} instances representing the queues returned by the request. - */ - @XmlElementWrapper(name = "Queues") - @XmlElement(name = "Queue") - public List getQueues() { - return queues; - } - - /** - * Reserved for internal use. Sets the list of queues returned by a {@link QueueContract}.listQueues - * request. This method is invoked by the API as part of the response generation from the Queue service REST API - * operation to set the value from the queue list returned by the server. - * - * @param value - * A {@link List} of {@link Queue} instances representing the queues returned by the request. - */ - public void setQueues(List value) { - this.queues = value; - } - - /** - * Gets the base URI for Queue service REST API operations on the storage account. The URI consists of the protocol - * along with the DNS prefix name for the account followed by ".queue.core.windows.net". For example, if the DNS - * prefix name for the storage account is "myaccount" then the value returned by this method is - * "http://myaccount.queue.core.windows.net". - * - * @return - * A {@link String} containing the base URI for Queue service REST API operations on the storage account. - */ - @XmlAttribute(name = "AccountName") - public String getAccountName() { - return accountName; - } - - /** - * Reserved for internal use. Sets the base URI for Queue service REST API operations on the storage account. This - * method is invoked by the API as part of the response generation from the Queue service REST API operation to set - * the value from the response returned by the server. - * - * @param accountName - * A {@link String} containing the base URI for Queue service REST API operations on the storage account. - */ - public void setAccountName(String accountName) { - this.accountName = accountName; - } - - /** - * Gets the prefix {@link String} used to qualify the results returned by the - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. Only queues with names that start with - * the prefix are returned by the request. By default, the prefix is empty and all queues are returned. - * - * @return - * The {@link String} prefix used to qualify the names of the queues returned. - */ - @XmlElement(name = "Prefix") - public String getPrefix() { - return prefix; - } - - /** - * Reserved for internal use. Sets the prefix {@link String} used to qualify the results returned by the Queue - * service REST API list queues operation invoked with a call to {@link QueueContract#listQueues(ListQueuesOptions) - * listQueues}. This method is invoked by the API as part of the response generation from the Queue service REST API - * operation to set the value from the Prefix element returned by the server. - * - * @param prefix - * The {@link String} prefix used to qualify the names of the queues returned. - */ - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - /** - * Gets the marker value for the beginning of the queue results returned by the - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. The marker is used by the server to - * specify the place to resume a query for queues. The marker value is a {@link String} opaque to the client. A - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request response may include a - * NextMarker value if there are more queue results than can be returned in a single response. Call - * the {@link ListQueuesResult#getNextMarker() getNextMarker} method to get this value. The - * client can request the next set of queue results by setting the marker to this value in the - * {@link ListQueuesOptions} parameter. By default, this value is empty and the server responds with the first - * queues that match the request. - * - * @return - * A {@link String} containing the marker value used for the response. - */ - @XmlElement(name = "Marker") - public String getMarker() { - return marker; - } - - /** - * Reserved for internal use. Sets the marker value specifying the beginning of the results returned by the Queue - * service REST API list queues operation invoked with a call to {@link QueueContract#listQueues(ListQueuesOptions) - * listQueues}. This method is invoked by the API as part of the response generation from the Queue service REST API - * operation to set the value from the Marker element returned by the server. - * - * @param marker - * A {@link String} containing the marker value used for the response. - */ - public void setMarker(String marker) { - this.marker = marker; - } - - /** - * Gets the next marker value needed to retrieve additional queues. If more queues are available that satisfy a - * listQueues request than can be returned in the response, the server generates a marker value to specify - * the beginning of the queues to return in a subsequent request. The client can request the next set of queue - * results by setting the marker to this value in the {@link ListQueuesOptions} parameter. This value is - * empty if there are no more queues that satisfy the request than are included in the response. - * - * @return - * A {@link String} containing the marker value to use to resume the list queues request. - */ - @XmlElement(name = "NextMarker") - public String getNextMarker() { - return nextMarker; - } - - /** - * Reserved for internal use. Sets the next marker value specifying the place to resume a list queues query if more - * results are available than have been returned by the Queue service REST API list queues operation response. This - * method is invoked by the API as part of the response generation from the Queue service REST API operation to set - * the value from the NextMarker element returned by the server. - * - * @param nextMarker - * A {@link String} containing the marker value to use to resume the list queues request. - */ - public void setNextMarker(String nextMarker) { - this.nextMarker = nextMarker; - } - - /** - * Gets the value specified for the number of queue results to return for the - * {@link QueueContract#listQueues(ListQueuesOptions) listQueues} request. The server will not return more than this - * number of queues in the response. If the value is not specified, the server will return up to 5,000 items. - *

- * If there are more queues available that match the request than the number returned, the response will include a - * next marker value to specify the beginning of the queues to return in a subsequent request. Call the - * {@link ListQueuesResult#getNextMarker() getNextMarker} method to get this value. The client can request the next - * set of queue results by setting the marker to this value in the {@link ListQueuesOptions} parameter. - * - * @return - * The maximum number of results to return specified by the request. - */ - @XmlElement(name = "MaxResults") - public int getMaxResults() { - return maxResults; - } - - /** - * Reserved for internal use. Sets the value returned by the Queue service REST API list queues operation response - * for the maximum number of queues to return. This method is invoked by the API as part of the response generation - * from the Queue service REST API operation to set the value from the MaxResults element returned - * by the server. - * - * @param maxResults - * The maximum number of results to return specified by the request. - */ - public void setMaxResults(int maxResults) { - this.maxResults = maxResults; - } - - /** - * Represents a queue in the storage account returned by the server. A {@link Queue} instance contains a copy of the - * queue name, URI, and metadata in the storage service as of the time the queue was requested. - */ - public static class Queue { - private String name; - private String url; - private HashMap metadata = new HashMap(); - - /** - * Gets the name of this queue. - * - * @return - * A {@link String} containing the name of this queue. - */ - @XmlElement(name = "Name") - public String getName() { - return name; - } - - /** - * Reserved for internal use. Sets the name of this queue. This method is invoked by the API as part of the - * response generation from the Queue service REST API operation to set the value from the - * Name element returned by the server. - * - * @param name - * A {@link String} containing the name of this queue. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Gets the URI for Queue service REST API operations on this queue. - * - * @return - * A {@link String} containing the URI for Queue service REST API operations on this queue. - */ - @XmlElement(name = "Url") - public String getUrl() { - return url; - } - - /** - * Reserved for internal use. Sets the URI of this queue. This method is invoked by the API as part of the - * response generation from the Queue service REST API operation to set the value from the - * Url element returned by the server. - * - * @param url - * A {@link String} containing the URI for Queue service REST API operations on this queue. - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * Gets the metadata collection of key-value {@link String} pairs associated with this queue. - * - * @return - * A {@link java.util.HashMap} of key-value {@link String} pairs containing the queue metadata. - */ - @XmlElement(name = "Metadata") - @XmlJavaTypeAdapter(MetadataAdapter.class) - public HashMap getMetadata() { - return metadata; - } - - /** - * Reserved for internal use. Sets the metadata of this queue. This method is invoked by the API as part of the - * response generation from the Queue service REST API operation to set the value from the - * Metadata element returned by the server. - * - * @param metadata - * A {@link java.util.HashMap} of key-value {@link String} pairs containing the queue metadata. - */ - public void setMetadata(HashMap metadata) { - this.metadata = metadata; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesOptions.java deleted file mode 100644 index 50fbe5ab288e3..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesOptions.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * Represents the options that may be set on a {@link QueueContract#peekMessages(String, PeekMessagesOptions) - * peekMessages} request. These options include a server response timeout for the request and the number of messages to - * peek from the queue. - */ -public class PeekMessagesOptions extends QueueServiceOptions { - private Integer numberOfMessages; - - /** - * Sets the server request timeout value associated with this {@link PeekMessagesOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link PeekMessagesOptions} instance is passed as - * a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link PeekMessagesOptions} instance. - */ - @Override - public PeekMessagesOptions setTimeout(Integer timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * Gets the number of messages to return in the response to a - * {@link QueueContract#peekMessages(String, PeekMessagesOptions) peekMessages} request specified in this instance. - * - * @return - * The number of messages to return in the response. - */ - public Integer getNumberOfMessages() { - return numberOfMessages; - } - - /** - * Sets the number of messages to return in the response to a - * {@link QueueContract#peekMessages(String, PeekMessagesOptions) peekMessages} request. - *

- * The numberOfMessages value only affects calls made on methods where this {@link PeekMessagesOptions} - * instance is passed as a parameter. - * - * - * @param numberOfMessages - * The number of messages to return in the response. This value must be in the range from 0 to 32. - * @return - * A reference to this {@link PeekMessagesOptions} instance. - */ - public PeekMessagesOptions setNumberOfMessages(Integer numberOfMessages) { - this.numberOfMessages = numberOfMessages; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesResult.java deleted file mode 100644 index aac5f1990cb06..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/PeekMessagesResult.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import com.microsoft.windowsazure.services.core.RFC1123DateAdapter; -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * A wrapper class for the results returned in response to Queue Service REST API operations to peek messages. This - * is returned by calls to implementations of {@link QueueContract#peekMessages(String)} and - * {@link QueueContract#peekMessages(String, PeekMessagesOptions)}. - *

- * See the Peek Messages documentation - * on MSDN for details of the underlying Queue Service REST API operation. - */ -@XmlRootElement(name = "QueueMessagesList") -public class PeekMessagesResult { - private List queueMessages = new ArrayList(); - - /** - * Gets the list of queue messages returned by a {@link QueueContract}.peekMessages request. The queue - * messages returned do not have a visibility timeout set, and they can be retrieved by other clients for - * processing. - * - * @return - * A {@link List} of {@link QueueMessage} instances representing the messages returned by the request. - */ - @XmlElement(name = "QueueMessage") - public List getQueueMessages() { - return queueMessages; - } - - /** - * Reserved for internal use. Sets the list of queue messages returned by a {@link QueueContract} - * .peekMessages request. This method is invoked by the API as part of the response generation from the - * Queue Service REST API operation to set the value from the queue message list returned by the server. - * - * @param queueMessages - * A {@link List} of {@link QueueMessage} instances representing the messages returned by the request. - */ - public void setQueueMessages(List queueMessages) { - this.queueMessages = queueMessages; - } - - /** - * Represents a message in the queue returned by the server. A {@link QueueMessage} instance contains a copy of the - * queue message data in the storage service as of the time the message was requested. - */ - public static class QueueMessage { - private String messageId; - private Date insertionDate; - private Date expirationDate; - private int dequeueCount; - private String messageText; - - /** - * Gets the message ID for the message in the queue. * - * - * @return - * A {@link String} containing the message ID. - */ - @XmlElement(name = "MessageId") - public String getMessageId() { - return messageId; - } - - /** - * Reserved for internal use. Sets the value of the message ID for the queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the message ID returned by the server. - * - * @param messageId - * A {@link String} containing the message ID. - */ - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - /** - * Gets the {@link Date} when this message was added to the queue. - * - * @return - * The {@link Date} when this message was added to the queue. - */ - @XmlElement(name = "InsertionTime") - @XmlJavaTypeAdapter(RFC1123DateAdapter.class) - public Date getInsertionDate() { - return insertionDate; - } - - /** - * Reserved for internal use. Sets the value of the insertion time for the queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the insertion time returned by the server. - * - * @param insertionDate - * The {@link Date} when this message was added to the queue. - */ - public void setInsertionDate(Date insertionDate) { - this.insertionDate = insertionDate; - } - - /** - * Gets the {@link Date} when this message will expire and be automatically removed from the queue. - * - * @return - * The {@link Date} when this message will expire. - */ - @XmlElement(name = "ExpirationTime") - @XmlJavaTypeAdapter(RFC1123DateAdapter.class) - public Date getExpirationDate() { - return expirationDate; - } - - /** - * Reserved for internal use. Sets the value of the expiration time for the queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the expiration time returned by the server. - * - * @param expirationDate - * The {@link Date} when this message will expire. - */ - public void setExpirationDate(Date expirationDate) { - this.expirationDate = expirationDate; - } - - /** - * Gets the number of times this queue message has been retrieved with a list messages operation. - * - * @return - * The number of times this queue message has been retrieved. - */ - @XmlElement(name = "DequeueCount") - public int getDequeueCount() { - return dequeueCount; - } - - /** - * Reserved for internal use. Sets the value of the dequeue count of the message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the queue message dequeue count returned by the server. - * - * @param dequeueCount - * The number of times this queue message has been retrieved. - */ - public void setDequeueCount(int dequeueCount) { - this.dequeueCount = dequeueCount; - } - - /** - * Gets the {@link String} containing the content of the queue message. - * - * @return - * A {@link String} containing the content of the queue message. - */ - @XmlElement(name = "MessageText") - public String getMessageText() { - return messageText; - } - - /** - * Reserved for internal use. Sets the {@link String} containing the content of the message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the queue message content returned by the server. - * - * @param messageText - * A {@link String} containing the content of the message. - */ - public void setMessageText(String messageText) { - this.messageText = messageText; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/QueueServiceOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/QueueServiceOptions.java deleted file mode 100644 index a0836fa64f091..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/QueueServiceOptions.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * Represents the base class for options that may be set on Queue Service REST API operations invoked through the - * {@link QueueContract} interface. This class defines a server request timeout, which can be applied to all operations. - */ -public class QueueServiceOptions { - // Nullable because it is optional - private Integer timeout; - - /** - * Gets the current server request timeout value associated with this {@link QueueServiceOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link QueueServiceOptions} instance is passed as - * a parameter. - * - * @return - * The server request timeout value in milliseconds. - */ - public Integer getTimeout() { - return timeout; - } - - /** - * Sets the server request timeout value associated with this {@link QueueServiceOptions} instance. - *

- * The timeout value only affects calls made on methods where this {@link QueueServiceOptions} instance is passed as - * a parameter. - * - * @param timeout - * The server request timeout value to set in milliseconds. - * @return - * A reference to this {@link QueueServiceOptions} instance. - */ - public QueueServiceOptions setTimeout(Integer timeout) { - this.timeout = timeout; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ServiceProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ServiceProperties.java deleted file mode 100644 index e83c9ff5bf044..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/ServiceProperties.java +++ /dev/null @@ -1,432 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * A wrapper class for the Queue service properties set or retrieved with Queue Service REST API operations. This - * is returned by calls to implementations of {@link QueueContract#getServiceProperties()} and - * {@link QueueContract#getServiceProperties(QueueServiceOptions)} and passed to the server with calls to - * {@link QueueContract#setServiceProperties(ServiceProperties)} and - * {@link QueueContract#setServiceProperties(ServiceProperties, QueueServiceOptions)}. - *

- * See the Get Queue Service Properties - * and Set Queue Service Properties - * documentation on MSDN for details of the underlying Queue Service REST API operations. See the Storage Analytics Overview - * documentation on MSDN for more information about logging and metrics. - */ -@XmlRootElement(name = "StorageServiceProperties") -public class ServiceProperties { - private Logging logging = new Logging(); - private Metrics metrics = new Metrics(); - - /** - * Gets a reference to the {@link Logging} instance in this {@link ServiceProperties} instance. - *

- * This {@link ServiceProperties} instance holds a local copy of the Queue service properties when returned by a - * call to {@link QueueContract}.getServiceProperties. - *

- * Note that changes to this value are not reflected in the Queue service properties until they have been set on the - * storage account with a call to {@link QueueContract}.setServiceProperties. - * - * @return - * A reference to the {@link Logging} instance in this {@link ServiceProperties} instance. - */ - @XmlElement(name = "Logging") - public Logging getLogging() { - return logging; - } - - /** - * Sets the {@link Logging} instance in this {@link ServiceProperties} instance. - *

- * Note that changes to this value are not reflected in the Queue service properties until they have been set on the - * storage account with a call to {@link QueueContract}.setServiceProperties. - * - * @param logging - * The {@link Logging} instance to set in this {@link ServiceProperties} instance. - * @return - * A reference to this {@link ServiceProperties} instance. - */ - public ServiceProperties setLogging(Logging logging) { - this.logging = logging; - return this; - } - - /** - * Gets a reference to the {@link Metrics} instance in this {@link ServiceProperties} instance. - *

- * This {@link ServiceProperties} instance holds a local copy of the Queue service properties when returned by a - * call to {@link QueueContract}.getServiceProperties. - *

- * Note that changes to this value are not reflected in the Queue service properties until they have been set on the - * storage account with a call to {@link QueueContract}.setServiceProperties. - * - * @return - * A reference to the {@link Metrics} instance in this {@link ServiceProperties} instance. - */ - @XmlElement(name = "Metrics") - public Metrics getMetrics() { - return metrics; - } - - /** - * Sets the {@link Metrics} instance in this {@link ServiceProperties} instance. - *

- * Note that changes to this value are not reflected in the Queue service properties until they have been set on the - * storage account with a call to {@link QueueContract}.setServiceProperties. - * - * @param metrics - * The {@link Metrics} instance to set in this {@link ServiceProperties} instance. - * @return - * A reference to this {@link ServiceProperties} instance. - */ - public ServiceProperties setMetrics(Metrics metrics) { - this.metrics = metrics; - return this; - } - - /** - * This inner class represents the settings for logging on the Queue service of the storage account. These settings - * include the Storage Analytics version, whether to log delete requests, read requests, or write requests, and a - * {@link RetentionPolicy} instance for retention policy settings. - */ - public static class Logging { - private String version; - private Boolean delete; - private Boolean read; - private Boolean write; - private RetentionPolicy retentionPolicy; - - /** - * Gets a reference to the {@link RetentionPolicy} instance in this {@link Logging} instance. - * - * @return - * A reference to the {@link RetentionPolicy} instance in this {@link Logging} instance. - */ - @XmlElement(name = "RetentionPolicy") - public RetentionPolicy getRetentionPolicy() { - return retentionPolicy; - } - - /** - * Sets the {@link RetentionPolicy} instance in this {@link Logging} instance. - * - * @param retentionPolicy - * The {@link RetentionPolicy} instance to set in this {@link Logging} instance. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setRetentionPolicy(RetentionPolicy retentionPolicy) { - this.retentionPolicy = retentionPolicy; - return this; - } - - /** - * Gets a flag indicating whether queue write operations are logged. If this value is true then all - * requests that write to the Queue service will be logged. These requests include adding a message, updating a - * message, setting queue metadata, and creating a queue. - * - * @return - * true if queue write operations are logged, otherwise false. - */ - @XmlElement(name = "Write") - public boolean isWrite() { - return write; - } - - /** - * Sets a flag indicating whether queue write operations are logged. If this value is true then all - * requests that write to the Queue service will be logged. These requests include adding a message, updating a - * message, setting queue metadata, and creating a queue. - * - * @param write - * true to enable logging of queue write operations, otherwise false. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setWrite(boolean write) { - this.write = write; - return this; - } - - /** - * Gets a flag indicating whether queue read operations are logged. If this value is true then all - * requests that read from the Queue service will be logged. These requests include listing queues, getting - * queue metadata, listing messages, and peeking messages. - * - * @return - * true if queue read operations are logged, otherwise false. - */ - @XmlElement(name = "Read") - public boolean isRead() { - return read; - } - - /** - * Sets a flag indicating whether queue read operations are logged. If this value is true then all - * requests that read from the Queue service will be logged. These requests include listing queues, getting - * queue metadata, listing messages, and peeking messages. - * - * @param read - * true to enable logging of queue read operations, otherwise false. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setRead(boolean read) { - this.read = read; - return this; - } - - /** - * Gets a flag indicating whether queue delete operations are logged. If this value is true then - * all requests that delete from the Queue service will be logged. These requests include deleting queues, - * deleting messages, and clearing messages. - * - * @return - * true if queue delete operations are logged, otherwise false. - */ - @XmlElement(name = "Delete") - public boolean isDelete() { - return delete; - } - - /** - * Sets a flag indicating whether queue delete operations are logged. If this value is true then - * all requests that delete from the Queue service will be logged. These requests include deleting queues, - * deleting messages, and clearing messages. - * - * @param delete - * true to enable logging of queue delete operations, otherwise false. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setDelete(boolean delete) { - this.delete = delete; - return this; - } - - /** - * Gets the Storage Analytics version number associated with this {@link Logging} instance. - * - * @return - * A {@link String} containing the Storage Analytics version number. - */ - @XmlElement(name = "Version") - public String getVersion() { - return version; - } - - /** - * Sets the Storage Analytics version number to associate with this {@link Logging} instance. The current - * supported - * version number is "1.0". - *

- * See the Storage Analytics - * Overview documentation on MSDN for more information. - * - * @param version - * A {@link String} containing the Storage Analytics version number to set. - * @return - * A reference to this {@link Logging} instance. - */ - public Logging setVersion(String version) { - this.version = version; - return this; - } - } - - /** - * This inner class represents the settings for metrics on the Queue service of the storage account. These settings - * include the Storage Analytics version, whether metrics are enabled, whether to include API operation summary - * statistics, and a {@link RetentionPolicy} instance for retention policy settings. - */ - public static class Metrics { - private String version; - private boolean enabled; - private Boolean includeAPIs; - private RetentionPolicy retentionPolicy; - - /** - * Gets a reference to the {@link RetentionPolicy} instance in this {@link Metrics} instance. - * - * @return - * A reference to the {@link RetentionPolicy} instance in this {@link Metrics} instance. - */ - @XmlElement(name = "RetentionPolicy") - public RetentionPolicy getRetentionPolicy() { - return retentionPolicy; - } - - /** - * Sets the {@link RetentionPolicy} instance in this {@link Metrics} instance. - * - * @param retentionPolicy - * The {@link RetentionPolicy} instance to set in this {@link Metrics} instance. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setRetentionPolicy(RetentionPolicy retentionPolicy) { - this.retentionPolicy = retentionPolicy; - return this; - } - - /** - * Gets a flag indicating whether metrics should generate summary statistics for called API operations. If this - * value is true then all Queue service REST API operations will be included in the metrics. - * - * @return - * true if Queue service REST API operations are included in metrics, otherwise - * false. - */ - @XmlElement(name = "IncludeAPIs") - public Boolean isIncludeAPIs() { - return includeAPIs; - } - - /** - * Sets a flag indicating whether metrics should generate summary statistics for called API operations. If this - * value is true then all Queue service REST API operations will be included in the metrics. - * - * @param includeAPIs - * true to include Queue service REST API operations in metrics, otherwise - * false. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setIncludeAPIs(Boolean includeAPIs) { - this.includeAPIs = includeAPIs; - return this; - } - - /** - * Gets a flag indicating whether metrics is enabled for the Queue storage service. - * - * @return - * A flag indicating whether metrics is enabled for the Queue storage service. - */ - @XmlElement(name = "Enabled") - public boolean isEnabled() { - return enabled; - } - - /** - * Sets a flag indicating whether to enable metrics for the Queue storage service. - * - * @param enabled - * true to enable metrics for the Queue storage service, otherwise false. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Gets the Storage Analytics version number associated with this {@link Metrics} instance. - * - * @return - * A {@link String} containing the Storage Analytics version number. - */ - @XmlElement(name = "Version") - public String getVersion() { - return version; - } - - /** - * Sets the Storage Analytics version number to associate with this {@link Metrics} instance. The current - * supported version number is "1.0". - *

- * See the Storage Analytics - * Overview documentation on MSDN for more information. - * - * @param version - * A {@link String} containing the Storage Analytics version number to set. - * @return - * A reference to this {@link Metrics} instance. - */ - public Metrics setVersion(String version) { - this.version = version; - return this; - } - } - - /** - * This inner class represents the retention policy settings for logging or metrics on the Queue service of the - * storage account. These settings include whether a retention policy is enabled for the data, and the number of - * days that metrics or logging data should be retained. - */ - public static class RetentionPolicy { - private boolean enabled; - private Integer days; // nullable, because optional if "enabled" is false - - /** - * Gets the number of days that metrics or logging data should be retained. All data older than this value will - * be deleted. The value may be null if a retention policy is not enabled. - * - * @return - * The number of days that metrics or logging data should be retained. - */ - @XmlElement(name = "Days") - public Integer getDays() { - return days; - } - - /** - * Sets the number of days that metrics or logging data should be retained. All data older than this value will - * be deleted. The value must be in the range from 1 to 365. This value must be set if a retention policy is - * enabled, but is not required if a retention policy is not enabled. - * - * @param days - * The number of days that metrics or logging data should be retained. - * @return - * A reference to this {@link RetentionPolicy} instance. - */ - public RetentionPolicy setDays(Integer days) { - this.days = days; - return this; - } - - /** - * Gets a flag indicating whether a retention policy is enabled for the storage service. - * - * @return - * true if data retention is enabled, otherwise false. - */ - @XmlElement(name = "Enabled") - public boolean isEnabled() { - return enabled; - } - - /** - * Sets a flag indicating whether a retention policy is enabled for the storage service. - * - * @param enabled - * Set true to enable data retention. - * @return - * A reference to this {@link RetentionPolicy} instance. - */ - public RetentionPolicy setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/UpdateMessageResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/UpdateMessageResult.java deleted file mode 100644 index b75fa54659d44..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/queue/models/UpdateMessageResult.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.models; - -import java.util.Date; - -import com.microsoft.windowsazure.services.queue.QueueContract; - -/** - * A wrapper class for the results returned in response to Queue Service REST API operations to update a message. This - * is returned by calls to implementations of {@link QueueContract#updateMessage(String, String, String, String, int)} - * and {@link QueueContract#updateMessage(String, String, String, String, int, QueueServiceOptions)}. - *

- * See the Update Message documentation - * on MSDN for details of the underlying Queue Service REST API operation. - */ -public class UpdateMessageResult { - private String popReceipt; - private Date timeNextVisible; - - /** - * Gets the pop receipt value for the updated queue message. The pop receipt is a value that is opaque to the client - * that must be used along with the message ID to validate an update message or delete message operation. - * - * @return - * A {@link String} containing the pop receipt value for the queue message. - */ - public String getPopReceipt() { - return popReceipt; - } - - /** - * Reserved for internal use. Sets the value of the pop receipt for the updated queue message. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the pop receipt returned by the server. - * - * @param popReceipt - * A {@link String} containing the pop receipt value for the queue message. - */ - public void setPopReceipt(String popReceipt) { - this.popReceipt = popReceipt; - } - - /** - * Gets the {@link Date} when the updated message will become visible in the queue. - * - * @return - * The {@link Date} when the updated message will become visible in the queue. - */ - public Date getTimeNextVisible() { - return timeNextVisible; - } - - /** - * Reserved for internal use. Sets the value of the time the updated message will become visible. This method is - * invoked by the API as part of the response generation from the Queue Service REST API operation to set the - * value with the time next visible returned by the server. - * - * @param timeNextVisible - * The {@link Date} when the updated message will become visible in the queue. - */ - public void setTimeNextVisible(Date timeNextVisible) { - this.timeNextVisible = timeNextVisible; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/Exports.java deleted file mode 100644 index 4c5929ec18eb2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/Exports.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import java.util.Map; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.serviceBus.implementation.BrokerPropertiesMapper; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntryModelProvider; -import com.microsoft.windowsazure.services.serviceBus.implementation.MarshallerProvider; -import com.microsoft.windowsazure.services.serviceBus.implementation.ServiceBusExceptionProcessor; -import com.microsoft.windowsazure.services.serviceBus.implementation.ServiceBusRestProxy; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; - -public class Exports implements Builder.Exports { - @Override - public void register(Builder.Registry registry) { - - // provide contract implementation - registry.add(ServiceBusContract.class, ServiceBusExceptionProcessor.class); - registry.add(ServiceBusExceptionProcessor.class); - registry.add(ServiceBusRestProxy.class); - registry.add(UserAgentFilter.class); - - // alter jersey client config for serviceBus - registry.alter(ServiceBusContract.class, ClientConfig.class, new Builder.Alteration() { - - @Override - public ClientConfig alter(String profile, ClientConfig instance, Builder builder, - Map properties) { - - // enable this feature for unattributed json object serialization - instance.getProperties().put(JSONConfiguration.FEATURE_POJO_MAPPING, true); - - // need to avoid certain element prefixes, which the service does not ignore - instance.getSingletons().add(new MarshallerProvider()); - - // add body reader/writer for EntryModel descendant classes - instance.getClasses().add(EntryModelProvider.class); - - return instance; - } - }); - - // convenience provider to transform BrokerProperty headers to json - registry.add(BrokerPropertiesMapper.class); - - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusConfiguration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusConfiguration.java deleted file mode 100644 index eb01a664440ea..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusConfiguration.java +++ /dev/null @@ -1,217 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import com.microsoft.windowsazure.services.core.Configuration; - -/** - * Provides functionality to create a service bus configuration. - * - */ -public class ServiceBusConfiguration { - - - /** - * Defines the configuration connection string constant. - * - */ - public final static String CONNECTION_STRING = "serviceBus.connection.string"; - - /** - * Defines the configuration URI constant. - * - */ - public final static String URI = "serviceBus.uri"; - - /** - * Defines the configuration wrap URI constant. - * - */ - public final static String WRAP_URI = "serviceBus.wrap.uri"; - - /** - * Defines the configuration wrap name constant. - * - */ - public final static String WRAP_NAME = "serviceBus.wrap.name"; - - /** - * Defines the configuration wrap password constant. - * - */ - public final static String WRAP_PASSWORD = "serviceBus.wrap.password"; - - /** - * Creates a service bus configuration using the specified namespace, name, and password. - * - * @param namespace - * A String object that represents the namespace. - * - * @param authenticationName - * A String object that represents the authentication name. - * - * @param authenticationPassword - * A String object that represents the authentication password. - * - * @param serviceBusRootUri - * A String object containing the base URI that is added to your - * Service Bus namespace to form the URI to connect to the Service Bus service. - * - * To access the default public Azure service, pass ".servicebus.windows.net" - * - * @param wrapRootUri - * A String object containing the base URI that is added to your - * Service Bus namespace to form the URI to get an access token for the Service - * Bus service. - * - * To access the default public Azure service, pass "-sb.accesscontrol.windows.net/WRAPv0.9" - * - * @return - * A Configuration object that can be used when creating an instance of the - * ServiceBusService class. - * - */ - public static Configuration configureWithWrapAuthentication(String namespace, String authenticationName, - String authenticationPassword, String serviceBusRootUri, String wrapRootUri) { - return configureWithWrapAuthentication(null, Configuration.getInstance(), namespace, authenticationName, - authenticationPassword, serviceBusRootUri, wrapRootUri); - } - - /** - * Creates a service bus configuration using the specified configuration, namespace, name, and password. - * - * @param configuration - * A previously instantiated Configuration object. - * - * @param namespace - * A String object that represents the namespace. - * - * @param authenticationName - * A String object that represents the authentication name. - * - * @param authenticationPassword - * A String object that represents the authentication password. - * - * @param serviceBusRootUri - * A String object containing the base URI that is added to your - * Service Bus namespace to form the URI to connect to the Service Bus service. - * - * To access the default public Azure service, pass ".servicebus.windows.net" - * - * @param wrapRootUri - * A String object containing the base URI that is added to your - * Service Bus namespace to form the URI to get an access token for the Service - * Bus service. - * - * To access the default public Azure service, pass "-sb.accesscontrol.windows.net/WRAPv0.9" - * - * @return - * A Configuration object that can be used when creating an instance of the - * ServiceBusService class. - * - */ - public static Configuration configureWithWrapAuthentication(Configuration configuration, String namespace, - String authenticationName, String authenticationPassword, String serviceBusRootUri, String wrapRootUri) { - return configureWithWrapAuthentication(null, configuration, namespace, authenticationName, - authenticationPassword, serviceBusRootUri, wrapRootUri); - } - - /** - * Creates a service bus configuration using the specified profile, configuration, namespace, name, and password. - * - * @param profile - * A String object that represents the profile. - * - * @param configuration - * A previously instantiated Configuration object. - * - * @param namespace - * A String object that represents the namespace. - * - * @param authenticationName - * A String object that represents the authentication name. - * - * @param authenticationPassword - * A String object that represents the authentication password. - * - * @param serviceBusRootUri - * A String object containing the base URI that is added to your - * Service Bus namespace to form the URI to connect to the Service Bus service. - * - * To access the default public Azure service, pass ".servicebus.windows.net" - * - * @param wrapRootUri - * A String object containing the base URI that is added to your - * Service Bus namespace to form the URI to get an access token for the Service - * Bus service. - * - * To access the default public Azure service, pass "-sb.accesscontrol.windows.net/WRAPv0.9" - * - * @return - * A Configuration object that can be used when creating an instance of the - * ServiceBusService class. - * - */ - public static Configuration configureWithWrapAuthentication(String profile, Configuration configuration, - String namespace, String authenticationName, String authenticationPassword, String serviceBusRootUri, - String wrapRootUri) { - - if (profile == null) { - profile = ""; - } - else if (profile.length() != 0 && !profile.endsWith(".")) { - profile = profile + "."; - } - - configuration.setProperty(profile + CONNECTION_STRING, null); - - configuration.setProperty(profile + URI, "https://" + namespace + serviceBusRootUri); - - configuration.setProperty(profile + WRAP_URI, "https://" + namespace + wrapRootUri); - - configuration.setProperty(profile + WRAP_NAME, authenticationName); - configuration.setProperty(profile + WRAP_PASSWORD, authenticationPassword); - - return configuration; - } - - /** - * Creates a service bus configuration using the specified connection string. - * @param profile - * A String object that represents the profile. - * @param configuration - * A previously instantiated Configuration object. - * @param connectionString - * A String object the contains the connection string for the - * service bus connection information. - * @return - * A Configuration object that can be used when creating an instance of the - * ServiceBusService class. - */ - public static Configuration configureWithConnectionString(String profile, Configuration configuration, - String connectionString) { - - if (profile == null) { - profile = ""; - } - else if (profile.length() != 0 && !profile.endsWith(".")) { - profile = profile + "."; - } - - configuration.setProperty(profile + CONNECTION_STRING, connectionString); - - return configuration; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusContract.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusContract.java deleted file mode 100644 index 537d22623dd0a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusContract.java +++ /dev/null @@ -1,513 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import com.microsoft.windowsazure.services.core.FilterableService; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.serviceBus.models.BrokeredMessage; -import com.microsoft.windowsazure.services.serviceBus.models.CreateQueueResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateRuleResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateSubscriptionResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateTopicResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetQueueResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetRuleResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetSubscriptionResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetTopicResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListQueuesOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListQueuesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListRulesOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListRulesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListSubscriptionsOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListSubscriptionsResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsResult; -import com.microsoft.windowsazure.services.serviceBus.models.QueueInfo; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveQueueMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveSubscriptionMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.RuleInfo; -import com.microsoft.windowsazure.services.serviceBus.models.SubscriptionInfo; -import com.microsoft.windowsazure.services.serviceBus.models.TopicInfo; - -/** - * - * Defines the service bus contract. - * - */ -public interface ServiceBusContract extends FilterableService { - - /** - * Sends a queue message. - * - * @param queuePath - * A String object that represents the name of the queue to which the message will be sent. - * @param message - * A Message object that represents the message to send. - * @throws ServiceException - * If a service exception is encountered. - */ - void sendQueueMessage(String queuePath, BrokeredMessage message) throws ServiceException; - - /** - * Receives a queue message. - * - * @param queuePath - * A String object that represents the name of the queue from which to receive the message. - * @return A ReceiveQueueMessageResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ReceiveQueueMessageResult receiveQueueMessage(String queuePath) throws ServiceException; - - /** - * Receives a queue message using the specified receive message options. - * - * @param queuePath - * A String object that represents the name of the queue from which to receive the message. - * @param options - * A ReceiveMessageOptions object that represents the receive message options. - * @return A ReceiveQueueMessageResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ReceiveQueueMessageResult receiveQueueMessage(String queuePath, ReceiveMessageOptions options) - throws ServiceException; - - /** - * Sends a topic message. - * - * @param topicPath - * A String object that represents the name of the topic to which the message will be sent. - * @param message - * A Message object that represents the message to send. - * @throws ServiceException - * If a service exception is encountered. - */ - void sendTopicMessage(String topicPath, BrokeredMessage message) throws ServiceException; - - /** - * Receives a subscription message. - * - * @param topicPath - * A String object that represents the name of the topic to receive. - * @param subscriptionName - * A String object that represents the name of the subscription from the message will be - * received. - * @return A ReceiveSubscriptionMessageResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ReceiveSubscriptionMessageResult receiveSubscriptionMessage(String topicPath, String subscriptionName) - throws ServiceException; - - /** - * Receives a subscription message using the specified receive message options. - * - * @param topicPath - * A String object that represents the name of the topic to receive. - * @param subscriptionName - * A String object that represents the name of the subscription from the message will be - * received. - * @param options - * A ReceiveMessageOptions object that represents the receive message options. - * @return A ReceiveSubscriptionMessageResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ReceiveSubscriptionMessageResult receiveSubscriptionMessage(String topicPath, String subscriptionName, - ReceiveMessageOptions options) throws ServiceException; - - /** - * Unlocks a message. - * - * @param message - * A Message object that represents the message to unlock. - * @throws ServiceException - * If a service exception is encountered. - */ - void unlockMessage(BrokeredMessage message) throws ServiceException; - - /** - * Sends a message. - * - * @param path - * A String object that represents the path to which the message will be sent. - * This may be the value of a queuePath or a topicPath. - * @param message - * A Message object that represents the message to send. - * - * @throws ServiceException - * If a service exception is encountered. - */ - void sendMessage(String path, BrokeredMessage message) throws ServiceException; - - /** - * Receives a message. - * - * @param path - * A String object that represents the path from which a message will be received. - * This may either be the value of queuePath or a combination of - * the topicPath + "/subscriptions/" + subscriptionName. - * @return A ReceiveSubscriptionMessageResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ReceiveMessageResult receiveMessage(String path) throws ServiceException; - - /** - * Receives a message using the specified receive message options. - * - * @param path - * A String object that represents the path from which a message will be received. - * This may either be the value of queuePath or a combination of - * the topicPath + "/subscriptions/" + subscriptionName. - * @param options - * A ReceiveMessageOptions object that represents the receive message options. - * @return A ReceiveSubscriptionMessageResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ReceiveMessageResult receiveMessage(String path, ReceiveMessageOptions options) throws ServiceException; - - /** - * Deletes a message. - * - * @param message - * A Message object that represents the message to delete. - * @throws ServiceException - * If a service exception is encountered. - */ - void deleteMessage(BrokeredMessage message) throws ServiceException; - - /** - * Creates a queue. - * - * @param queueInfo - * A QueueInfo object that represents the queue to create. - * @return A CreateQueueResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - CreateQueueResult createQueue(QueueInfo queueInfo) throws ServiceException; - - /** - * Deletes a queue. - * - * @param queuePath - * A String object that represents the name of the queue to delete. - * @throws ServiceException - * If a service exception is encountered. - */ - void deleteQueue(String queuePath) throws ServiceException; - - /** - * Retrieves a queue. - * - * @param queuePath - * A String object that represents the name of the queue to retrieve. - * @return A GetQueueResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - GetQueueResult getQueue(String queuePath) throws ServiceException; - - /** - * Returns a list of queues. - * - * @return A ListQueuesResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ListQueuesResult listQueues() throws ServiceException; - - /** - * Returns a list of queues. - * - * @param options - * A ListQueueOptions object that represents the options to list the queue. - * @return A ListQueuesResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ListQueuesResult listQueues(ListQueuesOptions options) throws ServiceException; - - /** - * Updates the information of a queue. - * - * @param queueInfo - * The information of a queue to be updated. - * - * @return A QueueInfo object that represents the updated queue. - * - * @throws ServiceException - * If a service exception is encountered. - */ - QueueInfo updateQueue(QueueInfo queueInfo) throws ServiceException; - - /** - * Creates a topic. - * - * @param topic - * A Topic object that represents the topic to create. - * @return A CreateTopicResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - CreateTopicResult createTopic(TopicInfo topic) throws ServiceException; - - /** - * Deletes a topic. - * - * @param topicPath - * A String object that represents the name of the queue to delete. - * @throws ServiceException - * If a service exception is encountered. - */ - void deleteTopic(String topicPath) throws ServiceException; - - /** - * Retrieves a topic. - * - * @param topicPath - * A String object that represents the name of the topic to retrieve. - * @return A GetTopicResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - GetTopicResult getTopic(String topicPath) throws ServiceException; - - /** - * Returns a list of topics. - * - * @return A ListTopicsResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ListTopicsResult listTopics() throws ServiceException; - - /** - * Returns a list of topics. - * - * @param options - * A ListTopicsOptions object that represents the options to list the topic. - * @return A ListTopicsResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ListTopicsResult listTopics(ListTopicsOptions options) throws ServiceException; - - /** - * Updates a topic. - * - * @param topicInfo - * A TopicInfo object that represents the topic to be updated. - * - * @return A TopicInfo object that represents the update topic result. - * @throws ServiceException - * If a service exception is encountered. - */ - TopicInfo updateTopic(TopicInfo topicInfo) throws ServiceException; - - /** - * Creates a subscription. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscription - * A Subscription object that represents the subscription to create. - * @return A CreateSubscriptionResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - CreateSubscriptionResult createSubscription(String topicPath, SubscriptionInfo subscription) - throws ServiceException; - - /** - * Deletes a subscription. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscriptionName - * A String object that represents the name of the subscription to delete. - * @throws ServiceException - * If a service exception is encountered. - */ - void deleteSubscription(String topicPath, String subscriptionName) throws ServiceException; - - /** - * Retrieves a subscription. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscriptionName - * A String object that represents the name of the subscription to retrieve. - * @return A GetSubscriptionResult object that represents the result. - * A String object that represents the name of the subscription to retrieve. - * @throws ServiceException - * If a service exception is encountered. - */ - GetSubscriptionResult getSubscription(String topicPath, String subscriptionName) throws ServiceException; - - /** - * Returns a list of subscriptions. - * - * @param topicPath - * A String object that represents the name of the topic for the subscriptions to retrieve. - * @return A ListSubscriptionsResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ListSubscriptionsResult listSubscriptions(String topicPath) throws ServiceException; - - /** - * Returns a list of subscriptions. - * - * @param topicPath - * A String object that represents the name of the topic for the subscriptions to retrieve. - * - * @param options - * A ListSubscriptionsOptions object that represents the options to list subscriptions. - * - * @return A ListSubscriptionsResult object that represents the result. - * - * @throws ServiceException - * the service exception - */ - ListSubscriptionsResult listSubscriptions(String topicPath, ListSubscriptionsOptions options) - throws ServiceException; - - /** - * Updates a subscription. - * - * @param topicName - * A String option which represents the name of the topic. - * @param subscriptionInfo - * A SubscriptionInfo option which represents the information of the subscription. - * @return A SubscriptionInfo object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - SubscriptionInfo updateSubscription(String topicName, SubscriptionInfo subscriptionInfo) throws ServiceException; - - /** - * Creates a rule. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscriptionName - * A String object that represents the name of the subscription for which the rule will be - * created. - * @param rule - * A Rule object that represents the rule to create. - * @return A CreateRuleResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - CreateRuleResult createRule(String topicPath, String subscriptionName, RuleInfo rule) throws ServiceException; - - /** - * Deletes a rule. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscriptionName - * A String object that represents the name of the subscription for which the rule will be - * deleted. - * @param ruleName - * A String object that represents the name of the rule to delete. - * @throws ServiceException - * If a service exception is encountered. - */ - void deleteRule(String topicPath, String subscriptionName, String ruleName) throws ServiceException; - - /** - * Retrieves a rule. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscriptionName - * A String object that represents the name of the subscription for which the rule will be - * retrieved. - * @param ruleName - * A String object that represents the name of the rule to retrieve. - * @return A GetRuleResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - GetRuleResult getRule(String topicPath, String subscriptionName, String ruleName) throws ServiceException; - - /** - * Returns a list of rules. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscriptionName - * A String object that represents the name of the subscription whose rules are being - * retrieved. - * @return A ListRulesResult object that represents the result. - * @throws ServiceException - * If a service exception is encountered. - */ - ListRulesResult listRules(String topicPath, String subscriptionName) throws ServiceException; - - /** - * Returns a list of rules. - * - * @param topicPath - * A String object that represents the name of the topic for the subscription. - * @param subscriptionName - * A String object that represents the name of the subscription whose rules are being - * retrieved. - * @param options - * A ListRulesOptions object that represents the options to retrieve rules. - * @return the list rules result - * @throws ServiceException - * If a service exception is encountered. - */ - ListRulesResult listRules(String topicPath, String subscriptionName, ListRulesOptions options) - throws ServiceException; - - /** - * Renew queue lock. - * - * @param queueName - * A String object that represents the name of the queue. - * @param messageId - * A String object that represents the ID of the message. - * @param lockToken - * A String object that represents the token of the lock. - * @throws ServiceException - * If a service exception is encountered. - */ - void renewQueueLock(String queueName, String messageId, String lockToken) throws ServiceException; - - /** - * Renew subscription lock. - * - * @param topicName - * A String object that represents the name of the topic. - * @param queueName - * A String object that represents the name of the queue. - * @param messageId - * A String object that represents the ID of the message. - * @param lockToken - * A String object that represents the token of the lock. - * @throws ServiceException - * If a service exception is encountered. - */ - void renewSubscriptionLock(String topicName, String subscriptionName, String messageId, String lockToken) - throws ServiceException; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/Util.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/Util.java deleted file mode 100644 index 128e23fe2f506..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/Util.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.serviceBus.models.QueueInfo; -import com.microsoft.windowsazure.services.serviceBus.models.TopicInfo; - -public class Util { - public static Iterable iterateQueues(ServiceBusContract service) throws ServiceException { - return service.listQueues().getItems(); - } - - public static Iterable iterateTopics(ServiceBusContract service) throws ServiceException { - return service.listTopics().getItems(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/EntryModelProvider.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/EntryModelProvider.java deleted file mode 100644 index 04ba3dce58b9c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/EntryModelProvider.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Type; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.ext.MessageBodyReader; -import javax.ws.rs.ext.MessageBodyWriter; - -import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; -import com.sun.jersey.spi.MessageBodyWorkers; - -public class EntryModelProvider extends AbstractMessageReaderWriterProvider> { - - MessageBodyWorkers workers; - - public EntryModelProvider(@Context MessageBodyWorkers workers) { - this.workers = workers; - } - - @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return EntryModel.class.isAssignableFrom(type); - } - - @Override - public EntryModel readFrom(Class> type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - - MessageBodyReader reader = workers - .getMessageBodyReader(Entry.class, Entry.class, annotations, mediaType); - - Entry entry = reader.readFrom(Entry.class, Entry.class, annotations, mediaType, httpHeaders, entityStream); - - // these exceptions are masked as a RuntimeException because they cannot - // be thrown by this override - try { - return type.getConstructor(Entry.class).newInstance(entry); - } - catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - catch (InvocationTargetException e) { - throw new RuntimeException(e); - } - catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - catch (InstantiationException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return EntryModel.class.isAssignableFrom(type); - } - - @Override - public void writeTo(EntryModel t, Class type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws IOException, WebApplicationException { - - Entry entry = t.getEntry(); - - MessageBodyWriter writer = workers - .getMessageBodyWriter(Entry.class, Entry.class, annotations, mediaType); - - writer.writeTo(entry, Entry.class, genericType, annotations, mediaType, httpHeaders, entityStream); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/Exports.java deleted file mode 100644 index e5a2629fa9c7c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/Exports.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import static com.microsoft.windowsazure.services.core.utils.ExportUtils.*; - -import java.net.URISyntaxException; -import java.util.Map; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.utils.ConnectionStringSyntaxException; -import com.microsoft.windowsazure.services.serviceBus.ServiceBusConfiguration; - -public class Exports implements Builder.Exports { - - @Override - public void register(Builder.Registry registry) { - registry.add(WrapContract.class, WrapRestProxy.class); - registry.add(WrapTokenManager.class); - registry.add(WrapFilter.class); - - registry.add(new Builder.Factory() { - - @Override - public ServiceBusConnectionSettings create(String profile, Class service, Builder builder, - Map properties) { - try { - return new ServiceBusConnectionSettings((String) getPropertyIfExists(profile, properties, - ServiceBusConfiguration.CONNECTION_STRING), (String) getPropertyIfExists(profile, - properties, ServiceBusConfiguration.URI), (String) getPropertyIfExists(profile, properties, - ServiceBusConfiguration.WRAP_URI), (String) getPropertyIfExists(profile, properties, - ServiceBusConfiguration.WRAP_NAME), (String) getPropertyIfExists(profile, properties, - ServiceBusConfiguration.WRAP_PASSWORD)); - } - catch (ConnectionStringSyntaxException e) { - throw new RuntimeException(e.getMessage(), e); - } - catch (URISyntaxException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - }); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionSettings.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionSettings.java deleted file mode 100644 index 20bd238789b9e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionSettings.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import java.net.URI; -import java.net.URISyntaxException; - -import com.microsoft.windowsazure.services.core.utils.ConnectionStringSyntaxException; - -/** - * Class that encapsulates all the various settings needed - * to connect to Service Bus, provided via either a - * connection string or via separate configuration variables. - *

- * The connection string is looked for first, falling back to separate config values if not found. - */ -class ServiceBusConnectionSettings { - private String uri; - private String wrapUri; - private String wrapName; - private String wrapPassword; - - public ServiceBusConnectionSettings(String connectionString, String uri, String wrapUri, String wrapName, - String wrapPassword) throws ConnectionStringSyntaxException, URISyntaxException { - if (connectionString != null) { - parseConnectionString(connectionString); - } - else { - this.uri = uri; - this.wrapUri = wrapUri; - this.wrapName = wrapName; - this.wrapPassword = wrapPassword; - } - } - - public String getUri() { - return uri; - } - - public String getWrapUri() { - return wrapUri; - } - - public String getWrapName() { - return wrapName; - } - - public String getWrapPassword() { - return wrapPassword; - } - - private boolean parseConnectionString(String connectionString) throws URISyntaxException, - ConnectionStringSyntaxException { - ServiceBusConnectionString cs = new ServiceBusConnectionString(connectionString); - setUri(cs); - setWrapUri(cs); - wrapName = cs.getSharedSecretIssuer(); - wrapPassword = cs.getSharedSecretValue(); - return true; - } - - private void setUri(ServiceBusConnectionString connectionString) { - uri = connectionString.getEndpoint().replaceFirst("^sb://", "https://"); - } - - private void setWrapUri(ServiceBusConnectionString connectionString) throws URISyntaxException { - if (connectionString.getStsEndpoint() == null || connectionString.getStsEndpoint().isEmpty()) { - URI hostUri = new URI(uri); - String namespace = hostUri.getHost().split("\\.")[0]; - wrapUri = "https://" + namespace + "-sb.accesscontrol.windows.net/WRAPv0.9"; - } - else { - wrapUri = connectionString.getStsEndpoint().replaceAll("\\/$", "") + "/WRAPv0.9"; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusExceptionProcessor.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusExceptionProcessor.java deleted file mode 100644 index 70e3de447c40a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusExceptionProcessor.java +++ /dev/null @@ -1,559 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import javax.inject.Inject; -import javax.ws.rs.WebApplicationException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.microsoft.windowsazure.services.serviceBus.ServiceBusContract; -import com.microsoft.windowsazure.services.serviceBus.models.BrokeredMessage; -import com.microsoft.windowsazure.services.serviceBus.models.CreateQueueResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateRuleResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateSubscriptionResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateTopicResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetQueueResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetRuleResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetSubscriptionResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetTopicResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListQueuesOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListQueuesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListRulesOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListRulesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListSubscriptionsOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListSubscriptionsResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsResult; -import com.microsoft.windowsazure.services.serviceBus.models.QueueInfo; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveQueueMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveSubscriptionMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.RuleInfo; -import com.microsoft.windowsazure.services.serviceBus.models.SubscriptionInfo; -import com.microsoft.windowsazure.services.serviceBus.models.TopicInfo; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.UniformInterfaceException; - -public class ServiceBusExceptionProcessor implements ServiceBusContract { - - private final ServiceBusContract next; - static Log log = LogFactory.getLog(ServiceBusContract.class); - - public ServiceBusExceptionProcessor(ServiceBusContract next) { - this.next = next; - } - - @Inject - public ServiceBusExceptionProcessor(ServiceBusRestProxy next) { - this.next = next; - } - - @Override - public ServiceBusContract withFilter(ServiceFilter filter) { - return new ServiceBusExceptionProcessor(next.withFilter(filter)); - } - - private ServiceException processCatch(ServiceException e) { - log.warn(e.getMessage(), e.getCause()); - return ServiceExceptionFactory.process("serviceBus", e); - } - - @Override - public void sendQueueMessage(String path, BrokeredMessage message) throws ServiceException { - try { - next.sendQueueMessage(path, message); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ReceiveQueueMessageResult receiveQueueMessage(String queueName) throws ServiceException { - try { - return next.receiveQueueMessage(queueName); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ReceiveQueueMessageResult receiveQueueMessage(String queueName, ReceiveMessageOptions options) - throws ServiceException { - try { - return next.receiveQueueMessage(queueName, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void sendTopicMessage(String path, BrokeredMessage message) throws ServiceException { - try { - next.sendTopicMessage(path, message); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ReceiveSubscriptionMessageResult receiveSubscriptionMessage(String topicName, String subscriptionName) - throws ServiceException { - try { - return next.receiveSubscriptionMessage(topicName, subscriptionName); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ReceiveSubscriptionMessageResult receiveSubscriptionMessage(String topicName, String subscriptionName, - ReceiveMessageOptions options) throws ServiceException { - try { - return next.receiveSubscriptionMessage(topicName, subscriptionName, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void unlockMessage(BrokeredMessage message) throws ServiceException { - try { - next.unlockMessage(message); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteMessage(BrokeredMessage message) throws ServiceException { - try { - next.deleteMessage(message); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateQueueResult createQueue(QueueInfo queue) throws ServiceException { - try { - return next.createQueue(queue); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteQueue(String queuePath) throws ServiceException { - try { - next.deleteQueue(queuePath); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetQueueResult getQueue(String queuePath) throws ServiceException { - try { - return next.getQueue(queuePath); - } - catch (WebApplicationException e) { - throw processCatch(new ServiceException(e)); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListQueuesResult listQueues() throws ServiceException { - try { - return next.listQueues(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public QueueInfo updateQueue(QueueInfo queueInfo) throws ServiceException { - try { - return next.updateQueue(queueInfo); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateTopicResult createTopic(TopicInfo topic) throws ServiceException { - try { - return next.createTopic(topic); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteTopic(String topicPath) throws ServiceException { - try { - next.deleteTopic(topicPath); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetTopicResult getTopic(String topicPath) throws ServiceException { - try { - return next.getTopic(topicPath); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListTopicsResult listTopics() throws ServiceException { - try { - return next.listTopics(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public TopicInfo updateTopic(TopicInfo topicInfo) throws ServiceException { - try { - return next.updateTopic(topicInfo); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateSubscriptionResult createSubscription(String topicPath, SubscriptionInfo subscription) - throws ServiceException { - try { - return next.createSubscription(topicPath, subscription); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteSubscription(String topicPath, String subscriptionName) throws ServiceException { - try { - next.deleteSubscription(topicPath, subscriptionName); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetSubscriptionResult getSubscription(String topicPath, String subscriptionName) throws ServiceException { - try { - return next.getSubscription(topicPath, subscriptionName); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListSubscriptionsResult listSubscriptions(String topicPath) throws ServiceException { - try { - return next.listSubscriptions(topicPath); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public SubscriptionInfo updateSubscription(String topicName, SubscriptionInfo subscriptionInfo) - throws ServiceException { - try { - return next.updateSubscription(topicName, subscriptionInfo); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public CreateRuleResult createRule(String topicPath, String subscriptionName, RuleInfo rule) - throws ServiceException { - try { - return next.createRule(topicPath, subscriptionName, rule); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteRule(String topicPath, String subscriptionName, String ruleName) throws ServiceException { - try { - next.deleteRule(topicPath, subscriptionName, ruleName); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetRuleResult getRule(String topicPath, String subscriptionName, String ruleName) throws ServiceException { - try { - return next.getRule(topicPath, subscriptionName, ruleName); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListRulesResult listRules(String topicPath, String subscriptionName) throws ServiceException { - try { - return next.listRules(topicPath, subscriptionName); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListQueuesResult listQueues(ListQueuesOptions options) throws ServiceException { - try { - return next.listQueues(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListTopicsResult listTopics(ListTopicsOptions options) throws ServiceException { - try { - return next.listTopics(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListSubscriptionsResult listSubscriptions(String topicName, ListSubscriptionsOptions options) - throws ServiceException { - try { - return next.listSubscriptions(topicName, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ListRulesResult listRules(String topicName, String subscriptionName, ListRulesOptions options) - throws ServiceException { - try { - return next.listRules(topicName, subscriptionName, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void sendMessage(String path, BrokeredMessage message) throws ServiceException { - try { - next.sendMessage(path, message); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ReceiveMessageResult receiveMessage(String path) throws ServiceException { - try { - return next.receiveMessage(path); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public ReceiveMessageResult receiveMessage(String path, ReceiveMessageOptions options) throws ServiceException { - try { - return next.receiveMessage(path, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void renewQueueLock(String queueName, String messageId, String lockToken) throws ServiceException { - try { - next.renewQueueLock(queueName, messageId, lockToken); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void renewSubscriptionLock(String topicName, String subscriptionName, String messageId, String lockToken) - throws ServiceException { - try { - next.renewSubscriptionLock(topicName, subscriptionName, messageId, lockToken); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusRestProxy.java deleted file mode 100644 index c27d177b5d025..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusRestProxy.java +++ /dev/null @@ -1,472 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import java.io.InputStream; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; - -import javax.inject.Inject; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.pipeline.ClientFilterAdapter; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.microsoft.windowsazure.services.serviceBus.ServiceBusContract; -import com.microsoft.windowsazure.services.serviceBus.models.AbstractListOptions; -import com.microsoft.windowsazure.services.serviceBus.models.BrokeredMessage; -import com.microsoft.windowsazure.services.serviceBus.models.CreateQueueResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateRuleResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateSubscriptionResult; -import com.microsoft.windowsazure.services.serviceBus.models.CreateTopicResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetQueueResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetRuleResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetSubscriptionResult; -import com.microsoft.windowsazure.services.serviceBus.models.GetTopicResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListQueuesOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListQueuesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListRulesOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListRulesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListSubscriptionsOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListSubscriptionsResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsResult; -import com.microsoft.windowsazure.services.serviceBus.models.QueueInfo; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveQueueMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveSubscriptionMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.RuleInfo; -import com.microsoft.windowsazure.services.serviceBus.models.SubscriptionInfo; -import com.microsoft.windowsazure.services.serviceBus.models.TopicInfo; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; - -public class ServiceBusRestProxy implements ServiceBusContract { - - private Client channel; - private final String uri; - private final BrokerPropertiesMapper mapper; - private final CustomPropertiesMapper customPropertiesMapper; - static Log log = LogFactory.getLog(ServiceBusContract.class); - - ServiceFilter[] filters; - - @Inject - public ServiceBusRestProxy(Client channel, WrapFilter authFilter, UserAgentFilter userAgentFilter, - ServiceBusConnectionSettings connectionSettings, BrokerPropertiesMapper mapper) { - - this.channel = channel; - this.filters = new ServiceFilter[0]; - this.uri = connectionSettings.getUri(); - this.mapper = mapper; - this.customPropertiesMapper = new CustomPropertiesMapper(); - channel.addFilter(authFilter); - channel.addFilter(userAgentFilter); - } - - public ServiceBusRestProxy(Client channel, ServiceFilter[] filters, String uri, BrokerPropertiesMapper mapper) { - this.channel = channel; - this.filters = filters; - this.uri = uri; - this.mapper = mapper; - this.customPropertiesMapper = new CustomPropertiesMapper(); - } - - @Override - public ServiceBusContract withFilter(ServiceFilter filter) { - ServiceFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1); - newFilters[filters.length] = filter; - return new ServiceBusRestProxy(channel, newFilters, uri, mapper); - } - - public Client getChannel() { - return channel; - } - - public void setChannel(Client channel) { - this.channel = channel; - } - - private WebResource getResource() { - WebResource resource = getChannel().resource(uri).queryParam("api-version", "2012-08"); - for (ServiceFilter filter : filters) { - resource.addFilter(new ClientFilterAdapter(filter)); - } - return resource; - } - - @Override - public void sendMessage(String path, BrokeredMessage message) { - Builder request = getResource().path(path).path("messages").getRequestBuilder(); - - if (message.getContentType() != null) - request = request.type(message.getContentType()); - - if (message.getBrokerProperties() != null) - request = request.header("BrokerProperties", mapper.toString(message.getBrokerProperties())); - - for (java.util.Map.Entry entry : message.getProperties().entrySet()) { - request.header(entry.getKey(), customPropertiesMapper.toString(entry.getValue())); - } - - request.post(message.getBody()); - } - - @Override - public void sendQueueMessage(String path, BrokeredMessage message) throws ServiceException { - sendMessage(path, message); - } - - @Override - public ReceiveQueueMessageResult receiveQueueMessage(String queueName) throws ServiceException { - return receiveQueueMessage(queueName, ReceiveMessageOptions.DEFAULT); - } - - @Override - public ReceiveQueueMessageResult receiveQueueMessage(String queuePath, ReceiveMessageOptions options) - throws ServiceException { - - WebResource resource = getResource().path(queuePath).path("messages").path("head"); - - BrokeredMessage message = receiveMessage(options, resource); - return new ReceiveQueueMessageResult(message); - } - - @Override - public ReceiveMessageResult receiveMessage(String path) throws ServiceException { - return receiveMessage(path, ReceiveMessageOptions.DEFAULT); - } - - @Override - public ReceiveMessageResult receiveMessage(String path, ReceiveMessageOptions options) throws ServiceException { - - WebResource resource = getResource().path(path).path("messages").path("head"); - - BrokeredMessage message = receiveMessage(options, resource); - return new ReceiveMessageResult(message); - } - - private BrokeredMessage receiveMessage(ReceiveMessageOptions options, WebResource resource) { - if (options.getTimeout() != null) { - resource = resource.queryParam("timeout", Integer.toString(options.getTimeout())); - } - - ClientResponse clientResult; - if (options.isReceiveAndDelete()) { - clientResult = resource.delete(ClientResponse.class); - } - else if (options.isPeekLock()) { - clientResult = resource.post(ClientResponse.class, ""); - } - else { - throw new RuntimeException("Unknown ReceiveMode"); - } - - if (clientResult.getStatus() == 204) { - return null; - } - - BrokerProperties brokerProperties; - if (clientResult.getHeaders().containsKey("BrokerProperties")) { - brokerProperties = mapper.fromString(clientResult.getHeaders().getFirst("BrokerProperties")); - } - else { - brokerProperties = new BrokerProperties(); - } - - String location = clientResult.getHeaders().getFirst("Location"); - if (location != null) { - brokerProperties.setLockLocation(location); - } - - BrokeredMessage message = new BrokeredMessage(brokerProperties); - - MediaType contentType = clientResult.getType(); - if (contentType != null) { - message.setContentType(contentType.toString()); - } - - Date date = clientResult.getResponseDate(); - if (date != null) { - message.setDate(date); - } - - InputStream body = clientResult.getEntityInputStream(); - if (body != null) { - message.setBody(body); - } - - for (String key : clientResult.getHeaders().keySet()) { - Object value = clientResult.getHeaders().getFirst(key); - try { - value = customPropertiesMapper.fromString(value.toString()); - message.setProperty(key, value); - } - catch (ParseException e) { - //log.warn("Unable to parse custom header", e); - } - catch (NumberFormatException e) { - //log.warn("Unable to parse custom header", e); - } - } - - return message; - } - - @Override - public void sendTopicMessage(String topicName, BrokeredMessage message) throws ServiceException { - sendMessage(topicName, message); - } - - @Override - public ReceiveSubscriptionMessageResult receiveSubscriptionMessage(String topicName, String subscriptionName) - throws ServiceException { - return receiveSubscriptionMessage(topicName, subscriptionName, ReceiveMessageOptions.DEFAULT); - } - - @Override - public ReceiveSubscriptionMessageResult receiveSubscriptionMessage(String topicName, String subscriptionName, - ReceiveMessageOptions options) throws ServiceException { - WebResource resource = getResource().path(topicName).path("subscriptions").path(subscriptionName) - .path("messages").path("head"); - - BrokeredMessage message = receiveMessage(options, resource); - return new ReceiveSubscriptionMessageResult(message); - } - - @Override - public void unlockMessage(BrokeredMessage message) throws ServiceException { - getChannel().resource(message.getLockLocation()).put(""); - } - - @Override - public void deleteMessage(BrokeredMessage message) throws ServiceException { - getChannel().resource(message.getLockLocation()).delete(); - } - - @Override - public CreateQueueResult createQueue(QueueInfo queueInfo) throws ServiceException { - Builder webResourceBuilder = getResource().path(queueInfo.getPath()).type( - "application/atom+xml;type=entry;charset=utf-8"); - if ((queueInfo.getForwardTo() != null) && !queueInfo.getForwardTo().isEmpty()) { - webResourceBuilder.header("ServiceBusSupplementaryAuthorization", queueInfo.getForwardTo()); - } - return new CreateQueueResult(webResourceBuilder.put(QueueInfo.class, queueInfo)); - } - - @Override - public void deleteQueue(String queuePath) throws ServiceException { - getResource().path(queuePath).delete(); - } - - @Override - public GetQueueResult getQueue(String queuePath) throws ServiceException { - return new GetQueueResult(getResource().path(queuePath).get(QueueInfo.class)); - } - - @Override - public ListQueuesResult listQueues(ListQueuesOptions options) throws ServiceException { - Feed feed = listOptions(options, getResource().path("$Resources/Queues")).get(Feed.class); - ArrayList queues = new ArrayList(); - for (Entry entry : feed.getEntries()) { - queues.add(new QueueInfo(entry)); - } - ListQueuesResult result = new ListQueuesResult(); - result.setItems(queues); - return result; - } - - @Override - public QueueInfo updateQueue(QueueInfo queueInfo) throws ServiceException { - Builder webResourceBuilder = getResource().path(queueInfo.getPath()) - .type("application/atom+xml;type=entry;charset=utf-8").header("If-Match", "*"); - if ((queueInfo.getForwardTo() != null) && !queueInfo.getForwardTo().isEmpty()) { - webResourceBuilder.header("ServiceBusSupplementaryAuthorization", queueInfo.getForwardTo()); - } - return webResourceBuilder.put(QueueInfo.class, queueInfo); - } - - private WebResource listOptions(AbstractListOptions options, WebResource path) { - if (options.getTop() != null) { - path = path.queryParam("$top", options.getTop().toString()); - } - if (options.getSkip() != null) { - path = path.queryParam("$skip", options.getSkip().toString()); - } - if (options.getFilter() != null) { - path = path.queryParam("$filter", options.getFilter()); - } - return path; - } - - @Override - public CreateTopicResult createTopic(TopicInfo entry) throws ServiceException { - return new CreateTopicResult(getResource().path(entry.getPath()) - .type("application/atom+xml;type=entry;charset=utf-8").put(TopicInfo.class, entry)); - } - - @Override - public void deleteTopic(String TopicPath) throws ServiceException { - getResource().path(TopicPath).delete(); - } - - @Override - public GetTopicResult getTopic(String TopicPath) throws ServiceException { - return new GetTopicResult(getResource().path(TopicPath).get(TopicInfo.class)); - } - - @Override - public ListTopicsResult listTopics(ListTopicsOptions options) throws ServiceException { - Feed feed = listOptions(options, getResource().path("$Resources/Topics")).get(Feed.class); - ArrayList Topics = new ArrayList(); - for (Entry entry : feed.getEntries()) { - Topics.add(new TopicInfo(entry)); - } - ListTopicsResult result = new ListTopicsResult(); - result.setItems(Topics); - return result; - } - - @Override - public TopicInfo updateTopic(TopicInfo topicInfo) throws ServiceException { - return getResource().path(topicInfo.getPath()).type("application/atom+xml;type=entry;charset=utf-8") - .header("If-Match", "*").put(TopicInfo.class, topicInfo); - } - - @Override - public CreateSubscriptionResult createSubscription(String topicPath, SubscriptionInfo subscriptionInfo) { - Builder webResourceBuilder = getResource().path(topicPath).path("subscriptions") - .path(subscriptionInfo.getName()).type("application/atom+xml;type=entry;charset=utf-8"); - if ((subscriptionInfo.getForwardTo() != null) && (!subscriptionInfo.getForwardTo().isEmpty())) { - webResourceBuilder.header("ServiceBusSupplementaryAuthorization", subscriptionInfo.getForwardTo()); - - } - return new CreateSubscriptionResult(webResourceBuilder.put(SubscriptionInfo.class, subscriptionInfo)); - } - - @Override - public void deleteSubscription(String topicPath, String subscriptionName) { - getResource().path(topicPath).path("subscriptions").path(subscriptionName).delete(); - } - - @Override - public GetSubscriptionResult getSubscription(String topicPath, String subscriptionName) { - return new GetSubscriptionResult(getResource().path(topicPath).path("subscriptions").path(subscriptionName) - .get(SubscriptionInfo.class)); - } - - @Override - public ListSubscriptionsResult listSubscriptions(String topicPath, ListSubscriptionsOptions options) { - Feed feed = listOptions(options, getResource().path(topicPath).path("subscriptions")).get(Feed.class); - ArrayList list = new ArrayList(); - for (Entry entry : feed.getEntries()) { - list.add(new SubscriptionInfo(entry)); - } - ListSubscriptionsResult result = new ListSubscriptionsResult(); - result.setItems(list); - return result; - } - - @Override - public SubscriptionInfo updateSubscription(String topicName, SubscriptionInfo subscriptionInfo) - throws ServiceException { - Builder webResourceBuilder = getResource().path(topicName).path("subscriptions") - .path(subscriptionInfo.getName()).type("application/atom+xml;type=entry;charset=utf-8") - .header("If-Match", "*"); - if ((subscriptionInfo.getForwardTo() != null) && !subscriptionInfo.getForwardTo().isEmpty()) { - webResourceBuilder.header("ServiceBusSupplementaryAuthorization", subscriptionInfo.getForwardTo()); - } - return webResourceBuilder.put(SubscriptionInfo.class, subscriptionInfo); - } - - @Override - public CreateRuleResult createRule(String topicPath, String subscriptionName, RuleInfo rule) { - return new CreateRuleResult(getResource().path(topicPath).path("subscriptions").path(subscriptionName) - .path("rules").path(rule.getName()).type("application/atom+xml;type=entry;charset=utf-8") - .put(RuleInfo.class, rule)); - } - - @Override - public void deleteRule(String topicPath, String subscriptionName, String ruleName) { - getResource().path(topicPath).path("subscriptions").path(subscriptionName).path("rules").path(ruleName) - .delete(); - } - - @Override - public GetRuleResult getRule(String topicPath, String subscriptionName, String ruleName) { - return new GetRuleResult(getResource().path(topicPath).path("subscriptions").path(subscriptionName) - .path("rules").path(ruleName).get(RuleInfo.class)); - } - - @Override - public ListRulesResult listRules(String topicPath, String subscriptionName, ListRulesOptions options) { - Feed feed = listOptions(options, - getResource().path(topicPath).path("subscriptions").path(subscriptionName).path("rules")).get( - Feed.class); - ArrayList list = new ArrayList(); - for (Entry entry : feed.getEntries()) { - list.add(new RuleInfo(entry)); - } - ListRulesResult result = new ListRulesResult(); - result.setItems(list); - return result; - } - - @Override - public ListQueuesResult listQueues() throws ServiceException { - return listQueues(ListQueuesOptions.DEFAULT); - } - - @Override - public ListTopicsResult listTopics() throws ServiceException { - return listTopics(ListTopicsOptions.DEFAULT); - } - - @Override - public ListSubscriptionsResult listSubscriptions(String topicName) throws ServiceException { - return listSubscriptions(topicName, ListSubscriptionsOptions.DEFAULT); - } - - @Override - public ListRulesResult listRules(String topicName, String subscriptionName) throws ServiceException { - return listRules(topicName, subscriptionName, ListRulesOptions.DEFAULT); - } - - @Override - public void renewQueueLock(String queueName, String messageId, String lockToken) throws ServiceException { - ClientResponse clientResponse = getResource().path(queueName).path("messages").path(messageId).path(lockToken) - .post(ClientResponse.class, ""); - PipelineHelpers.ThrowIfNotSuccess(clientResponse); - } - - @Override - public void renewSubscriptionLock(String topicName, String subscriptionName, String messageId, String lockToken) - throws ServiceException { - ClientResponse clientResponse = getResource().path(topicName).path("Subscriptions").path(subscriptionName) - .path("messages").path(messageId).path(lockToken).post(ClientResponse.class, ""); - PipelineHelpers.ThrowIfNotSuccess(clientResponse); - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapRestProxy.java deleted file mode 100644 index 3de13aea1d265..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapRestProxy.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import javax.inject.Inject; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.representation.Form; - -public class WrapRestProxy implements WrapContract { - Client channel; - - static Log log = LogFactory.getLog(WrapContract.class); - - @Inject - public WrapRestProxy(Client channel, UserAgentFilter userAgentFilter) { - this.channel = channel; - this.channel.addFilter(userAgentFilter); - } - - @Override - public WrapAccessTokenResult wrapAccessToken(String uri, String name, String password, String scope) - throws ServiceException { - Form requestForm = new Form(); - requestForm.add("wrap_name", name); - requestForm.add("wrap_password", password); - requestForm.add("wrap_scope", scope); - - Form responseForm; - try { - responseForm = channel.resource(uri).accept(MediaType.APPLICATION_FORM_URLENCODED) - .type(MediaType.APPLICATION_FORM_URLENCODED).post(Form.class, requestForm); - } - catch (UniformInterfaceException e) { - log.warn("WRAP server returned error acquiring access_token", e); - throw ServiceExceptionFactory.process("WRAP", new ServiceException( - "WRAP server returned error acquiring access_token", e)); - } - - WrapAccessTokenResult response = new WrapAccessTokenResult(); - - response.setAccessToken(responseForm.getFirst("wrap_access_token")); - - String expiresIn = responseForm.getFirst("wrap_access_token_expires_in"); - response.setExpiresIn(Long.parseLong(expiresIn)); - - return response; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListQueuesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListQueuesOptions.java deleted file mode 100644 index 71e71a3ff767b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListQueuesOptions.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.models; - -public class ListQueuesOptions extends AbstractListOptions { - public static final ListQueuesOptions DEFAULT = new ListQueuesOptions(); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListQueuesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListQueuesResult.java deleted file mode 100644 index b7c72147b1f15..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListQueuesResult.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.models; - -import java.util.List; - -/** - * Represents the result of a listQueues operation. - */ -public class ListQueuesResult { - - private List items; - - /** - * Returns the items in the result list. - * - * @return A List of {@link QueueInfo} objects that represent the - * items in the result list. - */ - public List getItems() { - return items; - } - - /** - * Specfies the items in the result list. - * - * @param items - * A List object that contains the {@link QueueInfo} objects assigned as the value of the - * result. - */ - public void setItems(List items) { - this.items = items; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/EdmValueConverter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/EdmValueConverter.java deleted file mode 100644 index 0f96ce3852eb5..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/EdmValueConverter.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table; - -import com.microsoft.windowsazure.services.table.models.EdmType; - -/** - * An interface for EDM type serialization to Windows Azure Storage service and deserialization to native Java - * types. - */ -public interface EdmValueConverter { - /** - * Creates a serialized string in EDM type format from the native Java value parameter. - *

- * Supported edmType parameter values are defined as constants in the {@link EdmType} class. - * - * @param edmType - * A {@link String} containing the EDM data type to serialize the value parameter as. - * @param value - * An {@link Object} reference to the native Java value to serialize. - * @return - * A {@link String} containing the serialized data to send to the Windows Azure Storage service. - */ - String serialize(String edmType, Object value); - - /** - * Creates an object of the correct native Java type from the serialized data in EDM type format. - *

- * Supported edmType parameter values are defined as constants in the {@link EdmType} class. - * - * @param edmType - * A {@link String} containing the EDM data type of the value parameter to deserialize. - * @param value - * A {@link String} containing the Windows Azure Storage service data to deserialize. - * @return - * An {@link Object} reference to the deserialized native Java value. This is an object of the - * correct native Java type for the EDM data type, passed as an {@link Object}. - */ - Object deserialize(String edmType, String value); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/Exports.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/Exports.java deleted file mode 100644 index 6be3e3c25264c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/Exports.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.table.implementation.AtomReaderWriter; -import com.microsoft.windowsazure.services.table.implementation.DefaultEdmValueConverter; -import com.microsoft.windowsazure.services.table.implementation.DefaultXMLStreamFactory; -import com.microsoft.windowsazure.services.table.implementation.HttpReaderWriter; -import com.microsoft.windowsazure.services.table.implementation.MimeReaderWriter; -import com.microsoft.windowsazure.services.table.implementation.SharedKeyFilter; -import com.microsoft.windowsazure.services.table.implementation.SharedKeyLiteFilter; -import com.microsoft.windowsazure.services.table.implementation.TableExceptionProcessor; -import com.microsoft.windowsazure.services.table.implementation.TableRestProxy; -import com.microsoft.windowsazure.services.table.implementation.XMLStreamFactory; - -public class Exports implements Builder.Exports { - @Override - public void register(Builder.Registry registry) { - registry.add(TableContract.class, TableExceptionProcessor.class); - registry.add(TableExceptionProcessor.class); - registry.add(TableRestProxy.class); - registry.add(SharedKeyLiteFilter.class); - registry.add(SharedKeyFilter.class); - registry.add(XMLStreamFactory.class, DefaultXMLStreamFactory.class); - registry.add(AtomReaderWriter.class); - registry.add(MimeReaderWriter.class); - registry.add(HttpReaderWriter.class); - registry.add(EdmValueConverter.class, DefaultEdmValueConverter.class); - registry.add(UserAgentFilter.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableConfiguration.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableConfiguration.java deleted file mode 100644 index b516e80d4128f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableConfiguration.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table; - -/** - * This class contains static strings used to identify parts of a service configuration instance associated with the - * Windows Azure Table service. - *

- * These values must not be altered. - */ -public class TableConfiguration { - /** - * The Table configuration account name constant. This String value is used as a key in the - * configuration file, to identify the value for the DNS prefix name for the storage account. - */ - public final static String ACCOUNT_NAME = "table.accountName"; - - /** - * The Table configuration account key constant. This String value is used as a key in the - * configuration file, to identify the value for the storage service account key. - */ - public final static String ACCOUNT_KEY = "table.accountKey"; - - /** - * The Table configuration URI constant. This String value is used as a key in the - * configuration file, to identify the URI value for the Table service REST API address for the - * storage account. - */ - public final static String URI = "table.uri"; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableContract.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableContract.java deleted file mode 100644 index e752d667d0346..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableContract.java +++ /dev/null @@ -1,532 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table; - -import com.microsoft.windowsazure.services.core.FilterableService; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.table.models.BatchOperations; -import com.microsoft.windowsazure.services.table.models.BatchResult; -import com.microsoft.windowsazure.services.table.models.DeleteEntityOptions; -import com.microsoft.windowsazure.services.table.models.Entity; -import com.microsoft.windowsazure.services.table.models.GetEntityResult; -import com.microsoft.windowsazure.services.table.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.table.models.GetTableResult; -import com.microsoft.windowsazure.services.table.models.InsertEntityResult; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesOptions; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesResult; -import com.microsoft.windowsazure.services.table.models.QueryTablesOptions; -import com.microsoft.windowsazure.services.table.models.QueryTablesResult; -import com.microsoft.windowsazure.services.table.models.ServiceProperties; -import com.microsoft.windowsazure.services.table.models.TableServiceOptions; -import com.microsoft.windowsazure.services.table.models.UpdateEntityResult; - -/** - * Defines the methods available on the Windows Azure Table storage service. Construct an object instance implementing - * TableContract with one of the static create methods on {@link TableService}. These methods - * associate a Configuration with the implementation, so the methods on the instance of - * TableContract all work with a particular storage account. - */ -public interface TableContract extends FilterableService { - /** - * Gets the properties of a storage account’s Table service, including Windows Azure Storage Analytics. - * - * @return - * A {@link GetServicePropertiesResult} reference to the Table service properties. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetServicePropertiesResult getServiceProperties() throws ServiceException; - - /** - * Gets the properties of a storage account’s Table service, including Windows Azure Storage Analytics, using the - * specified options. - *

- * Use the {@link TableServiceOptions options} parameter to specify options for the request. - * - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * A {@link GetServicePropertiesResult} reference to the Table service properties. - * - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetServicePropertiesResult getServiceProperties(TableServiceOptions options) throws ServiceException; - - /** - * Sets the properties of a storage account’s Table service, including Windows Azure Storage Analytics. - * - * @param serviceProperties - * A {@link ServiceProperties} instance containing the Table service properties to set. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException; - - /** - * Sets the properties of a storage account’s Table service, including Windows Azure Storage Analytics, using the - * specified options. - *

- * Use the {@link TableServiceOptions options} parameter to specify options for the request. - * - * @param serviceProperties - * A {@link ServiceProperties} instance containing the Table service properties to set. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void setServiceProperties(ServiceProperties serviceProperties, TableServiceOptions options) throws ServiceException; - - /** - * Creates a table with the specified name in the storage account. - *

- * Table names must be unique within a storage account, and must conform to these rules: - *

    - *
  • Table names may contain only alphanumeric characters.
  • - *
  • Table names cannot begin with a numeric character.
  • - *
  • Table names are case-insensitive.
  • - *
  • Table names must be from 3 to 63 characters long.
  • - *
- *

- * These rules are also described by the regular expression "^[A-Za-z][A-Za-z0-9]{2,62}$". - *

- * Table names preserve the case with which they were created, but are case-insensitive when used. - * - * @param table - * A {@link String} containing the name of the table to create. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void createTable(String table) throws ServiceException; - - /** - * Creates a table with the specified name in the storage account, using the specified options. - *

- * Use the {@link TableServiceOptions options} parameter to specify options for the request. - *

- * Table names must be unique within a storage account, and must conform to these rules: - *

    - *
  • Table names may contain only alphanumeric characters.
  • - *
  • Table names cannot begin with a numeric character.
  • - *
  • Table names are case-insensitive.
  • - *
  • Table names must be from 3 to 63 characters long.
  • - *
- *

- * These rules are also described by the regular expression "^[A-Za-z][A-Za-z0-9]{2,62}$". - *

- * Table names preserve the case with which they were created, but are case-insensitive when used. - * - * @param table - * A {@link String} containing the name of the table to create. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void createTable(String table, TableServiceOptions options) throws ServiceException; - - /** - * Deletes the specified table and any data it contains from the storage account. - *

- * When a table is successfully deleted, it is immediately marked for deletion and is no longer accessible to - * clients. The table is later removed from the Table service during garbage collection. - *

- * Note that deleting a table is likely to take at least 40 seconds to complete. If an operation is attempted - * against the table while it is being deleted, the service returns status code 409 (Conflict), with additional - * error information indicating that the table is being deleted. This causes a {@link ServiceException} to be thrown - * in the context of the client request. - * - * @param table - * A {@link String} containing the name of the table to delete. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteTable(String table) throws ServiceException; - - /** - * Deletes the specified table and any data it contains from the storage account, using the specified options. - *

- * Use the {@link TableServiceOptions options} parameter to specify options for the request. - *

- * When a table is successfully deleted, it is immediately marked for deletion and is no longer accessible to - * clients. The table is later removed from the Table service during garbage collection. - *

- * Note that deleting a table is likely to take at least 40 seconds to complete. If an operation is attempted - * against the table while it is being deleted, the service returns status code 409 (Conflict), with additional - * error information indicating that the table is being deleted. This causes a {@link ServiceException} to be thrown - * in the context of the client request. - * - * @param table - * A {@link String} containing the name of the table to delete. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteTable(String table, TableServiceOptions options) throws ServiceException; - - /** - * Gets the specified table entry from the list of tables in the storage account. - * - * @param table - * A {@link String} containing the name of the table to retrieve. - * @return - * A {@link GetTableResult} instance containing the table entry returned. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetTableResult getTable(String table) throws ServiceException; - - /** - * Gets the specified table entry from the list of tables in the storage account, using the specified options. - *

- * Use the {@link TableServiceOptions options} parameter to specify options for the request. - * - * @param table - * A {@link String} containing the name of the table to retrieve. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * A {@link GetTableResult} instance containing the table entry returned. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - GetTableResult getTable(String table, TableServiceOptions options) throws ServiceException; - - /** - * Gets a list of tables in the storage account. - * - * @return - * A {@link QueryTablesResult} instance containing the list of table entries returned. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - QueryTablesResult queryTables() throws ServiceException; - - /** - * Gets a list of tables in the storage account, using the specified options. - *

- * Use the {@link QueryTablesOptions options} parameter to specify options for the request, such as a filter to - * limit results to tables with certain properties, the next table name continuation token to use to resume the - * query tables request from, and a prefix string to match table names with. - * - * @param options - * A {@link QueryTablesOptions} instance containing options for the request. - * @return - * A {@link QueryTablesResult} instance containing the list of table entries returned. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - QueryTablesResult queryTables(QueryTablesOptions options) throws ServiceException; - - /** - * Inserts an entity into a table. - * - * @param table - * A {@link String} containing the name of the table to insert the entity into. - * @param entity - * An {@link Entity} instance containing the entity data to insert in the table. - * @return - * An {@link InsertEntityResult} containing the entity inserted in the table. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - InsertEntityResult insertEntity(String table, Entity entity) throws ServiceException; - - /** - * Inserts an entity into a table, using the specified options. - * - * @param table - * A {@link String} containing the name of the table to insert the entity into. - * @param entity - * An {@link Entity} instance containing the entity data to insert in the table. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * An {@link InsertEntityResult} containing the entity inserted in the table. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - InsertEntityResult insertEntity(String table, Entity entity, TableServiceOptions options) throws ServiceException; - - /** - * Updates an entity in a table. The entity data is completely replaced with the data in the entity - * parameter. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to update. - * @param entity - * An {@link Entity} instance containing the entity to update in the table. - * @return - * An {@link UpdateEntityResult} containing the ETag of the updated entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult updateEntity(String table, Entity entity) throws ServiceException; - - /** - * Updates an entity in a table, using the specified options. The entity data is completely replaced with the data - * in the entity parameter. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to update. - * @param entity - * An {@link Entity} instance containing the entity to update in the table. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * An {@link UpdateEntityResult} containing the ETag of the updated entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult updateEntity(String table, Entity entity, TableServiceOptions options) throws ServiceException; - - /** - * Merges entity data into an existing entity in a table. Property values in the existing entity are overwritten - * with matching properties in the entity parameter. Properties in the entity parameter that are - * not present in the existing entity are added to it. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to merge. - * @param entity - * An {@link Entity} instance containing the entity data to merge into the existing entity. - * @return - * An {@link UpdateEntityResult} containing the ETag of the modified entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult mergeEntity(String table, Entity entity) throws ServiceException; - - /** - * Merges entity data into an existing entity in a table, using the specified options. Property values in the - * existing entity are overwritten with matching properties in the entity parameter. Properties in the - * entity parameter that are not present in the existing entity are added to it. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to merge. - * @param entity - * An {@link Entity} instance containing the entity data to merge into the existing entity. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * An {@link UpdateEntityResult} containing the ETag of the modified entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult mergeEntity(String table, Entity entity, TableServiceOptions options) throws ServiceException; - - /** - * Inserts or replaces an entity in a table. If the table does not contain an entity with a matching primary key, it - * is inserted. Otherwise, the entity data is completely replaced with the data in the entity parameter. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to insert or replace. - * @param entity - * An {@link Entity} instance containing the entity data to insert or replace in the table. - * @return - * An {@link UpdateEntityResult} containing the ETag of the modified entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult insertOrReplaceEntity(String table, Entity entity) throws ServiceException; - - /** - * Inserts or replaces an entity in a table, using the specified options. If the table does not contain an entity - * with a matching primary key, it is inserted. Otherwise, the entity data is completely replaced with the data in - * the entity parameter. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to insert or replace. - * @param entity - * An {@link Entity} instance containing the entity data to insert or replace in the table. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * An {@link UpdateEntityResult} containing the ETag of the modified entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult insertOrReplaceEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException; - - /** - * Inserts or merges an entity in a table. If the table does not contain an entity with a matching primary key, it - * is inserted. Otherwise, property values in the existing entity are overwritten with matching properties in the - * entity parameter. Properties in the entity parameter that are not present in the existing - * entity are added to it. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to insert or merge. - * @param entity - * An {@link Entity} instance containing the entity data to insert or merge in the table. - * @return - * An {@link UpdateEntityResult} containing the ETag of the modified entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult insertOrMergeEntity(String table, Entity entity) throws ServiceException; - - /** - * Inserts or merges an entity in a table, using the specified options. If the table does not contain an entity with - * a matching primary key, it is inserted. Otherwise, property values in the existing entity are overwritten with - * matching properties in the entity parameter. Properties in the entity parameter that are not - * present in the existing entity are added to it. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to insert or merge. - * @param entity - * An {@link Entity} instance containing the entity data to insert or merge in the table. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * An {@link UpdateEntityResult} containing the ETag of the modified entity. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - UpdateEntityResult insertOrMergeEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException; - - /** - * Deletes an entity from a table. - * - * @param table - * A {@link String} containing the name of the table to delete the entity from. - * @param partitionKey - * A {@link String} containing the partition key of the entity to delete. - * @param rowKey - * A {@link String} containing the row key of the entity to delete. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteEntity(String table, String partitionKey, String rowKey) throws ServiceException; - - /** - * Deletes an entity from a table, using the specified options. - *

- * Use the {@link DeleteEntityOptions options} parameter to specify an ETag value that must match to delete the - * entity. - * - * @param table - * A {@link String} containing the name of the table to delete the entity from. - * @param partitionKey - * A {@link String} containing the partition key of the entity to delete. - * @param rowKey - * A {@link String} containing the row key of the entity to delete. - * @param options - * A {@link DeleteEntityOptions} instance containing the ETag to match with the entity to delete. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - void deleteEntity(String table, String partitionKey, String rowKey, DeleteEntityOptions options) - throws ServiceException; - - /** - * Gets the specified entity. - * - * @param table - * A {@link String} containing the name of the table to get the entity from. - * @param partitionKey - * A {@link String} containing the partition key of the entity to get. - * @param rowKey - * A {@link String} containing the row key of the entity to get. - * @return - * A {@link GetEntityResult} instance containing the entity data returned in the server response. - * @throws ServiceException - */ - GetEntityResult getEntity(String table, String partitionKey, String rowKey) throws ServiceException; - - /** - * Gets the specified entity, using the specified options. - * - * @param table - * A {@link String} containing the name of the table to get the entity from. - * @param partitionKey - * A {@link String} containing the partition key of the entity to get. - * @param rowKey - * A {@link String} containing the row key of the entity to get. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * A {@link GetEntityResult} instance containing the entity data returned in the server response. - * @throws ServiceException - */ - GetEntityResult getEntity(String table, String partitionKey, String rowKey, TableServiceOptions options) - throws ServiceException; - - /** - * Lists the entities in a table. - * - * @param table - * A {@link String} containing the name of the table to retrieve the list of entities from. - * @return - * A {@link QueryEntitiesResult} instance containing the server response to the batch request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - QueryEntitiesResult queryEntities(String table) throws ServiceException; - - /** - * Lists the entities in a table that match the specified options. - *

- * Use the {@link QueryEntitiesOptions options} parameter to specify the next partition key and next row key - * continuation tokens to use to resume the query entities request from, a collection of the property names to - * include in the entities returned in the server response, a filter to limit results to entities with certain - * property values, and a top count to limit the response to that number of the first matching results. - * - * @param table - * A {@link String} containing the name of the table to retrieve the list of entities from. - * @param options - * A {@link QueryEntitiesOptions} instance containing options for the request. - * @return - * A {@link QueryEntitiesResult} instance containing the server response to the batch request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - QueryEntitiesResult queryEntities(String table, QueryEntitiesOptions options) throws ServiceException; - - /** - * Submits multiple entity operations in the same table and partition group as a single transaction. Multiple insert - * entity, update entity, merge entity, delete entity, insert or replace entity, and insert or merge entity - * operations are supported within a single transaction. - * - * @param operations - * A {@link BatchOperations} instance containing the list of operations to send as a single transaction. - * @return - * A {@link BatchResult} instance containing the server response to the batch request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - BatchResult batch(BatchOperations operations) throws ServiceException; - - /** - * Submits multiple entity operations in the same table and partition group as a single transaction, using the - * specified options. Multiple insert entity, update entity, merge entity, delete entity, insert or replace entity, - * and insert or merge entity operations are supported within a single transaction. - *

- * Use the {@link TableServiceOptions options} parameter to specify options for the request. - * - * @param operations - * A {@link BatchOperations} instance containing the list of operations to send as a single transaction. - * @param options - * A {@link TableServiceOptions} instance containing options for the request. - * @return - * A {@link BatchResult} instance containing the server response to the batch request. - * @throws ServiceException - * if an error occurs accessing the storage service. - */ - BatchResult batch(BatchOperations operations, TableServiceOptions options) throws ServiceException; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableService.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableService.java deleted file mode 100644 index 71c95a11ea971..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/TableService.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table; - -import com.microsoft.windowsazure.services.core.Configuration; - -/** - * A class for static factory methods that return instances implementing {@link TableContract}. - */ -public class TableService { - private TableService() { - } - - /** - * A static factory method that returns an instance implementing {@link TableContract} using default values for - * initializing a {@link Configuration} instance. Note that the returned interface will not work unless storage - * account credentials have been added to the "META-INF/com.microsoft.windowsazure.properties" resource file. - * - * @return - * An instance implementing {@link TableContract} for interacting with the Table service. - */ - public static TableContract create() { - return create(null, Configuration.getInstance()); - } - - /** - * A static factory method that returns an instance implementing {@link TableContract} using the specified - * {@link Configuration} instance. The {@link Configuration} instance must have storage account information and - * credentials set before this method is called for the returned interface to work. - * - * @param config - * A {@link Configuration} instance configured with storage account information and credentials. - * - * @return - * An instance implementing {@link TableContract} for interacting with the Table service. - */ - public static TableContract create(Configuration config) { - return create(null, config); - } - - /** - * A static factory method that returns an instance implementing {@link TableContract} using default values for - * initializing a {@link Configuration} instance, and using the specified profile prefix for service settings. Note - * that the returned interface will not work unless storage account settings and credentials have been added to the - * "META-INF/com.microsoft.windowsazure.properties" resource file with the specified profile prefix. - * - * @param profile - * A string prefix for the account name and credentials settings in the {@link Configuration} instance. - * @return - * An instance implementing {@link TableContract} for interacting with the Table service. - */ - public static TableContract create(String profile) { - return create(profile, Configuration.getInstance()); - } - - /** - * A static factory method that returns an instance implementing {@link TableContract} using the specified - * {@link Configuration} instance and profile prefix for service settings. The {@link Configuration} instance must - * have storage account information and credentials set with the specified profile prefix before this method is - * called for the returned interface to work. - * - * @param profile - * A string prefix for the account name and credentials settings in the {@link Configuration} instance. - * @param config - * A {@link Configuration} instance configured with storage account information and credentials. - * - * @return - * An instance implementing {@link TableContract} for interacting with the Table service. - */ - public static TableContract create(String profile, Configuration config) { - return config.create(profile, TableContract.class); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/AtomPubParser.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/AtomPubParser.java deleted file mode 100644 index 8ea633c39a869..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/AtomPubParser.java +++ /dev/null @@ -1,562 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.InputStream; -import java.io.OutputStream; -import java.text.ParseException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map.Entry; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamWriter; - -import org.apache.commons.lang3.StringEscapeUtils; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Reserved for internal use. A class used to read and write Table entities in OData AtomPub format requests and - * responses. - *

- * For more information about OData, see the Open Data Protocol website. For more - * information about the AtomPub format used in OData, see OData Protocol Atom Format. - */ -class AtomPubParser { - /** - * Reserved for internal use. A static factory method to construct an XMLStreamWriter instance based on - * the specified OutputStream. - * - * @param outStream - * The OutputStream instance to create an XMLStreamWriter on. - * @return - * An XMLStreamWriter instance based on the specified OutputStream. - * @throws XMLStreamException - * if an error occurs while creating the stream. - */ - protected static XMLStreamWriter generateTableWriter(final OutputStream outStream) throws XMLStreamException { - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - return xmlOutFactoryInst.createXMLStreamWriter(outStream, "UTF-8"); - } - - /** - * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the - * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type - * projected using the specified resolver. - * - * @param xmlr - * An XMLStreamReader on the input stream. - * @param clazzType - * The class type T implementing {@link TableEntity} for the entity returned. Set to - * null to ignore the returned entity and copy only response properties into the - * {@link TableResult} object. - * @param resolver - * An {@link EntityResolver} instance to project the entity into an instance of type R. Set - * to null to return the entity as an instance of the class type T. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * @return - * A {@link TableResult} containing the parsed entity result of the operation. - * - * @throws XMLStreamException - * if an error occurs while accessing the stream. - * @throws ParseException - * if an error occurs while parsing the stream. - * @throws InstantiationException - * if an error occurs while constructing the result. - * @throws IllegalAccessException - * if an error occurs in reflection while parsing the result. - * @throws StorageException - * if a storage service error occurs. - */ - protected static TableResult parseEntity(final XMLStreamReader xmlr, - final Class clazzType, final EntityResolver resolver, final OperationContext opContext) - throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException, StorageException { - int eventType = xmlr.getEventType(); - final TableResult res = new TableResult(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY); - - res.setEtag(StringEscapeUtils.unescapeHtml4(xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, - ODataConstants.ETAG))); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.CHARACTERS) { - xmlr.getText(); - continue; - } - - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ID)) { - res.setId(Utility.readElementFromXMLReader(xmlr, ODataConstants.ID)); - } - else if (name.equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) { - // Do read properties - if (resolver == null && clazzType == null) { - return res; - } - else { - res.setProperties(readProperties(xmlr, opContext)); - break; - } - } - } - } - - // Move to end Content - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.CHARACTERS) { - eventType = xmlr.next(); - } - xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT); - - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.CHARACTERS) { - eventType = xmlr.next(); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY); - - String rowKey = null; - String partitionKey = null; - Date timestamp = null; - - // Remove core properties from map and set individually - EntityProperty tempProp = res.getProperties().get(TableConstants.PARTITION_KEY); - if (tempProp != null) { - res.getProperties().remove(TableConstants.PARTITION_KEY); - partitionKey = tempProp.getValueAsString(); - } - - tempProp = res.getProperties().get(TableConstants.ROW_KEY); - if (tempProp != null) { - res.getProperties().remove(TableConstants.ROW_KEY); - rowKey = tempProp.getValueAsString(); - } - - tempProp = res.getProperties().get(TableConstants.TIMESTAMP); - if (tempProp != null) { - res.getProperties().remove(TableConstants.TIMESTAMP); - timestamp = tempProp.getValueAsDate(); - } - - if (resolver != null) { - // Call resolver - res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag())); - } - else if (clazzType != null) { - // Generate new entity and return - final T entity = clazzType.newInstance(); - entity.setEtag(res.getEtag()); - - entity.setPartitionKey(partitionKey); - entity.setRowKey(rowKey); - entity.setTimestamp(timestamp); - - entity.readEntity(res.getProperties(), opContext); - - res.setResult(entity); - } - - return res; - } - - /** - * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the - * specified input stream using the specified class type and optionally projects each entity result with the - * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. . - * - * @param inStream - * The InputStream to read the data to parse from. - * @param clazzType - * The class type T implementing {@link TableEntity} for the entities returned. Set to - * null to ignore the returned entities and copy only response properties into the - * {@link TableResult} objects. - * @param resolver - * An {@link EntityResolver} instance to project the entities into instances of type R. Set - * to null to return the entities as instances of the class type T. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * @return - * An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation - * response. - * - * @throws XMLStreamException - * if an error occurs while accessing the stream. - * @throws ParseException - * if an error occurs while parsing the stream. - * @throws InstantiationException - * if an error occurs while constructing the result. - * @throws IllegalAccessException - * if an error occurs in reflection while parsing the result. - * @throws StorageException - * if a storage service error occurs. - */ - @SuppressWarnings("unchecked") - protected static ODataPayload parseResponse(final InputStream inStream, - final Class clazzType, final EntityResolver resolver, final OperationContext opContext) - throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException, StorageException { - ODataPayload corePayload = null; - ODataPayload resolvedPayload = null; - ODataPayload commonPayload = null; - - if (resolver != null) { - resolvedPayload = new ODataPayload(); - commonPayload = resolvedPayload; - } - else { - corePayload = new ODataPayload(); - commonPayload = corePayload; - } - - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream); - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - eventType = xmlr.next(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.FEED); - // skip feed chars - eventType = xmlr.next(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.CHARACTERS) { - xmlr.getText(); - continue; - } - - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT) { - if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ENTRY)) { - final TableResult res = parseEntity(xmlr, clazzType, resolver, opContext); - if (corePayload != null) { - corePayload.tableResults.add(res); - } - - if (resolver != null) { - resolvedPayload.results.add((R) res.getResult()); - } - else { - corePayload.results.add((T) res.getResult()); - } - } - } - else if (eventType == XMLStreamConstants.END_ELEMENT - && name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.FEED)) { - break; - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.FEED); - return commonPayload; - } - - /** - * Reserved for internal use. Parses the operation response as an entity. Reads entity data from the specified - * XMLStreamReader using the specified class type and optionally projects the entity result with the - * specified resolver into a {@link TableResult} object. - * - * @param xmlr - * The XMLStreamReader to read the data to parse from. - * @param httpStatusCode - * The HTTP status code returned with the operation response. - * @param clazzType - * The class type T implementing {@link TableEntity} for the entity returned. Set to - * null to ignore the returned entity and copy only response properties into the - * {@link TableResult} object. - * @param resolver - * An {@link EntityResolver} instance to project the entity into an instance of type R. Set - * to null to return the entitys as instance of the class type T. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * @return - * A {@link TableResult} object with the parsed operation response. - * - * @throws XMLStreamException - * if an error occurs while accessing the stream. - * @throws ParseException - * if an error occurs while parsing the stream. - * @throws InstantiationException - * if an error occurs while constructing the result. - * @throws IllegalAccessException - * if an error occurs in reflection while parsing the result. - * @throws StorageException - * if a storage service error occurs. - */ - protected static TableResult parseSingleOpResponse(final XMLStreamReader xmlr, - final int httpStatusCode, final Class clazzType, final EntityResolver resolver, - final OperationContext opContext) throws XMLStreamException, ParseException, InstantiationException, - IllegalAccessException, StorageException { - xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null); - xmlr.next(); - - final TableResult res = parseEntity(xmlr, clazzType, resolver, opContext); - res.setHttpStatusCode(httpStatusCode); - return res; - } - - /** - * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to - * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into - * a map of String property names to {@link EntityProperty} data typed values. - * - * @param xmlr - * The XMLStreamReader to read the data from. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * - * @return - * A java.util.HashMap containing a map of String property names to - * {@link EntityProperty} data typed values found in the entity data. - * @throws XMLStreamException - * if an error occurs accessing the stream. - * @throws ParseException - * if an error occurs converting the input to a particular data type. - */ - protected static HashMap readProperties(final XMLStreamReader xmlr, - final OperationContext opContext) throws XMLStreamException, ParseException { - int eventType = xmlr.getEventType(); - xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES); - final HashMap properties = new HashMap(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - if (eventType == XMLStreamConstants.CHARACTERS) { - xmlr.getText(); - continue; - } - - if (eventType == XMLStreamConstants.START_ELEMENT - && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) { - final String key = xmlr.getLocalName(); - String val = Constants.EMPTY_STRING; - String edmType = null; - - if (xmlr.getAttributeCount() > 0) { - edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE); - } - - // move to chars - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.CHARACTERS) { - val = xmlr.getText(); - - // end element - eventType = xmlr.next(); - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, key); - - final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType)); - properties.put(key, newProp); - } - else if (eventType == XMLStreamConstants.END_ELEMENT - && xmlr.getName().toString() - .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) { - // End read properties - break; - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES); - return properties; - } - - /** - * Reserved for internal use. Writes an entity to the stream as an AtomPub Entry Resource, leaving the stream open - * for additional writing. - * - * @param entity - * The instance implementing {@link TableEntity} to write to the output stream. - * @param isTableEntry - * A flag indicating the entity is a reference to a table at the top level of the storage service when - * true and a reference to an entity within a table when false. - * @param xmlw - * The XMLStreamWriter to write the entity to. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * - * @throws XMLStreamException - * if an error occurs accessing the stream. - * @throws StorageException - * if a Storage service error occurs. - */ - protected static void writeEntityToStream(final TableEntity entity, final boolean isTableEntry, - final XMLStreamWriter xmlw, final OperationContext opContext) throws XMLStreamException, StorageException { - final HashMap properties = entity.writeEntity(opContext); - if (properties == null) { - throw new IllegalArgumentException("Entity did not produce properties to serialize"); - } - - if (!isTableEntry) { - Utility.assertNotNull(TableConstants.PARTITION_KEY, entity.getPartitionKey()); - Utility.assertNotNull(TableConstants.ROW_KEY, entity.getRowKey()); - Utility.assertNotNull(TableConstants.TIMESTAMP, entity.getTimestamp()); - } - - // Begin entry - xmlw.writeStartElement("entry"); - xmlw.writeNamespace("d", ODataConstants.DATA_SERVICES_NS); - xmlw.writeNamespace("m", ODataConstants.DATA_SERVICES_METADATA_NS); - - // default namespace - xmlw.writeNamespace(null, ODataConstants.ATOM_NS); - - // Content - xmlw.writeStartElement(ODataConstants.CONTENT); - xmlw.writeAttribute(ODataConstants.TYPE, ODataConstants.ODATA_CONTENT_TYPE); - - // m:properties - xmlw.writeStartElement("m", ODataConstants.PROPERTIES, ODataConstants.DATA_SERVICES_METADATA_NS); - - if (!isTableEntry) { - // d:PartitionKey - xmlw.writeStartElement("d", TableConstants.PARTITION_KEY, ODataConstants.DATA_SERVICES_NS); - xmlw.writeAttribute("xml", "xml", "space", "preserve"); - xmlw.writeCharacters(entity.getPartitionKey()); - xmlw.writeEndElement(); - - // d:RowKey - xmlw.writeStartElement("d", TableConstants.ROW_KEY, ODataConstants.DATA_SERVICES_NS); - xmlw.writeAttribute("xml", "xml", "space", "preserve"); - xmlw.writeCharacters(entity.getRowKey()); - xmlw.writeEndElement(); - - // d:Timestamp - if (entity.getTimestamp() == null) { - entity.setTimestamp(new Date()); - } - - xmlw.writeStartElement("d", TableConstants.TIMESTAMP, ODataConstants.DATA_SERVICES_NS); - xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE, - EdmType.DATE_TIME.toString()); - xmlw.writeCharacters(Utility.getTimeByZoneAndFormat(entity.getTimestamp(), Utility.UTC_ZONE, - Utility.ISO8061_LONG_PATTERN)); - xmlw.writeEndElement(); - } - - for (final Entry ent : properties.entrySet()) { - if (ent.getKey().equals(TableConstants.PARTITION_KEY) || ent.getKey().equals(TableConstants.ROW_KEY) - || ent.getKey().equals(TableConstants.TIMESTAMP) || ent.getKey().equals("Etag")) { - continue; - } - - EntityProperty currProp = ent.getValue(); - - // d:PropName - xmlw.writeStartElement("d", ent.getKey(), ODataConstants.DATA_SERVICES_NS); - - if (currProp.getEdmType() == EdmType.STRING) { - xmlw.writeAttribute("xml", "xml", "space", "preserve"); - } - else if (currProp.getEdmType().toString().length() != 0) { - String edmTypeString = currProp.getEdmType().toString(); - if (edmTypeString.length() != 0) { - xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE, - edmTypeString); - } - } - - if (currProp.getIsNull()) { - xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.NULL, Constants.TRUE); - } - - // Write Value - xmlw.writeCharacters(currProp.getValueAsString()); - // End d:PropName - xmlw.writeEndElement(); - } - - // End m:properties - xmlw.writeEndElement(); - - // End content - xmlw.writeEndElement(); - - // End entry - xmlw.writeEndElement(); - } - - /** - * Reserved for internal use. Writes a single entity to the specified OutputStream as a complete XML - * document. - * - * @param entity - * The instance implementing {@link TableEntity} to write to the output stream. - * @param isTableEntry - * A flag indicating the entity is a reference to a table at the top level of the storage service when - * true and a reference to an entity within a table when false. - * @param outStream - * The OutputStream to write the entity to. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * - * @throws XMLStreamException - * if an error occurs creating or accessing the stream. - * @throws StorageException - * if a Storage service error occurs. - */ - protected static void writeSingleEntityToStream(final TableEntity entity, final boolean isTableEntry, - final OutputStream outStream, final OperationContext opContext) throws XMLStreamException, StorageException { - final XMLStreamWriter xmlw = AtomPubParser.generateTableWriter(outStream); - writeSingleEntityToStream(entity, isTableEntry, xmlw, opContext); - } - - /** - * Reserved for internal use. Writes a single entity to the specified XMLStreamWriter as a complete XML - * document. - * - * @param entity - * The instance implementing {@link TableEntity} to write to the output stream. - * @param isTableEntry - * A flag indicating the entity is a reference to a table at the top level of the storage service when - * true and a reference to an entity within a table when false. - * @param xmlw - * The XMLStreamWriter to write the entity to. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * - * @throws XMLStreamException - * if an error occurs creating or accessing the stream. - * @throws StorageException - * if a Storage service error occurs. - */ - protected static void writeSingleEntityToStream(final TableEntity entity, final boolean isTableEntry, - final XMLStreamWriter xmlw, final OperationContext opContext) throws XMLStreamException, StorageException { - // default is UTF8 - xmlw.writeStartDocument("UTF-8", "1.0"); - - writeEntityToStream(entity, isTableEntry, xmlw, opContext); - - // end doc - xmlw.writeEndDocument(); - xmlw.flush(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/CloudTable.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/CloudTable.java deleted file mode 100644 index 298f2a8f6064a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/CloudTable.java +++ /dev/null @@ -1,649 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import java.io.OutputStream; -import java.io.StringWriter; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; - -import com.microsoft.windowsazure.services.blob.core.storage.SharedAccessSignatureHelper; -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageCredentials; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsAccountAndKey; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * Represents a table in the Windows Azure Table service. - */ -public final class CloudTable { - - /** - * The name of the table. - */ - String name; - - /** - * The URI of the table. - */ - URI uri; - - /** - * A reference to the associated service client. - */ - private final CloudTableClient tableServiceClient; - - /** - * Gets the name of the table. - * - * @return A String object that represents the name of the table. - */ - public String getName() { - return this.name; - } - - /** - * Gets the table service client associated with this queue. - * - * @return A {@link CloudTableClient} object that represents the service client associated with this table. - */ - public CloudTableClient getServiceClient() { - return this.tableServiceClient; - } - - /** - * Gets the absolute URI for this table. - * - * @return A java.net.URI object that represents the URI for this table. - */ - public URI getUri() { - return this.uri; - } - - /** - * Creates an instance of the CloudTable class using the specified address and client. - * - * @param tableName - * A String that represents the table name. - * @param client - * A {@link CloudTableClient} object that represents the associated service client, and that specifies - * the endpoint for the Table service. - * - * @throws URISyntaxException - * If the resource URI is invalid. - */ - public CloudTable(final String tableName, final CloudTableClient client) throws URISyntaxException { - this(PathUtility.appendPathToUri(client.getEndpoint(), tableName), client); - } - - /** - * Creates an instance of the CloudTable class using the specified table URI and client. - * - * @param uri - * A java.net.URI object that represents the absolute URI of the table. - * @param client - * A {@link CloudTableClient} object that represents the associated service client, and that specifies - * the endpoint for the Table service. - */ - public CloudTable(final URI uri, final CloudTableClient client) { - this.uri = uri; - this.name = PathUtility.getTableNameFromUri(uri, client.isUsePathStyleUris()); - this.tableServiceClient = client; - } - - /** - * Creates the table in the storage service with default request options. - *

- * This method invokes the Create - * Table REST API to create the specified table, using the Table service endpoint and storage account - * credentials of this instance. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void create() throws StorageException { - this.create(null, null); - } - - /** - * Creates the table in the storage service, using the specified {@link TableRequestOptions} and - * {@link OperationContext}. - *

- * This method invokes the Create - * Table REST API to create the specified table, using the Table service endpoint and storage account - * credentials of this instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @throws StorageException - * If an error occurs accessing the storage service, or because the table cannot be - * created, or already exists. - */ - @DoesServiceRequest - public void create(TableRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.tableServiceClient); - - Utility.assertNotNullOrEmpty("tableName", this.name); - - final DynamicTableEntity tableEntry = new DynamicTableEntity(); - tableEntry.getProperties().put(TableConstants.TABLE_NAME, new EntityProperty(this.name)); - - this.tableServiceClient.execute(TableConstants.TABLES_SERVICE_TABLES_NAME, TableOperation.insert(tableEntry), - options, opContext); - } - - /** - * Creates the table in the storage service using default request options if it does not already exist. - * - * @return A value of true if the table is created in the storage service, otherwise false - * . - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean createIfNotExist() throws StorageException { - return this.createIfNotExist(null, null); - } - - /** - * Creates the table in the storage service with the specified request options and operation context, if it does not - * already exist. - * - * @param options - * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudTableClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A value of true if the table is created in the storage service, otherwise false - * . - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean createIfNotExist(TableRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.tableServiceClient); - - Utility.assertNotNullOrEmpty("tableName", this.name); - - if (this.exists(options, opContext)) { - return false; - } - else { - try { - this.create(options, opContext); - } - catch (StorageException ex) { - if (ex.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT - && StorageErrorCodeStrings.TABLE_ALREADY_EXISTS.equals(ex.getErrorCode())) { - return false; - } - else { - throw ex; - } - } - return true; - } - } - - /** - * Deletes the table from the storage service. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void delete() throws StorageException { - this.delete(null, null); - } - - /** - * Deletes the table from the storage service, using the specified request options and operation context. - * - * @param options - * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudTableClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public void delete(TableRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.tableServiceClient); - - Utility.assertNotNullOrEmpty("tableName", this.name); - final DynamicTableEntity tableEntry = new DynamicTableEntity(); - tableEntry.getProperties().put(TableConstants.TABLE_NAME, new EntityProperty(this.name)); - - final TableOperation delOp = new TableOperation(tableEntry, TableOperationType.DELETE); - - final TableResult result = this.tableServiceClient.execute(TableConstants.TABLES_SERVICE_TABLES_NAME, delOp, - options, opContext); - - if (result.getHttpStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return; - } - else { - throw new StorageException(StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, - "Unexpected http status code received.", result.getHttpStatusCode(), null, null); - } - - } - - /** - * Deletes the table from the storage service, if it exists. - * - * @return A value of true if the table existed in the storage service and has been deleted, otherwise - * false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean deleteIfExists() throws StorageException { - return this.deleteIfExists(null, null); - } - - /** - * Deletes the table from the storage service using the specified request options and operation context, if it - * exists. - * - * @param options - * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudTableClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A value of true if the table existed in the storage service and has been deleted, otherwise - * false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean deleteIfExists(TableRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.tableServiceClient); - - Utility.assertNotNullOrEmpty("tableName", this.name); - - if (this.exists(options, opContext)) { - try { - this.delete(options, opContext); - } - catch (StorageException ex) { - if (ex.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND - && StorageErrorCodeStrings.RESOURCE_NOT_FOUND.equals(ex.getErrorCode())) { - return false; - } - else { - throw ex; - } - } - return true; - } - else { - return false; - } - - } - - /** - * Returns a value that indicates whether the table exists in the storage service. - * - * @return true if the table exists in the storage service, otherwise false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean exists() throws StorageException { - return this.exists(null, null); - } - - /** - * Returns a value that indicates whether the table exists in the storage service, using the specified request - * options and operation context. - * - * @param options - * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudTableClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return true if the table exists in the storage service, otherwise false. - * - * @throws StorageException - * If a storage service error occurred during the operation. - */ - @DoesServiceRequest - public boolean exists(TableRequestOptions options, OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.tableServiceClient); - - Utility.assertNotNullOrEmpty("tableName", this.name); - - final TableResult result = this.tableServiceClient.execute(TableConstants.TABLES_SERVICE_TABLES_NAME, - TableOperation.retrieve(this.name /* Used As PK */, null/* Row Key */, DynamicTableEntity.class), - options, opContext); - - if (result.getHttpStatusCode() == HttpURLConnection.HTTP_OK) { - return true; - } - else if (result.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - return false; - } - else { - throw new StorageException(StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, - "Unexpected http status code received.", result.getHttpStatusCode(), null, null); - } - } - - /** - * Uploads the table's permissions. - * - * @param permissions - * A {@link TablePermissions} object that represents the permissions to upload. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPermissions(final TablePermissions permissions) throws StorageException { - this.uploadPermissions(permissions, null, null); - } - - /** - * Uploads the table's permissions using the specified request options and operation context. - * - * @param permissions - * A {@link TablePermissions} object that represents the permissions to upload. - * @param options - * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudTableClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public void uploadPermissions(final TablePermissions permissions, TableRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.tableServiceClient); - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public Void execute(final CloudTableClient client, final CloudTable table, final OperationContext opContext) - throws Exception { - - final HttpURLConnection request = TableRequest.setAcl(table.uri, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - final StringWriter outBuffer = new StringWriter(); - - TableRequest.writeSharedAccessIdentifiersToStream(permissions.getSharedAccessPolicies(), outBuffer); - - final byte[] aclBytes = outBuffer.toString().getBytes("UTF8"); - - this.signTableRequest(client, request, aclBytes.length, opContext); - - final OutputStream outStreamRef = request.getOutputStream(); - outStreamRef.write(aclBytes); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - this.setNonExceptionedRetryableFailure(true); - } - - return null; - } - }; - - ExecutionEngine.executeWithRetry(this.tableServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Downloads the permission settings for the table. - * - * @return A {@link TablePermissions} object that represents the container's permissions. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public TablePermissions downloadPermissions() throws StorageException { - return this.downloadPermissions(null, null); - } - - /** - * Downloads the permissions settings for the table using the specified request options and operation context. - * - * @param options - * A {@link TableRequestOptions} object that specifies any additional options for the request. Specifying - * null will use the default request options from the associated service client ( - * {@link CloudTableClient}). - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. This object - * is used to track requests to the storage service, and to provide additional runtime information about - * the operation. - * - * @return A {@link TablePermissions} object that represents the table's permissions. - * - * @throws StorageException - * If a storage service error occurred. - */ - @DoesServiceRequest - public TablePermissions downloadPermissions(TableRequestOptions options, OperationContext opContext) - throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this.tableServiceClient); - final String tableName = this.name; - - final StorageOperation impl = new StorageOperation( - options) { - - @Override - public TablePermissions execute(final CloudTableClient client, final CloudTable table, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = TableRequest.getAcl(table.uri, tableName, this.getRequestOptions() - .getTimeoutIntervalInMs(), opContext); - this.setConnection(request); - - this.signTableRequest(client, request, -1L, opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - this.setNonExceptionedRetryableFailure(true); - } - - final TablePermissions permissions = new TablePermissions(); - final TableAccessPolicyResponse response = new TableAccessPolicyResponse(request.getInputStream()); - for (final String key : response.getAccessIdentifiers().keySet()) { - permissions.getSharedAccessPolicies().put(key, response.getAccessIdentifiers().get(key)); - } - - return permissions; - } - }; - - return ExecutionEngine.executeWithRetry(this.tableServiceClient, this, impl, options.getRetryPolicyFactory(), - opContext); - } - - /** - * Returns a shared access signature for the table. - * - * @param policy - * The access policy for the shared access signature. - * @param accessPolicyIdentifier - * A table-level access policy. - * @return A String containing the shared access signature for the table. - * @throws InvalidKeyException - * If an invalid key was passed. - * @throws StorageException - * If a storage service error occurred. - * @throws IllegalArgumentException - * If an unexpected value is passed. - */ - public String generateSharedAccessSignature(final SharedAccessTablePolicy policy, - final String accessPolicyIdentifier, final String startPartitionKey, final String startRowKey, - final String endPartitionKey, final String endRowKey) throws InvalidKeyException, StorageException { - - if (!this.tableServiceClient.getCredentials().canCredentialsSignRequest()) { - final String errorMessage = "Cannot create Shared Access Signature unless the Account Key credentials are used by the BlobServiceClient."; - throw new IllegalArgumentException(errorMessage); - } - - final String resourceName = this.getSharedAccessCanonicalName(); - - final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHash(policy, - accessPolicyIdentifier, resourceName, startPartitionKey, startRowKey, endPartitionKey, endRowKey, - this.tableServiceClient, null); - - String accountKeyName = null; - StorageCredentials credentials = this.tableServiceClient.getCredentials(); - - if (credentials instanceof StorageCredentialsAccountAndKey) { - accountKeyName = ((StorageCredentialsAccountAndKey) credentials).getAccountKeyName(); - } - - final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignature(policy, - startPartitionKey, startRowKey, endPartitionKey, endRowKey, accessPolicyIdentifier, this.name, - signature, accountKeyName); - - return builder.toString(); - } - - /** - * Returns the canonical name for shared access. - * - * @return A String containing the canonical name for shared access. - */ - private String getSharedAccessCanonicalName() { - if (this.tableServiceClient.isUsePathStyleUris()) { - return this.getUri().getPath(); - } - else { - return PathUtility.getCanonicalPathFromCredentials(this.tableServiceClient.getCredentials(), this.getUri() - .getPath()); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/CloudTableClient.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/CloudTableClient.java deleted file mode 100644 index ca181e471aa67..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/CloudTableClient.java +++ /dev/null @@ -1,993 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.ResultContinuationType; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.ServiceClient; -import com.microsoft.windowsazure.services.core.storage.StorageCredentials; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.LazySegmentedIterable; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.SegmentedStorageOperation; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; -import com.microsoft.windowsazure.services.queue.client.CloudQueue; - -/** - * Provides a service client for accessing the Windows Azure Table service. - *

- * The {@link CloudTableClient} class encapsulates the base URI for the Table service endpoint and the credentials for - * accessing the storage account, and provides methods to create, delete, list, and query tables, as well as methods to - * execute operations and queries on table entities. These methods invoke Storage Service REST API operations to make - * the requests and obtain the results that are returned. - *

- * A Table service endpoint is the base URI for Table service resources, including the DNS name of the storage account: - *
- *     http://myaccount.table.core.windows.net
- * For more information, see the MSDN topic Addressing Table Service Resources. - *

- * The credentials can be a combination of the storage account name and a key, or a shared access signature. For more - * information, see the MSDN topic Authenticating Access to Your Storage - * Account. - * - */ -public final class CloudTableClient extends ServiceClient { - - /** - * Reserved for internal use. An {@link EntityResolver} that projects table entity data as a String - * containing the table name. - */ - private final EntityResolver tableNameResolver = new EntityResolver() { - @Override - public String resolve(String partitionKey, String rowKey, Date timeStamp, - HashMap properties, String etag) { - return properties.get(TableConstants.TABLE_NAME).getValueAsString(); - } - }; - - /** - * Initializes an instance of the {@link CloudTableClient} class using a Table service endpoint. - *

- * A {@link CloudTableClient} initialized with this constructor must have storage account credentials added before - * it can be used to access the Windows Azure storage service. - * - * @param baseUri - * A java.net.URI that represents the Table service endpoint used to initialize the - * client. - */ - public CloudTableClient(final URI baseUri) { - this(baseUri, null); - this.setTimeoutInMs(TableConstants.TABLE_DEFAULT_TIMEOUT_IN_MS); - } - - /** - * Initializes an instance of the {@link CloudTableClient} class using a Table service endpoint and - * storage account credentials. - * - * @param baseUri - * A java.net.URI object that represents the Table service endpoint used to initialize the - * client. - * @param credentials - * A {@link StorageCredentials} object that represents the storage account credentials for access. - */ - public CloudTableClient(final URI baseUri, StorageCredentials credentials) { - super(baseUri, credentials); - this.setTimeoutInMs(TableConstants.TABLE_DEFAULT_TIMEOUT_IN_MS); - } - - /** - * Gets a {@link CloudTable} object that represents the storage service - * queue for the specified address. - * - * @param tableAddress - * A String that represents the name of the table, - * or the absolute URI to the queue. - * - * @return A {@link CloudQueue} object that represents a reference to the - * table. - * - * @throws URISyntaxException - * If the resource URI is invalid. - * @throws StorageException - * If a storage service error occurred during the operation. - */ - public CloudTable getTableReference(final String tableAddress) throws URISyntaxException, StorageException { - Utility.assertNotNullOrEmpty("tableAddress", tableAddress); - return new CloudTable(tableAddress, this); - } - - /** - * Executes the specified batch operation on a table as an atomic operation. A batch operation may contain up to 100 - * individual table operations, with the requirement that each operation entity must have same partition key. Only - * one retrieve operation is allowed per batch. Note that the total payload of a batch operation is limited to 4MB. - *

- * This method invokes an Entity Group - * Transaction on the REST API to execute the specified batch operation on the table as an atomic unit, using - * the Table service endpoint and storage account credentials of this instance. - * - * @param tableName - * A String containing the name of the table to execute the operations on. - * @param batch - * The {@link TableBatchOperation} object representing the operations to execute on the table. - * - * @return - * A java.util.ArrayList of {@link TableResult} that contains the results, in order, of - * each {@link TableOperation} in the {@link TableBatchOperation} on the named table. - * - * @throws StorageException - * if an error occurs accessing the storage service, or the operation fails. - */ - @DoesServiceRequest - public ArrayList execute(final String tableName, final TableBatchOperation batch) - throws StorageException { - return this.execute(tableName, batch, null, null); - } - - /** - * Executes the specified batch operation on a table as an atomic operation, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. A batch operation may contain up to 100 individual - * table operations, with the requirement that each operation entity must have same partition key. Only one retrieve - * operation is allowed per batch. Note that the total payload of a batch operation is limited to 4MB. - *

- * This method invokes an Entity Group - * Transaction on the REST API to execute the specified batch operation on the table as an atomic unit, using - * the Table service endpoint and storage account credentials of this instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param tableName - * A String containing the name of the table to execute the operations on. - * @param batch - * The {@link TableBatchOperation} object representing the operations to execute on the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * A java.util.ArrayList of {@link TableResult} that contains the results, in order, of - * each {@link TableOperation} in the {@link TableBatchOperation} on the named table. - * - * @throws StorageException - * if an error occurs accessing the storage service, or the operation fails. - */ - @DoesServiceRequest - public ArrayList execute(final String tableName, final TableBatchOperation batch, - TableRequestOptions options, OperationContext opContext) throws StorageException { - Utility.assertNotNull("batch", batch); - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this); - return batch.execute(this, tableName, options, opContext); - } - - /** - * Executes the operation on a table. - *

- * This method will invoke the Table - * Service REST API to execute the specified operation on the table, using the Table service endpoint and - * storage account credentials of this instance. - * - * @param tableName - * A String containing the name of the table to execute the operation on. - * @param operation - * The {@link TableOperation} object representing the operation to execute on the table. - * - * @return - * A {@link TableResult} containing the result of executing the {@link TableOperation} on the table. - * - * @throws StorageException - * if an error occurs accessing the storage service, or the operation fails. - */ - @DoesServiceRequest - public TableResult execute(final String tableName, final TableOperation operation) throws StorageException { - return this.execute(tableName, operation, null, null); - } - - /** - * Executes the operation on a table, using the specified {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Table - * Service REST API to execute the specified operation on the table, using the Table service endpoint and - * storage account credentials of this instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param tableName - * A String containing the name of the table to execute the operation on. - * @param operation - * The {@link TableOperation} object representing the operation to execute on the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * A {@link TableResult} containing the result of executing the {@link TableOperation} on the table. - * - * @throws StorageException - * if an error occurs accessing the storage service, or the operation fails. - */ - @DoesServiceRequest - public TableResult execute(final String tableName, final TableOperation operation, - final TableRequestOptions options, final OperationContext opContext) throws StorageException { - Utility.assertNotNull("operation", operation); - return operation.execute(this, tableName, options, opContext); - } - - /** - * Executes a query, applying the specified {@link EntityResolver} to the result. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use. - * @param resolver - * An {@link EntityResolver} instance which creates a projection of the table query result entities into - * the specified type R. - * - * @return - * A collection implementing the Iterable interface containing the projection into type - * R of the results of executing the query. - */ - @DoesServiceRequest - public Iterable execute(final TableQuery query, final EntityResolver resolver) { - return this.execute(query, resolver, null, null); - } - - /** - * Executes a query, applying the specified {@link EntityResolver} to the result, using the - * specified {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use. - * @param resolver - * An {@link EntityResolver} instance which creates a projection of the table query result entities into - * the specified type R. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * A collection implementing the Iterable interface containing the projection into type - * R of the results of executing the query. - */ - @DoesServiceRequest - @SuppressWarnings("unchecked") - public Iterable execute(final TableQuery query, final EntityResolver resolver, - final TableRequestOptions options, final OperationContext opContext) { - Utility.assertNotNull("query", query); - Utility.assertNotNull("Query requires a valid class type or resolver.", resolver); - return (Iterable) this.generateIteratorForQuery(query, resolver, options, opContext); - } - - /** - * Executes a query. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use, - * specialized for a type T implementing {@link TableEntity}. - * - * @return - * A collection implementing the Iterable interface specialized for type T of the results of - * executing the query. - */ - @DoesServiceRequest - public Iterable execute(final TableQuery query) { - return this.execute(query, null, null); - } - - /** - * Executes a query, using the specified {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use, - * specialized for a type T implementing {@link TableEntity}. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * A collection implementing the Iterable interface specialized for type T of the results of - * executing the query. - */ - @SuppressWarnings("unchecked") - @DoesServiceRequest - public Iterable execute(final TableQuery query, final TableRequestOptions options, - final OperationContext opContext) { - Utility.assertNotNull("query", query); - return (Iterable) this.generateIteratorForQuery(query, null, options, opContext); - } - - /** - * Executes a query in segmented mode with the specified {@link ResultContinuation} continuation token, - * applying the {@link EntityResolver} to the result. - * Executing a query with executeSegmented allows the query to be resumed after returning partial - * results, using information returned by the server in the {@link ResultSegment} object. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use. - * @param resolver - * An {@link EntityResolver} instance which creates a projection of the table query result entities into - * the specified type R. - * @param continuationToken - * A {@link ResultContinuation} object representing a continuation token from the server when the - * operation returns a partial result. Specify null on the initial call. Call the - * {@link ResultSegment#getContinuationToken()} method on the result to obtain the - * {@link ResultContinuation} object to use in the next call to resume the query. - * - * @return - * A {@link ResultSegment} containing the projection into type R of the results of executing - * the query. - * - * @throws IOException - * if an IO error occurred during the operation. - * @throws URISyntaxException - * if the URI generated for the query is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment executeSegmented(final TableQuery query, final EntityResolver resolver, - final ResultContinuation continuationToken) throws IOException, URISyntaxException, StorageException { - return this.executeSegmented(query, resolver, continuationToken, null, null); - } - - /** - * Executes a query in segmented mode with the specified {@link ResultContinuation} continuation token, - * using the specified {@link TableRequestOptions} and {@link OperationContext}, applying the {@link EntityResolver} - * to the result. - * Executing a query with executeSegmented allows the query to be resumed after returning partial - * results, using information returned by the server in the {@link ResultSegment} object. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use. - * @param resolver - * An {@link EntityResolver} instance which creates a projection of the table query result entities into - * the specified type R. - * @param continuationToken - * A {@link ResultContinuation} object representing a continuation token from the server when the - * operation returns a partial result. Specify null on the initial call. Call the - * {@link ResultSegment#getContinuationToken()} method on the result to obtain the - * {@link ResultContinuation} object to use in the next call to resume the query. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * A {@link ResultSegment} containing the projection into type R of the results of executing - * the query. - * - * @throws IOException - * if an IO error occurred during the operation. - * @throws URISyntaxException - * if the URI generated for the query is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - @DoesServiceRequest - @SuppressWarnings("unchecked") - public ResultSegment executeSegmented(final TableQuery query, final EntityResolver resolver, - final ResultContinuation continuationToken, final TableRequestOptions options, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - Utility.assertNotNull("Query requires a valid class type or resolver.", resolver); - return (ResultSegment) this - .executeQuerySegmentedImpl(query, resolver, continuationToken, options, opContext); - } - - /** - * Executes a query in segmented mode with a {@link ResultContinuation} continuation token. - * Executing a query with executeSegmented allows the query to be resumed after returning partial - * results, using information returned by the server in the {@link ResultSegment} object. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use, - * specialized for a type T implementing {@link TableEntity}. - * @param continuationToken - * A {@link ResultContinuation} object representing a continuation token from the server when the - * operation returns a partial result. Specify null on the initial call. Call the - * {@link ResultSegment#getContinuationToken()} method on the result to obtain the - * {@link ResultContinuation} object to use in the next call to resume the query. - * - * @return - * A {@link ResultSegment} specialized for type T of the results of executing the query. - * - * @throws IOException - * if an IO error occurred during the operation. - * @throws URISyntaxException - * if the URI generated for the query is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment executeSegmented(final TableQuery query, - final ResultContinuation continuationToken) throws IOException, URISyntaxException, StorageException { - return this.executeSegmented(query, continuationToken, null, null); - } - - /** - * Executes a query in segmented mode with a {@link ResultContinuation} continuation token, - * using the specified {@link TableRequestOptions} and {@link OperationContext}. - * Executing a query with executeSegmented allows the query to be resumed after returning partial - * results, using information returned by the server in the {@link ResultSegment} object. - *

- * This method will invoke a Query - * Entities operation on the Table - * Service REST API to query the table, using the Table service endpoint and storage account credentials of this - * instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param query - * A {@link TableQuery} instance specifying the table to query and the query parameters to use, - * specialized for a type T implementing {@link TableEntity}. - * @param continuationToken - * A {@link ResultContinuation} object representing a continuation token from the server when the - * operation returns a partial result. Specify null on the initial call. Call the - * {@link ResultSegment#getContinuationToken()} method on the result to obtain the - * {@link ResultContinuation} object to use in the next call to resume the query. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * A {@link ResultSegment} specialized for type T of the results of executing the query. - * - * @throws IOException - * if an IO error occurred during the operation. - * @throws URISyntaxException - * if the URI generated for the query is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - @DoesServiceRequest - @SuppressWarnings("unchecked") - public ResultSegment executeSegmented(final TableQuery query, - final ResultContinuation continuationToken, final TableRequestOptions options, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - Utility.assertNotNull("query", query); - return (ResultSegment) this.executeQuerySegmentedImpl(query, null, continuationToken, options, opContext); - } - - /** - * Lists the table names in the storage account. - *

- * This method invokes the Query - * Tables REST API to list the table names, using the Table service endpoint and storage account credentials of - * this instance. - * - * @return - * An Iterable collection of the table names in the storage account. - */ - @DoesServiceRequest - public Iterable listTables() { - return this.listTables(null); - } - - /** - * Lists the table names in the storage account that match the specified prefix. - *

- * This method invokes the Query - * Tables REST API to list the table names that match the prefix, using the Table service endpoint and storage - * account credentials of this instance. - * - * @param prefix - * A String containing the prefix to match on table names to return. - * - * @return - * An Iterable collection of the table names in the storage account that match the specified - * prefix. - */ - @DoesServiceRequest - public Iterable listTables(final String prefix) { - return this.listTables(prefix, null, null); - } - - /** - * Lists the table names in the storage account that match the specified prefix, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method invokes the Query - * Tables REST API to list the table names that match the prefix, using the Table service endpoint and storage - * account credentials of this instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param prefix - * A String containing the prefix to match on table names to return. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * An Iterable collection of the table names in the storage account that match the specified - * prefix. - */ - @DoesServiceRequest - public Iterable listTables(final String prefix, final TableRequestOptions options, - final OperationContext opContext) { - return this.execute(this.generateListTablesQuery(prefix), this.tableNameResolver, options, opContext); - } - - /** - * Lists the table names in the storage account in segmented mode. This method allows listing of tables to be - * resumed after returning a partial set of results, using information returned by the server in the - * {@link ResultSegment} object. - *

- * This method invokes the Query - * Tables REST API to list the table names, using the Table service endpoint and storage account credentials of - * this instance. - * - * @return - * A {@link ResultSegment} of String objects containing table names in the storage account. - * - * @throws IOException - * if an IO error occurred during the operation. - * @throws URISyntaxException - * if the URI generated for the operation is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment listTablesSegmented() throws IOException, URISyntaxException, StorageException { - return this.listTablesSegmented(null); - } - - /** - * Lists the table names in the storage account that match the specified prefix in segmented mode. This method - * allows listing of tables to be resumed after returning a partial set of results, using information returned by - * the server in the {@link ResultSegment} object. - *

- * This method invokes the Query - * Tables REST API to list the table names that match the prefix, using the Table service endpoint and storage - * account credentials of this instance. - * - * @param prefix - * A String containing the prefix to match on table names to return. - * - * @return - * A {@link ResultSegment} of String objects containing table names matching the prefix in the - * storage account. - * - * @throws IOException - * if an IO error occurred during the operation. - * @throws URISyntaxException - * if the URI generated for the operation is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment listTablesSegmented(final String prefix) throws IOException, URISyntaxException, - StorageException { - return this.listTablesSegmented(prefix, null, null, null, null); - } - - /** - * Lists up to the specified maximum of the table names in the storage account that match the specified prefix in a - * resumable mode with the specified {@link ResultContinuation} continuation token, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. This method allows listing of tables to be resumed - * after returning a page of results, using information returned by the server in the {@link ResultSegment} object. - *

- * This method invokes the Query - * Tables REST API to list the table names that match the prefix, using the Table service endpoint and storage - * account credentials of this instance. - * - * Use the {@link TableRequestOptions} to override execution options such as the timeout or retry policy for the - * operation. - * - * @param prefix - * A String containing the prefix to match on table names to return. - * @param maxResults - * The maximum number of table names to return in the {@link ResultSegment}. If this parameter is null, - * the query will list up to the maximum 1,000 results. - * @param continuationToken - * A {@link ResultContinuation} object representing a continuation token from the server when the - * operation returns a partial result. Specify null on the initial call. Call the - * {@link ResultSegment#getContinuationToken()} method on the result to obtain the - * {@link ResultContinuation} object to use in the next call to resume the query. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * A {@link ResultSegment} of String objects containing table names in the storage account. - * - * @throws IOException - * if an IO error occurred during the operation. - * @throws URISyntaxException - * if the URI generated for the operation is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - @DoesServiceRequest - public ResultSegment listTablesSegmented(final String prefix, final Integer maxResults, - final ResultContinuation continuationToken, final TableRequestOptions options, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - return this.executeSegmented(this.generateListTablesQuery(prefix).take(maxResults), this.tableNameResolver, - continuationToken, options, opContext); - } - - /** - * Reserved for internal use. Generates a query to list table names with the given prefix. - * - * @param prefix - * A String containing the prefix to match on table names to return. - * @return - * A {@link TableQuery} instance for listing table names with the specified prefix. - */ - private TableQuery generateListTablesQuery(final String prefix) { - TableQuery listQuery = TableQuery. from( - TableConstants.TABLES_SERVICE_TABLES_NAME, TableServiceEntity.class); - - if (!Utility.isNullOrEmpty(prefix)) { - // Append Max char to end '{' is 1 + 'z' in AsciiTable > uppperBound = prefix + '{' - final String prefixFilter = String.format("(%s ge '%s') and (%s lt '%s{')", TableConstants.TABLE_NAME, - prefix, TableConstants.TABLE_NAME, prefix); - - listQuery = listQuery.where(prefixFilter); - } - - return listQuery; - } - - /** - * Reserved for internal use. Implements the REST API call at the core of a segmented table query - * operation. - * - * @param queryToExecute - * The {@link TableQuery} to execute. - * @param resolver - * An {@link EntityResolver} instance to use to project the result entity as an instance of type - * R. Pass null to return the results as the table entity type. - * @param continuationToken - * The {@link ResultContinuation} to pass with the operation to resume a query, if any. Pass - * null for an initial query. - * @param taskReference - * A reference to the {@link StorageOperation} implementing the segmented operation. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * @return - * A {@link ResultSegment} containing a collection of the query results specialized for the - * {@link TableEntity} or {@link EntityResolver} type returned by the query. - * @throws StorageException - * if a Storage service error occurs. - * @throws IOException - * if an IO error occurs. - * @throws URISyntaxException - * if the URI generated for the query is invalid. - * @throws XMLStreamException - * if an error occurs accessing the XMLStreamReader. - * @throws ParseException - * if an error occurs in parsing the response. - * @throws InstantiationException - * if an error occurs in object construction. - * @throws IllegalAccessException - * if an error occurs in reflection on an object type. - * @throws InvalidKeyException - * if the key for an entity is invalid. - */ - @SuppressWarnings("unchecked") - protected ResultSegment executeQuerySegmentedCore(final TableQuery queryToExecute, - final EntityResolver resolver, final ResultContinuation continuationToken, - final StorageOperation taskReference, final TableRequestOptions options, - final OperationContext opContext) throws StorageException, IOException, URISyntaxException, - XMLStreamException, ParseException, InstantiationException, IllegalAccessException, InvalidKeyException { - if (resolver == null) { - Utility.assertNotNull("Query requires a valid class type or resolver.", queryToExecute.getClazzType()); - } - - final HttpURLConnection queryRequest = TableRequest.query(this.getTransformedEndPoint(opContext), - queryToExecute.getSourceTableName(), null/* identity */, options.getTimeoutIntervalInMs(), - queryToExecute.generateQueryBuilder(), continuationToken, options, opContext); - taskReference.setConnection(queryRequest); - - taskReference.signTableRequest(this, queryRequest, -1L, opContext); - - ExecutionEngine.processRequest(queryRequest, opContext, taskReference.getResult()); - - if (taskReference.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { - throw TableServiceException.generateTableServiceException(true, taskReference.getResult(), null, - queryRequest.getErrorStream()); - } - - ODataPayload clazzResponse = null; - ODataPayload resolvedResponse = null; - - InputStream inStream = queryRequest.getInputStream(); - - if (resolver == null) { - clazzResponse = (ODataPayload) AtomPubParser.parseResponse(inStream, queryToExecute.getClazzType(), - null, opContext); - } - else { - resolvedResponse = (ODataPayload) AtomPubParser.parseResponse(inStream, queryToExecute.getClazzType(), - resolver, opContext); - } - - final ResultContinuation nextToken = TableResponse.getTableContinuationFromResponse(queryRequest); - - if (resolver == null) { - return new ResultSegment(clazzResponse.results, - queryToExecute.getTakeCount() == null ? clazzResponse.results.size() - : queryToExecute.getTakeCount(), nextToken); - } - else { - return new ResultSegment(resolvedResponse.results, - queryToExecute.getTakeCount() == null ? resolvedResponse.results.size() - : queryToExecute.getTakeCount(), nextToken); - } - } - - /** - * Reserved for internal use. Executes a segmented query operation using the specified retry and timeout policies. - * - * @param queryToExecute - * The {@link TableQuery} to execute. - * @param resolver - * An {@link EntityResolver} instance which creates a projection of the table query result entities into - * the specified type R. Pass null to return the results as the table entity - * type. - * @param continuationToken - * The {@link ResultContinuation} to pass with the operation to resume a query, if any. Pass - * null for an initial query. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * @return - * A {@link ResultSegment} containing a collection of the query results specialized for the - * {@link TableEntity} or {@link EntityResolver} type returned by the query. - * @throws StorageException - * if a Storage service error occurs. - */ - protected ResultSegment executeQuerySegmentedImpl(final TableQuery queryToExecute, - final EntityResolver resolver, final ResultContinuation continuationToken, TableRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this); - - Utility.assertContinuationType(continuationToken, ResultContinuationType.TABLE); - - final StorageOperation, ResultSegment> impl = new StorageOperation, ResultSegment>( - options) { - @Override - public ResultSegment execute(final CloudTableClient client, final TableQuery queryRef, - final OperationContext opContext) throws Exception { - - return CloudTableClient.this.executeQuerySegmentedCore(queryRef, resolver, continuationToken, this, - (TableRequestOptions) this.getRequestOptions(), opContext); - } - }; - return ExecutionEngine.executeWithRetry(this, queryToExecute, impl, options.getRetryPolicyFactory(), opContext); - } - - protected final URI getTransformedEndPoint(final OperationContext opContext) throws URISyntaxException, - StorageException { - if (this.getCredentials().doCredentialsNeedTransformUri()) { - if (this.getEndpoint().isAbsolute()) { - return this.getCredentials().transformUri(this.getEndpoint(), opContext); - } - else { - final StorageException ex = Utility.generateNewUnexpectedStorageException(null); - ex.getExtendedErrorInformation().setErrorMessage("Table Object relative URIs not supported."); - throw ex; - } - } - else { - return this.getEndpoint(); - } - } - - /** - * Reserved for internal use. Generates an iterator for a segmented query operation. - * - * @param queryRef - * The {@link TableQuery} to execute. - * @param resolver - * An {@link EntityResolver} instance which creates a projection of the table query result entities into - * the specified type R. Pass null to return the results as the table entity - * type. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * @return - * An instance of Iterable specialized for the {@link TableEntity} or {@link EntityResolver} - * type returned by the query. - */ - protected Iterable generateIteratorForQuery(final TableQuery queryRef, - final EntityResolver resolver, TableRequestOptions options, OperationContext opContext) { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(this); - - if (resolver == null) { - final SegmentedStorageOperation, ResultSegment> impl = new SegmentedStorageOperation, ResultSegment>( - options, null) { - @Override - public ResultSegment execute(final CloudTableClient client, final TableQuery queryToExecute, - final OperationContext opContext) throws Exception { - - @SuppressWarnings("unchecked") - final ResultSegment result = (ResultSegment) CloudTableClient.this.executeQuerySegmentedCore( - queryToExecute, null, this.getToken(), this, - (TableRequestOptions) this.getRequestOptions(), opContext); - - // Note, setting the token on the SegmentedStorageOperation is - // key, this is how the iterator will share the token across executions - if (result != null) { - this.setToken(result.getContinuationToken()); - } - - return result; - } - }; - - return new LazySegmentedIterable, T>(impl, this, queryRef, - options.getRetryPolicyFactory(), opContext); - } - else { - final SegmentedStorageOperation, ResultSegment> impl = new SegmentedStorageOperation, ResultSegment>( - options, null) { - @Override - public ResultSegment execute(final CloudTableClient client, final TableQuery queryToExecute, - final OperationContext opContext) throws Exception { - - @SuppressWarnings("unchecked") - final ResultSegment result = (ResultSegment) CloudTableClient.this.executeQuerySegmentedCore( - queryToExecute, resolver, this.getToken(), this, - (TableRequestOptions) this.getRequestOptions(), opContext); - - // Note, setting the token on the SegmentedStorageOperation is - // key, this is how the iterator will share the token across executions - if (result != null) { - this.setToken(result.getContinuationToken()); - } - - return result; - } - }; - return new LazySegmentedIterable, R>(impl, this, queryRef, - options.getRetryPolicyFactory(), opContext); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/DynamicTableEntity.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/DynamicTableEntity.java deleted file mode 100644 index e4d8afccca744..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/DynamicTableEntity.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.HashMap; - -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * A {@link TableEntity} type which allows callers direct access to the property map of the entity. This class extends - * {@link TableServiceEntity} to eliminate the use of reflection for serialization and deserialization. - * - */ -public class DynamicTableEntity extends TableServiceEntity { - private HashMap properties = new HashMap(); - - /** - * Nullary default constructor. - */ - public DynamicTableEntity() { - // empty ctor - } - - /** - * Constructs a {@link DynamicTableEntity} instance using the specified property map. - * - * @param properties - * A java.util.HashMap containing a map of String property names to - * {@link EntityProperty} data typed values to store in the new {@link DynamicTableEntity}. - */ - public DynamicTableEntity(final HashMap properties) { - this.setProperties(properties); - } - - /** - * Gets the property map for this {@link DynamicTableEntity} instance. - * - * @return - * A java.util.HashMap containing the map of String property names to - * {@link EntityProperty} data typed values for this {@link DynamicTableEntity} instance. - */ - public HashMap getProperties() { - return this.properties; - } - - /** - * Populates this {@link DynamicTableEntity} instance using the specified map of property names to - * {@link EntityProperty} data typed values. - * - * @param properties - * The java.util.HashMap of String property names to {@link EntityProperty} - * data - * typed values to store in this {@link DynamicTableEntity} instance. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - */ - @Override - public void readEntity(final HashMap properties, final OperationContext opContext) { - this.setProperties(properties); - } - - /** - * Sets the property map for this {@link DynamicTableEntity} instance. - * - * @param properties - * A java.util.HashMap containing the map of String property names to - * {@link EntityProperty} data typed values to set in this {@link DynamicTableEntity} instance. - */ - public void setProperties(final HashMap properties) { - this.properties = properties; - } - - /** - * Returns the map of property names to {@link EntityProperty} data values from this {@link DynamicTableEntity} - * instance. - * - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * - * @return - * A java.util.HashMap containing the map of String property names to - * {@link EntityProperty} data typed values stored in this {@link DynamicTableEntity} instance. - * @throws StorageException - * if a Storage service error occurs. - */ - @Override - public HashMap writeEntity(final OperationContext opContext) throws StorageException { - return this.getProperties(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EdmType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EdmType.java deleted file mode 100644 index 44e8d7d8ab6fd..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EdmType.java +++ /dev/null @@ -1,203 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import com.microsoft.windowsazure.services.core.storage.Constants; - -/** - * A enumeration used to represent the primitive types of the Entity Data Model (EDM) in the Open Data Protocol (OData). - * The EDM is the underlying abstract data model used by OData services. The {@link EdmType} enumeration includes a - * {@link #parse(String)} method to convert EDM data type names to the enumeration type, and overrides the - * {@link #toString()} method to produce an EDM data type name. - *

- * For more information about OData, see the Open Data Protocol website. - *

- * For an overview of the available EDM primitive data types and names, see the Primitive Data Types section of the - * OData Protocol Overview. - *

- * The Abstract Type System used to define the primitive types supported by OData is defined in detail in [MC-CSDL] (section 2.2.1). - */ -public enum EdmType { - /** - * Null Represents the absence of a value - */ - NULL, - - /** - * Edm.Binary Represents fixed- or variable-length binary data - */ - BINARY, - - /** - * Edm.Boolean Represents the mathematical concept of binary-valued logic - */ - BOOLEAN, - - /** - * Edm.Byte Represents a unsigned 8-bit integer value - */ - BYTE, - - /** - * Edm.DateTime Represents date and time with values ranging from 12:00:00 midnight, January 1, - * 1753 A.D. through 11:59:59 P.M, December 9999 A.D. - */ - DATE_TIME, - - /** - * Edm.Decimal Represents numeric values with fixed precision and scale. This type can describe a - * numeric value ranging from negative 10^255 + 1 to positive 10^255 -1 - */ - DECIMAL, - - /** - * Edm.Double Represents a floating point number with 15 digits precision that can represent values - * with approximate range of +/- 2.23e -308 through +/- 1.79e +308 - */ - DOUBLE, - - /** - * Edm.Single Represents a floating point number with 7 digits precision that can represent values - * with approximate range of +/- 1.18e -38 through +/- 3.40e +38 - */ - SINGLE, - - /** - * Edm.Guid Represents a 16-byte (128-bit) unique identifier value - */ - GUID, - - /** - * Edm.Int16 Represents a signed 16-bit integer value - */ - INT16, - - /** - * Edm.Int32 Represents a signed 32-bit integer value - */ - INT32, - - /** - * Edm.Int64 Represents a signed 64-bit integer value - */ - INT64, - - /** - * Edm.SByte Represents a signed 8-bit integer value - */ - SBYTE, - - /** - * Edm.String Represents fixed- or variable-length character data - */ - STRING, - - /** - * Edm.Time Represents the time of day with values ranging from 0:00:00.x to 23:59:59.y, where x - * and y depend upon the precision - */ - TIME, - - /** - * Edm.DateTimeOffset Represents date and time as an Offset in minutes from GMT, with values - * ranging from 12:00:00 midnight, January 1, 1753 A.D. through 11:59:59 P.M, December 9999 A.D - */ - DATE_TIME_OFFSET; - - /** - * Parses an EDM data type name and return the matching {@link EdmType} enumeration value. A null or - * empty value parameter is matched as {@link EdmType#STRING}. Note that only the subset of EDM data types - * supported in Windows Azure Table storage is parsed, consisting of {@link #BINARY}, {@link #BOOLEAN}, - * {@link #BYTE} , {@link #DATE_TIME}, {@link #DOUBLE}, {@link #GUID}, {@link #INT32}, {@link #INT64}, and - * {@link #STRING}. Any other type will cause an {@link IllegalArgumentException} to be thrown. - * - * @param value - * A String containing the name of an EDM data type. - * @return - * The {@link EdmType} enumeration value matching the specified EDM data type. - * @throws IllegalArgumentException - * if an EDM data type not supported in Windows Azure Table storage is passed as an argument. - * - */ - public static EdmType parse(final String value) { - if (value == null || value.length() == 0) { - return EdmType.STRING; - } - else if (value.equals(ODataConstants.EDMTYPE_DATETIME)) { - return EdmType.DATE_TIME; - } - else if (value.equals(ODataConstants.EDMTYPE_INT32)) { - return EdmType.INT32; - } - else if (value.equals(ODataConstants.EDMTYPE_BOOLEAN)) { - return EdmType.BOOLEAN; - } - else if (value.equals(ODataConstants.EDMTYPE_DOUBLE)) { - return EdmType.DOUBLE; - } - else if (value.equals(ODataConstants.EDMTYPE_INT64)) { - return EdmType.INT64; - } - else if (value.equals(ODataConstants.EDMTYPE_GUID)) { - return EdmType.GUID; - } - else if (value.equals(ODataConstants.EDMTYPE_BINARY)) { - return EdmType.BINARY; - } - - throw new IllegalArgumentException("Invalid value for edmtype: ".concat(value)); - } - - /** - * Returns the name of the EDM data type corresponding to the enumeration value. - * - * @return - * A String containing the name of the EDM data type. - */ - @Override - public String toString() { - if (this == EdmType.BINARY) { - return ODataConstants.EDMTYPE_BINARY; - } - else if (this == EdmType.STRING) { - return Constants.EMPTY_STRING; - } - else if (this == EdmType.BOOLEAN) { - return ODataConstants.EDMTYPE_BOOLEAN; - } - else if (this == EdmType.DOUBLE) { - return ODataConstants.EDMTYPE_DOUBLE; - } - else if (this == EdmType.GUID) { - return ODataConstants.EDMTYPE_GUID; - } - else if (this == EdmType.INT32) { - return ODataConstants.EDMTYPE_INT32; - } - else if (this == EdmType.INT64) { - return ODataConstants.EDMTYPE_INT64; - } - else if (this == EdmType.DATE_TIME) { - return ODataConstants.EDMTYPE_DATETIME; - } - else { - // VNext : Update here if we add to supported edmtypes in the future. - return Constants.EMPTY_STRING; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EntityProperty.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EntityProperty.java deleted file mode 100644 index 5c166251b561f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EntityProperty.java +++ /dev/null @@ -1,496 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.text.ParseException; -import java.util.Date; -import java.util.UUID; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * A class which represents a single typed property value in a table entity. An {@link EntityProperty} stores the data - * type as an {@link EdmType}. The value, which may be null for object types, but not for primitive types, - * is serialized and stored as a String. - *

- * {@link EntityProperty} provides overloaded constructors and overloads of the setValue method for - * supported value types. Each overloaded constructor or setValue method sets the {@link EdmType} and - * serializes the value appropriately based on the parameter type. - *

- * Use one of the getValueAsType methods to deserialize an {@link EntityProperty} as the - * appropriate Java type. The method will throw a {@link ParseException} or {@link IllegalArgumentException} if the - * {@link EntityProperty} cannot be deserialized as the Java type. - */ -public final class EntityProperty { - private String value; - private EdmType edmType = EdmType.NULL; - private boolean isNull = false; - - /** - * Constructs an {@link EntityProperty} instance from a boolean value. - * - * @param value - * The boolean value of the entity property to set. - */ - public EntityProperty(final boolean value) { - this.setValue(value); - } - - /** - * Constructs an {@link EntityProperty} instance from a byte[] value. - * - * @param value - * The byte[] value of the entity property to set. - */ - public EntityProperty(final byte[] value) { - this.setValue(value); - } - - /** - * Constructs an {@link EntityProperty} instance from a Byte[]. - * - * @param value - * The Byte[] to set as the entity property value. - */ - public EntityProperty(final Byte[] value) { - this.setValue(value); - } - - /** - * Constructs an {@link EntityProperty} instance from a Date value. - * - * @param value - * The Date to set as the entity property value. - */ - public EntityProperty(final Date value) { - this.setValue(value); - } - - /** - * Constructs an {@link EntityProperty} instance from a double value. - * - * @param value - * The double value of the entity property to set. - */ - public EntityProperty(final double value) { - this.setValue(value); - } - - /** - * Constructs an {@link EntityProperty} instance from an int value. - * - * @param value - * The int value of the entity property to set. - */ - public EntityProperty(final int value) { - this.setValue(value); - } - - /** - * Constructs an {@link EntityProperty} instance from a long value. - * - * @param value - * The long value of the entity property to set. - */ - public EntityProperty(final long value) { - this.setValue(value); - } - - /** - * Constructs an {@link EntityProperty} instance from a String value. - * - * @param value - * The String to set as the entity property value. - */ - public EntityProperty(final String value) { - this.setValue(value); - } - - /** - * Reserved for internal use. Constructs an {@link EntityProperty} instance from a String value and a - * data type, and verifies that the value can be interpreted as the specified data type. - * - * @param value - * The String representation of the value to construct. - * @param edmType - * The {@link EdmType} data type of the value to construct. - * @throws ParseException - * if the String representation of the value cannot be interpreted as the data type. - */ - protected EntityProperty(final String value, final EdmType edmType) throws ParseException { - this.edmType = edmType; - this.value = value; - - // validate data is encoded correctly - if (edmType == EdmType.STRING) { - return; - } - else if (edmType == EdmType.BINARY) { - this.getValueAsByteArray(); - } - else if (edmType == EdmType.BOOLEAN) { - this.getValueAsBoolean(); - } - else if (edmType == EdmType.DOUBLE) { - this.getValueAsDouble(); - } - else if (edmType == EdmType.GUID) { - this.getValueAsUUID(); - } - else if (edmType == EdmType.INT32) { - this.getValueAsInteger(); - } - else if (edmType == EdmType.INT64) { - this.getValueAsLong(); - } - else if (edmType == EdmType.DATE_TIME) { - this.getValueAsDate(); - } - } - - /** - * Constructs an {@link EntityProperty} instance from a java.util.UUID value. - * - * @param value - * The java.util.UUID to set as the entity property value. - */ - public EntityProperty(final UUID value) { - this.setValue(value); - } - - /** - * Reserved for internal use. Constructs an {@link EntityProperty} instance as a null value with the - * specified type. - * - * @param type - * The {@link EdmType} to set as the entity property type. - */ - protected EntityProperty(EdmType type) { - this.value = null; - this.edmType = type; - this.isNull = true; - } - - /** - * Gets the {@link EdmType} storage data type for the {@link EntityProperty}. - * - * @return - * The {@link EdmType} enumeration value for the data type of the {@link EntityProperty}. - */ - public EdmType getEdmType() { - return this.edmType; - } - - /** - * Gets a flag indicating that the {@link EntityProperty} value is null. - * - * @return - * A boolean flag indicating that the {@link EntityProperty} value is null. - */ - public boolean getIsNull() { - return this.isNull; - } - - /** - * Gets the value of this {@link EntityProperty} as a boolean. - * - * @return - * A boolean representation of the {@link EntityProperty} value. - * - * @throws IllegalArgumentException - * if the value is null or cannot be parsed as a boolean. - */ - public boolean getValueAsBoolean() { - if (this.isNull) { - throw new IllegalArgumentException("EntityProperty cannot be set to null for value types."); - } - return Boolean.parseBoolean(this.value); - } - - /** - * Gets the value of this {@link EntityProperty} as a byte array. - * - * @return - * A byte[] representation of the {@link EntityProperty} value, or null. - */ - public byte[] getValueAsByteArray() { - return this.isNull ? null : Base64.decode(this.value); - } - - /** - * Gets the value of this {@link EntityProperty} as a Byte array. - * - * @return - * A Byte[] representation of the {@link EntityProperty} value, or null. - */ - public Byte[] getValueAsByteObjectArray() { - return this.isNull ? null : Base64.decodeAsByteObjectArray(this.value); - } - - /** - * Gets the value of this {@link EntityProperty} as a Date. - * - * @return - * A Date representation of the {@link EntityProperty} value, or null. - * - * @throws IllegalArgumentException - * if the value is not null and cannot be parsed as a Date. - */ - public Date getValueAsDate() { - if (this.isNull) { - return null; - } - - return Utility.parseDate(this.value); - } - - /** - * Gets the value of this {@link EntityProperty} as a double. - * - * @return - * A double representation of the {@link EntityProperty} value. - * - * @throws IllegalArgumentException - * if the value is null or cannot be parsed as a double. - */ - public double getValueAsDouble() { - if (this.isNull) { - throw new IllegalArgumentException("EntityProperty cannot be set to null for value types."); - } - return Double.parseDouble(this.value); - } - - /** - * Gets the value of this {@link EntityProperty} as an int. - * - * @return - * An int representation of the {@link EntityProperty} value. - * - * @throws IllegalArgumentException - * if the value is null or cannot be parsed as an int. - */ - public int getValueAsInteger() { - if (this.isNull) { - throw new IllegalArgumentException("EntityProperty cannot be set to null for value types."); - } - return Integer.parseInt(this.value); - } - - /** - * Gets the value of this {@link EntityProperty} as a long. - * - * @return - * A long representation of the {@link EntityProperty} value. - * - * @throws IllegalArgumentException - * if the value is null or cannot be parsed as a long. - */ - public long getValueAsLong() { - if (this.isNull) { - throw new IllegalArgumentException("EntityProperty cannot be set to null for value types."); - } - return Long.parseLong(this.value); - } - - /** - * Gets the value of this {@link EntityProperty} as a String. - * - * @return - * A String representation of the {@link EntityProperty} value, or null. - */ - public String getValueAsString() { - return this.isNull ? null : this.value; - } - - /** - * Gets the value of this {@link EntityProperty} as a java.util.UUID. - * - * @return - * A java.util.UUID representation of the {@link EntityProperty} value, or null. - * - * @throws IllegalArgumentException - * if the value cannot be parsed as a java.util.UUID. - */ - public UUID getValueAsUUID() { - return this.isNull ? null : UUID.fromString(this.value); - } - - /** - * Sets this {@link EntityProperty} using the serialized boolean value. - * - * @param value - * The boolean value to set as the {@link EntityProperty} value. - */ - public synchronized final void setValue(final boolean value) { - this.edmType = EdmType.BOOLEAN; - this.isNull = false; - this.value = value ? Constants.TRUE : Constants.FALSE; - } - - /** - * Sets this {@link EntityProperty} using the serialized byte[] value. - * - * @param value - * The byte[] value to set as the {@link EntityProperty} value. This value may be - * null. - */ - public synchronized final void setValue(final byte[] value) { - this.edmType = EdmType.BINARY; - if (value == null) { - this.value = null; - this.isNull = true; - return; - } - else { - this.isNull = false; - } - - this.value = Base64.encode(value); - } - - /** - * Sets this {@link EntityProperty} using the serialized Byte[] value. - * - * @param value - * The Byte[] value to set as the {@link EntityProperty} value. This value may be - * null. - */ - public synchronized final void setValue(final Byte[] value) { - this.edmType = EdmType.BINARY; - if (value == null) { - this.value = null; - this.isNull = true; - return; - } - else { - this.isNull = false; - } - - this.value = Base64.encode(value); - } - - /** - * Sets this {@link EntityProperty} using the serialized Date value. - * - * @param value - * The Date value to set as the {@link EntityProperty} value. This value may be - * null. - */ - public synchronized final void setValue(final Date value) { - this.edmType = EdmType.DATE_TIME; - - if (value == null) { - this.value = null; - this.isNull = true; - return; - } - else { - this.isNull = false; - } - - this.value = Utility.getTimeByZoneAndFormat(value, Utility.UTC_ZONE, Utility.ISO8061_LONG_PATTERN); - } - - /** - * Sets this {@link EntityProperty} using the serialized double value. - * - * @param value - * The double value to set as the {@link EntityProperty} value. - */ - public synchronized final void setValue(final double value) { - this.edmType = EdmType.DOUBLE; - this.isNull = false; - this.value = Double.toString(value); - } - - /** - * Sets this {@link EntityProperty} using the serialized int value. - * - * @param value - * The int value to set as the {@link EntityProperty} value. - */ - public synchronized final void setValue(final int value) { - this.edmType = EdmType.INT32; - this.isNull = false; - this.value = Integer.toString(value); - } - - /** - * Sets this {@link EntityProperty} using the serialized long value. - * - * @param value - * The long value to set as the {@link EntityProperty} value. - */ - public synchronized final void setValue(final long value) { - this.edmType = EdmType.INT64; - this.isNull = false; - this.value = Long.toString(value); - } - - /** - * Sets this {@link EntityProperty} using the String value. - * - * @param value - * The String value to set as the {@link EntityProperty} value. This value may be - * null. - */ - public synchronized final void setValue(final String value) { - this.edmType = EdmType.STRING; - if (value == null) { - this.value = null; - this.isNull = true; - return; - } - else { - this.isNull = false; - } - - this.value = value; - } - - /** - * Sets this {@link EntityProperty} using the serialized java.util.UUID value. - * - * @param value - * The java.util.UUID value to set as the {@link EntityProperty} value. - * This value may be null. - */ - public synchronized final void setValue(final UUID value) { - this.edmType = EdmType.GUID; - if (value == null) { - this.value = null; - this.isNull = true; - return; - } - else { - this.isNull = false; - } - - this.value = value.toString(); - } - - /** - * Reserved for internal use. Sets the null value flag to the specified boolean value. - * - * @param isNull - * The boolean value to set in the null value flag. - */ - protected void setIsNull(final boolean isNull) { - this.isNull = isNull; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EntityResolver.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EntityResolver.java deleted file mode 100644 index 013e0cdd1da7b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/EntityResolver.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.Date; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * An interface to perform client side projection on a retrieved entity. An {@link EntityResolver} instance must - * implement a resolve method projecting the entity data represented by the parameters passed in as a new - * instance of the type specified by the type parameter. - *

- * This interface is useful for converting directly from table entity data to a client object type without requiring a - * separate table entity class type that deserializes every property individually. For example, a client can perform a - * client side projection of a Customer entity by simply returning the String for the - * CustomerName property of each entity. The result of this projection will be a collection of - * Strings containing each customer name. - * - * @param - * The type of the object that the resolver produces. - */ -public interface EntityResolver { - /** - * Returns a reference to a new object instance of type T containing a projection of the specified - * table entity data. - * - * @param partitionKey - * A String containing the PartitionKey value for the entity. - * @param rowKey - * A String containing the RowKey value for the entity. - * @param timeStamp - * A Date containing the Timestamp value for the entity. - * @param properties - * The java.util.HashMap of String property names to {@link EntityProperty} - * data type and value pairs representing the table entity data. - * @param etag - * A String containing the Etag for the entity. - * @return - * A reference to an object instance of type T constructed as a projection of the table entity - * parameters. - * @throws StorageException - * if an error occurs during the operation. - */ - T resolve(String partitionKey, String rowKey, Date timeStamp, HashMap properties, - String etag) throws StorageException; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/Ignore.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/Ignore.java deleted file mode 100644 index d014927db13b3..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/Ignore.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * An annotation set on a method to prevent its use in serializing or deserializing a property by reflection. Apply the - * @Ignore annotation to methods in a class implementing {@link TableEntity} to force them to be ignored - * during reflection-based serialization and deserialization. See the documentation for {@link TableServiceEntity} for - * more information on using reflection-based serialization and deserialization. - * - * @see StoreAs - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Documented -public @interface Ignore { - // No attributes -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimeHeader.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimeHeader.java deleted file mode 100644 index 65b3bed132e70..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimeHeader.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -/** - * Reserved for internal use. A class that represents a given MIME Header. - */ -class MimeHeader { - protected String boundary; - protected String contentType; - protected String contentTransferEncoding; - protected String subBoundary; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimeHelper.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimeHelper.java deleted file mode 100644 index 53c5e1f605805..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimeHelper.java +++ /dev/null @@ -1,510 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.StringWriter; -import java.net.URISyntaxException; -import java.util.ArrayList; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Reserved for internal use. A class used to read and write MIME requests and responses. - */ -class MimeHelper { - /** - * Reserved for internal use. A static factory method that generates a {@link StorageException} for invalid MIME - * responses. - * - * @return - * The {@link StorageException} for the invalid MIME response. - */ - protected static StorageException generateMimeParseException() { - return new StorageException(StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, "Invalid MIME response received.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - /** - * Reserved for internal use. Returns the HTTP verb for a table operation. - * - * @param operation - * The {@link TableOperation} instance to get the HTTP verb for. - * @return - * A String containing the HTTP verb to use with the operation. - */ - protected static String getHttpVerbForOperation(final TableOperation operation) { - if (operation.getOperationType() == TableOperationType.INSERT) { - return "POST"; - } - else if (operation.getOperationType() == TableOperationType.DELETE) { - return "DELETE"; - } - else if (operation.getOperationType() == TableOperationType.MERGE - || operation.getOperationType() == TableOperationType.INSERT_OR_MERGE) { - return "MERGE"; - } - else if (operation.getOperationType() == TableOperationType.REPLACE - || operation.getOperationType() == TableOperationType.INSERT_OR_REPLACE) { - return "PUT"; - } - else if (operation.getOperationType() == TableOperationType.RETRIEVE) { - return "GET"; - } - else { - throw new IllegalArgumentException("Unknown table operation"); - } - } - - /** - * Reserved for internal use. Returns the next non-blank line from the {@link BufferedReader}. - * - * @param reader - * The {@link BufferedReader} to read lines from. - * @return - * A String containing the next non-blank line from the {@link BufferedReader}, or - * null. - * @throws IOException - * if an error occurs reading from the {@link BufferedReader}. - */ - protected static String getNextLineSkippingBlankLines(final BufferedReader reader) throws IOException { - String tString = null; - do { - tString = reader.readLine(); - } while (tString != null && tString.length() == 0); - - return tString; - } - - /** - * Reserved for internal use. Reads the response stream from a batch operation into an ArrayList of - * {@link MimePart} objects. - * - * @param inStream - * An {@link InputStream} containing the operation response stream. - * @param expectedBundaryName - * A String containing the MIME part boundary string. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * @return - * An ArrayList of {@link MimePart} objects parsed from the input stream. - * @throws IOException - * if an error occurs accessing the input stream. - * @throws StorageException - * if an error occurs parsing the input stream. - */ - protected static ArrayList readBatchResponseStream(final InputStream inStream, - final String expectedBundaryName, final OperationContext opContext) throws IOException, StorageException { - final ArrayList result = new ArrayList(); - final InputStreamReader streamReader = new InputStreamReader(inStream, "UTF-8"); - final BufferedReader reader = new BufferedReader(streamReader); - final String mungedExpectedBoundaryName = "--".concat(expectedBundaryName); - - final MimeHeader docHeader = readMimeHeader(reader, opContext); - if (docHeader.boundary == null || !docHeader.boundary.equals(mungedExpectedBoundaryName)) { - throw generateMimeParseException(); - } - - MimeHeader currHeader = null; - - // No explicit changeset present - if (docHeader.subBoundary == null) { - do { - result.add(readMimePart(reader, docHeader.boundary, opContext)); - currHeader = readMimeHeader(reader, opContext); - } while (currHeader != null); - } - else { - // explicit changeset present. - currHeader = readMimeHeader(reader, opContext); - if (currHeader == null) { - throw new TableServiceException( - -1, - "An Error Occurred while processing the request, check the extended error information for more details.", - null, reader); - } - else { - do { - result.add(readMimePart(reader, docHeader.subBoundary, opContext)); - currHeader = readMimeHeader(reader, opContext); - } while (currHeader != null); - } - } - - return result; - } - - /** - * Reserved for internal use. A static factory method that constructs a {@link MimeHeader} by parsing the MIME - * header - * data from a {@link BufferedReader}. - * - * @param reader - * The {@link BufferedReader} containing the response stream to parse. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * @return - * A {@link MimeHeader} constructed by parsing the MIME header data from the {@link BufferedReader}. - * @throws IOException - * if an error occurs accessing the input stream. - * @throws StorageException - * if an error occurs parsing the input stream. - */ - protected static MimeHeader readMimeHeader(final BufferedReader reader, final OperationContext opContext) - throws IOException, StorageException { - final MimeHeader retHeader = new MimeHeader(); - reader.mark(1024 * 1024); - - // First thing is separator - retHeader.boundary = getNextLineSkippingBlankLines(reader); - if (retHeader.boundary.endsWith("--")) { - return null; - } - if (!retHeader.boundary.startsWith("--")) { - reader.reset(); - return null; - } - - for (int m = 0; m < 2; m++) { - final String tempString = reader.readLine(); - if (tempString.length() == 0) { - break; - } - - if (tempString.startsWith("Content-Type:")) { - final String[] headerVals = tempString.split("Content-Type: "); - if (headerVals == null || headerVals.length != 2) { - throw generateMimeParseException(); - } - retHeader.contentType = headerVals[1]; - } - else if (tempString.startsWith("Content-Transfer-Encoding:")) { - final String[] headerVals = tempString.split("Content-Transfer-Encoding: "); - if (headerVals == null || headerVals.length != 2) { - throw generateMimeParseException(); - } - retHeader.contentTransferEncoding = headerVals[1]; - } - else { - throw generateMimeParseException(); - } - } - - // Validate headers - if (Utility.isNullOrEmpty(retHeader.boundary) || retHeader.contentType == null) { - throw generateMimeParseException(); - } - - if (retHeader.contentType.startsWith("multipart/mixed; boundary=")) { - final String[] headerVals = retHeader.contentType.split("multipart/mixed; boundary="); - if (headerVals == null || headerVals.length != 2) { - throw generateMimeParseException(); - } - retHeader.subBoundary = "--".concat(headerVals[1]); - } - else if (!retHeader.contentType.equals("application/http")) { - throw generateMimeParseException(); - } - - if (retHeader.contentTransferEncoding != null && !retHeader.contentTransferEncoding.equals("binary")) { - throw generateMimeParseException(); - } - - return retHeader; - } - - // Returns at start of next mime boundary header - /** - * Reserved for internal use. A static factory method that generates a {@link MimePart} containing the next MIME - * part read from the {@link BufferedReader}. - * The {@link BufferedReader} is left positioned at the start of the next MIME boundary header. - * - * @param reader - * The {@link BufferedReader} containing the response stream to parse. - * @param boundary - * A String containing the MIME part boundary string. - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * @return - * A {@link MimePart} constructed by parsing the next MIME part data from the {@link BufferedReader}. - * @throws IOException - * if an error occured accessing the input stream. - * @throws StorageException - * if an error occured parsing the input stream. - */ - protected static MimePart readMimePart(final BufferedReader reader, final String boundary, - final OperationContext opContext) throws IOException, StorageException { - final MimePart retPart = new MimePart(); - // Read HttpStatus code - String tempStr = getNextLineSkippingBlankLines(reader); - if (!tempStr.startsWith("HTTP/1.1 ")) { - throw generateMimeParseException(); - } - - final String[] headerVals = tempStr.split(" "); - - if (headerVals.length < 3) { - throw generateMimeParseException(); - } - - retPart.httpStatusCode = Integer.parseInt(headerVals[1]); - // "HTTP/1.1 XXX ".length() => 13 - retPart.httpStatusMessage = tempStr.substring(13); - - // Read headers - tempStr = reader.readLine(); - while (tempStr != null && tempStr.length() > 0) { - final String[] headerParts = tempStr.split(": "); - if (headerParts.length < 2) { - throw generateMimeParseException(); - } - - retPart.headers.put(headerParts[0], headerParts[1]); - tempStr = reader.readLine(); - } - - // Store xml payload - reader.mark(1024 * 1024); - tempStr = getNextLineSkippingBlankLines(reader); - - if (tempStr == null) { - throw generateMimeParseException(); - } - - // empty body - if (tempStr.startsWith(boundary)) { - reader.reset(); - retPart.payload = Constants.EMPTY_STRING; - return retPart; - } - else if (!tempStr.startsWith("Performing Entity Group - * Transactions. - * - * @param outStream - * The {@link OutputStream} to write the batch request to. - * @param tableName - * A String containing the name of the table to apply each operation to. - * @param batch - * A {@link TableBatchOperation} containing the operations to write to the output stream - * @param batchID - * A String containing the identifier to use as the MIME boundary for the batch request. - * @param changeSet - * A String containing the identifier to use as the MIME boundary for operations within the - * batch. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * @throws IOException - * if an IO error occurs. - * @throws URISyntaxException - * if an invalid URI is used. - * @throws StorageException - * if an error occurs accessing the Storage service. - * @throws XMLStreamException - * if an error occurs accessing the stream. - */ - protected static void writeBatchToStream(final OutputStream outStream, final String tableName, - final TableBatchOperation batch, final String batchID, final String changeSet, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException, - XMLStreamException { - final OutputStreamWriter outWriter = new OutputStreamWriter(outStream, "UTF8"); - - int contentID = 0; - boolean inChangeSet = false; - for (final TableOperation op : batch) { - if (op.getOperationType() == TableOperationType.RETRIEVE) { - final QueryTableOperation qOp = (QueryTableOperation) op; - - if (inChangeSet) { - inChangeSet = false; - // Write Boundary end. - MimeHelper.writeMIMEBoundaryClosure(outWriter, changeSet); - outWriter.write("\r\n"); - } - - // Write MIME Header - MimeHelper.writeMIMEBoundary(outWriter, batchID); - outWriter.write("Content-Type: application/http\r\n"); - outWriter.write("Content-Transfer-Encoding: binary\r\n\r\n"); - - outWriter.write(String.format("%s %s HTTP/1.1\r\n", getHttpVerbForOperation(op), - qOp.generateRequestIdentityWithTable(tableName))); - - outWriter.write("Host: host\r\n\r\n"); - } - else { - if (!inChangeSet) { - inChangeSet = true; - // New batch mime part - MimeHelper.writeMIMEBoundary(outWriter, batchID); - MimeHelper.writeMIMEContentType(outWriter, changeSet); - outWriter.write("\r\n"); - } - - // New mime part for changeset - MimeHelper.writeMIMEBoundary(outWriter, changeSet); - - // Write Headers - outWriter.write("Content-Type: application/http\r\n"); - outWriter.write("Content-Transfer-Encoding: binary\r\n\r\n"); - - outWriter.write(String.format("%s %s HTTP/1.1\r\n", getHttpVerbForOperation(op), - op.generateRequestIdentityWithTable(tableName))); - - outWriter.write(String.format("Content-ID: %s\r\n", Integer.toString(contentID))); - - if (op.getOperationType() != TableOperationType.INSERT - && op.getOperationType() != TableOperationType.INSERT_OR_MERGE - && op.getOperationType() != TableOperationType.INSERT_OR_REPLACE) { - outWriter.write(String.format("If-Match: %s\r\n", op.getEntity().getEtag())); - } - - if (op.getOperationType() == TableOperationType.DELETE) { - // empty body - outWriter.write("\r\n"); - } - else { - outWriter.write("Content-Type: application/atom+xml;type=entry\r\n"); - final String opString = writeStringForOperation(op, opContext); - outWriter.write(String.format("Content-Length: %s\r\n\r\n", - Integer.toString(opString.getBytes("UTF-8").length))); - outWriter.write(opString); - } - contentID = contentID + 1; - } - } - - if (inChangeSet) { - MimeHelper.writeMIMEBoundaryClosure(outWriter, changeSet); - } - MimeHelper.writeMIMEBoundaryClosure(outWriter, batchID); - - outWriter.flush(); - } - - /** - * Reserved for internal use. Writes a MIME part boundary to the output stream. - * - * @param outWriter - * The {@link OutputStreamWriter} to write the MIME part boundary to. - * @param boundaryID - * The String containing the MIME part boundary string. - * @throws IOException - * if an error occurs writing to the output stream. - */ - protected static void writeMIMEBoundary(final OutputStreamWriter outWriter, final String boundaryID) - throws IOException { - outWriter.write(String.format("--%s\r\n", boundaryID)); - } - - /** - * Reserved for internal use. Writes a MIME part boundary closure to the output stream. - * - * @param outWriter - * The {@link OutputStreamWriter} to write the MIME part boundary closure to. - * @param boundaryID - * The String containing the MIME part boundary string. - * @throws IOException - * if an error occurs writing to the output stream. - */ - protected static void writeMIMEBoundaryClosure(final OutputStreamWriter outWriter, final String boundaryID) - throws IOException { - outWriter.write(String.format("--%s--\r\n", boundaryID)); - } - - /** - * Reserved for internal use. Writes a MIME content type string to the output stream. - * - * @param outWriter - * The {@link OutputStreamWriter} to write the MIME content type string to. - * @param boundaryID - * The String containing the MIME part boundary string. - * @throws IOException - * if an error occurs writing to the output stream. - */ - protected static void writeMIMEContentType(final OutputStreamWriter outWriter, final String boundaryName) - throws IOException { - outWriter.write(String.format("Content-Type: multipart/mixed; boundary=%s\r\n", boundaryName)); - } - - /** - * Reserved for internal use. Generates a String containing the entity associated with an operation in - * AtomPub format. - * - * @param operation - * A {@link TableOperation} containing the entity to write to the returned String. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * @return - * A String containing the entity associated with the operation in AtomPub format - * @throws StorageException - * if a Storage error occurs. - * @throws XMLStreamException - * if an error occurs creating or writing to the output string. - */ - protected static String writeStringForOperation(final TableOperation operation, final OperationContext opContext) - throws StorageException, XMLStreamException { - final StringWriter outWriter = new StringWriter(); - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outWriter); - - AtomPubParser.writeSingleEntityToStream(operation.getEntity(), false, xmlw, opContext); - outWriter.write("\r\n"); - - return outWriter.toString(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimePart.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimePart.java deleted file mode 100644 index b8751b5e23fab..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/MimePart.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.HashMap; - -/** - * Reserved for internal use. A class that represents a given MIME Part. - */ -class MimePart { - protected int httpStatusCode = -1; - protected String httpStatusMessage; - protected HashMap headers = new HashMap(); - protected String payload; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/ODataConstants.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/ODataConstants.java deleted file mode 100644 index e2dfc5d373752..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/ODataConstants.java +++ /dev/null @@ -1,183 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -/** - * Reserved for internal use. A class that holds relevant constants for interacting with OData feeds. - */ -class ODataConstants { - /** - * The String representation of the Atom namespace. - */ - public static final String ATOM_NS = "http://www.w3.org/2005/Atom"; - - /** - * The String representation of the OData Data namespace. - */ - public static final String DATA_SERVICES_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices"; - - /** - * The String representation of the OData Metadata namespace. - */ - public static final String DATA_SERVICES_METADATA_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; - - /** - * The String representation of the Atom namespace in brackets. - */ - public static final String BRACKETED_ATOM_NS = "{" + ATOM_NS + "}"; // default - - /** - * The String representation of the OData Data namespace in brackets. - */ - public static final String BRACKETED_DATA_SERVICES_NS = "{" + DATA_SERVICES_NS + "}"; // d: - - /** - * The String representation of the OData Metadata namespace in brackets. - */ - public static final String BRACKETED_DATA_SERVICES_METADATA_NS = "{" + DATA_SERVICES_METADATA_NS + "}"; // m: - - /** - * The String representation of the Atom Entry feed element name. - */ - public static final String FEED = "feed"; - - /** - * The String representation of the Atom Entry title element name. - */ - public static final String TITLE = "title"; - - /** - * The String representation of the Atom Entry id element name. - */ - public static final String ID = "id"; - - /** - * The String representation of the Atom Entry updated element name. - */ - public static final String UPDATED = "updated"; - - /** - * The String representation of the Atom Entry link element name. - */ - public static final String LINK = "link"; - - /** - * The String representation of the Atom Entry author element name. - */ - public static final String AUTHOR = "author"; - - /** - * The String representation of the Atom Entry name element name. - */ - public static final String NAME = "name"; - - /** - * The String representation of the Atom Entry entry element name. - */ - public static final String ENTRY = "entry"; - - /** - * The String representation of the Atom Entry category element name. - */ - public static final String CATEGORY = "category"; - - /** - * The String representation of the Atom Entry content element name. - */ - public static final String CONTENT = "content"; - - /** - * The String representation of the OData Metadata properties element name. - */ - public static final String PROPERTIES = "properties"; - - /** - * The String representation of the Atom Entry etag element name. - */ - public static final String ETAG = "etag"; - - /** - * The String representation of the type attribute name. - */ - public static final String TYPE = "type"; - - /** - * The String representation of the term element name. - */ - public static final String TERM = "term"; - - /** - * The String representation of scheme. - */ - public static final String SCHEME = "scheme"; - - /** - * The String representation of href. - */ - public static final String HREF = "href"; - - /** - * The String representation of rel. - */ - public static final String REL = "rel"; - - /** - * The String representation of the null attribute name. - */ - public static final String NULL = "null"; - - /** - * The String representation of the content type attribute value to send. - */ - public static final String ODATA_CONTENT_TYPE = "application/xml"; - - // Odata edm types - - /** - * The String representation of the Edm.DateTime metadata type attribute value. - */ - public static final String EDMTYPE_DATETIME = "Edm.DateTime"; - - /** - * The String representation of the Edm.Binary metadata type attribute value. - */ - public static final String EDMTYPE_BINARY = "Edm.Binary"; - - /** - * The String representation of the Edm.Boolean metadata type attribute value. - */ - public static final String EDMTYPE_BOOLEAN = "Edm.Boolean"; - - /** - * The String representation of the Edm.Double metadata type attribute value. - */ - public static final String EDMTYPE_DOUBLE = "Edm.Double"; - - /** - * The String representation of the Edm.Guid metadata type attribute value. - */ - public static final String EDMTYPE_GUID = "Edm.Guid"; - - /** - * The String representation of the Edm.Int32 metadata type attribute value. - */ - public static final String EDMTYPE_INT32 = "Edm.Int32"; - - /** - * The String representation of the Edm.Int64 metadata type attribute value. - */ - public static final String EDMTYPE_INT64 = "Edm.Int64"; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/ODataPayload.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/ODataPayload.java deleted file mode 100644 index 9fbf3cb0a0626..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/ODataPayload.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.ArrayList; - -/** - * Reserved for internal use. A class that represents an OData payload and resulting entities. - */ -class ODataPayload { - /** - * A collection of table entities. - */ - protected ArrayList results; - - /** - * A collection of {@link TableResults} which include additional information about the entities returned by an - * operation. - */ - protected ArrayList tableResults; - - /** - * Constructs an {@link ODataPayload} instance with new empty entity and {@link TableResult} collections. - */ - protected ODataPayload() { - this.results = new ArrayList(); - this.tableResults = new ArrayList(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/PropertyPair.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/PropertyPair.java deleted file mode 100644 index aed9941b8c8f1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/PropertyPair.java +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Map.Entry; -import java.util.UUID; - -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * Reserved for internal use. A class used internally during the reflection process to determine which properties should - * be serialized. - */ -class PropertyPair { - /** - * Reserved for internal use. A static factory method to generate a map of property names to {@link PropertyPair} - * instances for the specified class type. Uses reflection to find pairs of getter and setter methods that are - * annotated with {@link StoreAs} with a common property name, or of the form getPropertyName - * and setPropertyName, with a common type for the getter return value and the - * setter parameter, and stores the methods and the property name for each pair found in a map for use in - * serializing and deserializing entity data. - * - * @param clazzType - * The class type to check for matching getter and setter methods with a common return and parameter - * type, respectively. - */ - protected static HashMap generatePropertyPairs(final Class clazzType) { - final Method[] methods = clazzType.getMethods(); - final HashMap propMap = new HashMap(); - - String propName = null; - PropertyPair currProperty = null; - - for (final Method m : methods) { - if (m.getName().length() < 4 || (!m.getName().startsWith("get") && !m.getName().startsWith("set"))) { - continue; - } - - // TODO add logging - // System.out.println(m.getName()); - - propName = m.getName().substring(3); - - // Skip interface methods, these will be called explicitly - if (propName.equals(TableConstants.PARTITION_KEY) || propName.equals(TableConstants.ROW_KEY) - || propName.equals(TableConstants.TIMESTAMP) || propName.equals("Etag") - || propName.equals("LastModified")) { - continue; - } - - if (propMap.containsKey(propName)) { - currProperty = propMap.get(propName); - } - else { - currProperty = new PropertyPair(); - currProperty.name = propName; - propMap.put(propName, currProperty); - } - - // TODO add logging - // System.out.println(m.getReturnType()); - if (m.getName().startsWith("get") && m.getParameterTypes().length == 0) { - currProperty.getter = m; - } - else if (m.getName().startsWith("set") && m.getParameterTypes().length == 1 - && void.class.equals(m.getReturnType())) { - currProperty.setter = m; - } - - // Check for StoreAs Annotation - final StoreAs storeAsInstance = m.getAnnotation(StoreAs.class); - if (storeAsInstance != null) { - if (Utility.isNullOrEmpty(storeAsInstance.name())) { - throw new IllegalArgumentException(String.format( - "StoreAs Annotation found for property %s with empty value", currProperty.name)); - } - - if (currProperty.effectiveName != null && !currProperty.effectiveName.equals(currProperty.name) - && !currProperty.effectiveName.equals(storeAsInstance.name())) { - throw new IllegalArgumentException( - String.format( - "StoreAs Annotation found for both getter and setter for property %s with non equal values", - currProperty.name)); - } - - if (!currProperty.name.equals(storeAsInstance.name())) { - currProperty.effectiveName = storeAsInstance.name(); - } - } - } - - // Return only processable pairs - final ArrayList keysToRemove = new ArrayList(); - final ArrayList keysToAlter = new ArrayList(); - - for (final Entry e : propMap.entrySet()) { - if (!e.getValue().shouldProcess()) { - keysToRemove.add(e.getKey()); - continue; - } - - if (!Utility.isNullOrEmpty(e.getValue().effectiveName)) { - keysToAlter.add(e.getKey()); - } - else { - e.getValue().effectiveName = e.getValue().name; - } - } - - // remove all entries for keys that should not process - for (final String key : keysToRemove) { - propMap.remove(key); - } - - // Any store as properties should be re-stored into the hash under the efective name. - for (final String key : keysToAlter) { - final PropertyPair p = propMap.get(key); - propMap.remove(key); - propMap.put(p.effectiveName, p); - } - - return propMap; - } - - private Method getter = null; - private Method setter = null; - private String name = null; - String effectiveName = null; - - /** - * Reserved for internal use. Invokes the setter method on the specified instance parameter with the value of the - * {@link EntityProperty} deserialized as the appropriate type. - * - * @param prop - * The {@link EntityProperty} containing the value to pass to the setter on the instance. - * @param instance - * An instance of a class supporting this property with getter and setter methods of the - * appropriate name and parameter or return type. - * - * @throws IllegalArgumentException - * if the specified instance parameter is not an instance of the class - * or interface declaring the setter method (or of a subclass or implementor thereof). - * @throws IllegalAccessException - * if the setter method is inaccessible. - * @throws InvocationTargetException - * if the setter method throws an exception. - */ - protected void consumeTableProperty(final EntityProperty prop, final Object instance) - throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - if (prop.getEdmType() == EdmType.STRING) { - this.setter.invoke(instance, prop.getValueAsString()); - } - else if (prop.getEdmType() == EdmType.BINARY) { - if (this.setter.getParameterTypes()[0].equals(Byte[].class)) { - this.setter.invoke(instance, (Object) prop.getValueAsByteObjectArray()); - } - else { - this.setter.invoke(instance, prop.getValueAsByteArray()); - } - } - else if (prop.getEdmType() == EdmType.BOOLEAN) { - this.setter.invoke(instance, prop.getValueAsBoolean()); - } - else if (prop.getEdmType() == EdmType.DOUBLE) { - this.setter.invoke(instance, prop.getValueAsDouble()); - } - else if (prop.getEdmType() == EdmType.GUID) { - this.setter.invoke(instance, prop.getValueAsUUID()); - } - else if (prop.getEdmType() == EdmType.INT32) { - this.setter.invoke(instance, prop.getValueAsInteger()); - } - else if (prop.getEdmType() == EdmType.INT64) { - this.setter.invoke(instance, prop.getValueAsLong()); - } - else if (prop.getEdmType() == EdmType.DATE_TIME) { - this.setter.invoke(instance, prop.getValueAsDate()); - } - else { - throw new IllegalArgumentException(String.format("Property %s with Edm Type %s cannot be de-serialized.", - this.name, prop.getEdmType().toString())); - } - } - - /** - * Reserved for internal use. Generates an {@link EntityProperty} from the result of invoking the getter method for - * this property on the specified instance parameter. - * - * @param instance - * An instance of a class supporting this property with getter and setter methods of the - * appropriate name and parameter or return type. - * - * @return - * An {@link EntityProperty} with the data type and value returned by the invoked getter on the instance. - * - * @throws IllegalArgumentException - * if the specified instance parameter is not an instance of the class - * or interface declaring the getter method (or of a subclass or implementor thereof). - * @throws IllegalAccessException - * if the getter method is inaccessible. - * @throws InvocationTargetException - * if the getter method throws an exception. - */ - protected EntityProperty generateTableProperty(final Object instance) throws IllegalArgumentException, - IllegalAccessException, InvocationTargetException { - final Class getType = this.getter.getReturnType(); - Object val = this.getter.invoke(instance, (Object[]) null); - - if (getType.equals(byte[].class)) { - return val != null ? new EntityProperty((byte[]) val) : new EntityProperty(EdmType.BINARY); - } - else if (getType.equals(Byte[].class)) { - return val != null ? new EntityProperty((Byte[]) val) : new EntityProperty(EdmType.BINARY); - } - else if (getType.equals(String.class)) { - return val != null ? new EntityProperty((String) val) : new EntityProperty(EdmType.STRING); - } - else if (getType.equals(boolean.class) || getType.equals(Boolean.class)) { - return val != null ? new EntityProperty((Boolean) val) : new EntityProperty(EdmType.BOOLEAN); - } - else if (getType.equals(double.class) || getType.equals(Double.class)) { - return val != null ? new EntityProperty((Double) val) : new EntityProperty(EdmType.DOUBLE); - } - else if (getType.equals(UUID.class)) { - return val != null ? new EntityProperty((UUID) val) : new EntityProperty(EdmType.GUID); - } - else if (getType.equals(int.class) || getType.equals(Integer.class)) { - return val != null ? new EntityProperty((Integer) val) : new EntityProperty(EdmType.INT32); - } - else if (getType.equals(long.class) || getType.equals(Long.class)) { - return val != null ? new EntityProperty((Long) val) : new EntityProperty(EdmType.INT64); - } - else if (getType.equals(Date.class)) { - return val != null ? new EntityProperty((Date) val) : new EntityProperty(EdmType.DATE_TIME); - } - else { - throw new IllegalArgumentException(String.format("Property %s with return type %s cannot be serialized.", - this.getter.getName(), this.getter.getReturnType())); - } - } - - /** - * Reserved for internal use. A utility function that returns true if this property is accessible - * through reflection. - * - * @return - */ - protected boolean shouldProcess() { - if (Utility.isNullOrEmpty(this.name) || this.getter == null || this.getter.isAnnotationPresent(Ignore.class) - || this.setter == null || this.setter.isAnnotationPresent(Ignore.class) - || (!this.getter.getReturnType().equals(this.setter.getParameterTypes()[0]))) { - return false; - } - - // TODO add logging - // System.out.println("Valid property " + this.name + " Storing as " + this.effectiveName); - return true; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/QueryTableOperation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/QueryTableOperation.java deleted file mode 100644 index 48a01577e8084..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/QueryTableOperation.java +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.text.ParseException; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * A class that extends {@link TableOperation} to implement a query to retrieve a single table entity. To execute a - * {@link QueryTableOperation} instance, call the execute method on a {@link CloudTableClient} instance. - * This operation can be executed directly or as part of a {@link TableBatchOperation}. If the - * {@link QueryTableOperation} returns an entity result, it is stored in the corresponding {@link TableResult} returned - * by the execute method. - */ -public class QueryTableOperation extends TableOperation { - private EntityResolver resolver; - - private Class clazzType; - - private String partitionKey; - - private String rowKey; - - /** - * Default constructor. - */ - protected QueryTableOperation() { - super(null, TableOperationType.RETRIEVE); - } - - /** - * Constructs a {@link QueryTableOperation} instance to retrieve a single table entity with the specified partition - * key and row key. - * - * @param partitionKey - * A String containing the PartitionKey value for the entity. - * @param rowKey - * A String containing the RowKey value for the entity. - */ - QueryTableOperation(final String partitionKey, final String rowKey) { - super(null, TableOperationType.RETRIEVE); - Utility.assertNotNull("partitionKey", partitionKey); - this.partitionKey = partitionKey; - this.rowKey = rowKey; - } - - /** - * Gets the PartitionKey value for the entity to retrieve. - * - * @return - * A String containing the PartitionKey value for the entity. - */ - public String getPartitionKey() { - return this.partitionKey; - } - - /** - * Gets the resolver to project the entity retrieved as a particular type. - * - * @return - * The {@link EntityResolver} instance. - */ - public EntityResolver getResolver() { - return this.resolver; - } - - /** - * Gets the RowKey value for the entity to retrieve. - * - * @return - * A String containing the RowKey value for the entity. - */ - public String getRowKey() { - return this.rowKey; - } - - /** - * Reserved for internal use. Gets the class type of the entity returned by the query. - * - * @return - * The java.lang.Class implementing {@link TableEntity} that represents the entity type for the - * query. - */ - protected Class getClazzType() { - return this.clazzType; - } - - /** - * Reserved for internal use. Parses the query table operation response into a {@link TableResult} to return. - * - * @param xmlr - * An XMLStreamReader containing the response to the query operation. - * @param httpStatusCode - * The HTTP status code returned from the operation request. - * @param etagFromHeader - * The String containing the Etag returned with the operation response. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. - * - * @return - * The {@link TableResult} representing the result of the query operation. - * - * @throws XMLStreamException - * if an error occurs accessing the XMLStreamReader. - * @throws ParseException - * if an error occurs in parsing the response. - * @throws InstantiationException - * if an error occurs in object construction. - * @throws IllegalAccessException - * if an error occurs in reflection on an object type. - * @throws StorageException - * if an error occurs in the storage operation. - */ - @Override - protected TableResult parseResponse(final XMLStreamReader xmlr, final int httpStatusCode, - final String etagFromHeader, final OperationContext opContext) throws XMLStreamException, ParseException, - InstantiationException, IllegalAccessException, StorageException { - return AtomPubParser.parseSingleOpResponse(xmlr, httpStatusCode, this.getClazzType(), this.getResolver(), - opContext); - } - - /** - * Reserved for internal use. Performs a retrieve operation on the specified table, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Storage Service REST API to execute this table operation, using the Table service - * endpoint and storage account credentials in the {@link CloudTableClient} object. - * - * @param client - * A {@link CloudTableClient} instance specifying the Table service endpoint and storage account - * credentials to use. - * @param tableName - * A String containing the name of the table to query. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * A {@link TableResult} containing the results of executing the query operation. - * - * @throws StorageException - * if an error occurs in the storage operation. - */ - protected TableResult performRetrieve(final CloudTableClient client, final String tableName, - final TableRequestOptions options, final OperationContext opContext) throws StorageException { - final boolean isTableEntry = TableConstants.TABLES_SERVICE_TABLES_NAME.equals(tableName); - if (this.getClazzType() != null) { - Utility.checkNullaryCtor(this.getClazzType()); - } - else { - Utility.assertNotNull("Query requires a valid class type or resolver.", this.getResolver()); - } - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public TableResult execute(final CloudTableClient client, final QueryTableOperation operation, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = TableRequest.query(client.getTransformedEndPoint(opContext), - tableName, generateRequestIdentity(isTableEntry, operation.getPartitionKey(), false), - options.getTimeoutIntervalInMs(), null/* Query Builder */, null/* Continuation Token */, - options, opContext); - this.setConnection(request); - - this.signTableRequest(client, request, -1L, opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { - // Parse response for updates - InputStream inStream = request.getInputStream(); - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream); - TableResult res = null; - - res = AtomPubParser.parseSingleOpResponse(xmlr, this.getResult().getStatusCode(), - operation.getClazzType(), operation.getResolver(), opContext); - - return res; - } - else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { - // Empty result - return new TableResult(this.getResult().getStatusCode()); - } - else { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - } - }; - - return ExecutionEngine.executeWithRetry(client, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Reserved for internal use. Sets the class type of the entity returned by the query. - * - * @param clazzType - * The java.lang.Class implementing {@link TableEntity} that represents the entity type for - * the query. - */ - protected void setClazzType(final Class clazzType) { - Utility.assertNotNull("clazzType", clazzType); - Utility.checkNullaryCtor(clazzType); - this.clazzType = clazzType; - } - - /** - * Reserved for internal use. Sets the PartitionKey value for the entity to retrieve. - * - * @param partitionKey - * A String containing the PartitionKey value for the entity. - */ - protected void setPartitionKey(final String partitionKey) { - this.partitionKey = partitionKey; - } - - /** - * Reserved for internal use. Sets the resolver to project the entity retrieved as a particular type. - * - * @param resolver - * The {@link EntityResolver} instance to use. - */ - protected void setResolver(final EntityResolver resolver) { - Utility.assertNotNull("Query requires a valid class type or resolver.", resolver); - this.resolver = resolver; - } - - /** - * Reserved for internal use. Sets the RowKey value for the entity to retrieve. - * - * @param rowKey - * A String containing the RowKey value for the entity. - */ - protected void setRowKey(final String rowKey) { - this.rowKey = rowKey; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/SharedAccessTablePermissions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/SharedAccessTablePermissions.java deleted file mode 100644 index 6ed1e001e94dc..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/SharedAccessTablePermissions.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import java.util.EnumSet; - -/** - * Specifies the set of possible permissions for a shared access table policy. - */ -public enum SharedAccessTablePermissions { - - /** - * No shared access granted. - */ - NONE((byte) 0x0), - - /** - * Permission to query entities granted. - */ - QUERY((byte) 0x1), - - /** - * Permission to add entities granted. - */ - ADD((byte) 0x2), - - /** - * Permission to modify entities granted. - */ - UPDATE((byte) 0x4), - - /** - * Permission to delete entities granted. - */ - DELETE((byte) 0x8); - - /** - * Returns the enum set representing the shared access permissions for the specified byte value. - * - * @param value - * The byte value to convert to the corresponding enum set. - * @return A java.util.EnumSet object that contains the SharedAccessTablePermissions values - * corresponding to the specified byte value. - */ - protected static EnumSet fromByte(final byte value) { - final EnumSet retSet = EnumSet.noneOf(SharedAccessTablePermissions.class); - - if (value == QUERY.value) { - retSet.add(QUERY); - } - - if (value == ADD.value) { - retSet.add(ADD); - } - if (value == UPDATE.value) { - retSet.add(UPDATE); - } - if (value == DELETE.value) { - retSet.add(DELETE); - } - - return retSet; - } - - /** - * Returns the value of this enum. - */ - private byte value; - - /** - * Sets the value of this enum. - * - * @param val - * The value being assigned. - */ - SharedAccessTablePermissions(final byte val) { - this.value = val; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/SharedAccessTablePolicy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/SharedAccessTablePolicy.java deleted file mode 100644 index 4bca919332cac..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/SharedAccessTablePolicy.java +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import java.util.Date; -import java.util.EnumSet; - -import com.microsoft.windowsazure.services.core.storage.Constants; - -/** - * Represents a shared access policy, which specifies the start time, expiry time, and permissions for a shared access - * signature. - */ -public final class SharedAccessTablePolicy { - - /** - * Assigns shared access permissions using the specified permissions string. - * - * @param value - * A String that represents the shared access permissions. The string must contain one or - * more of the following values. Note that they must be lower case, and the order that they are specified must - * be in the order of "rwdl". - *

    - *
  • d: Delete access.
  • - *
  • l: List access.
  • - *
  • r: Read access.
  • - *
  • w: Write access.
  • - *
- * - * @return A java.util.EnumSet object that contains {@link SharedAccessTablePermissions} values that - * represents the set of shared access permissions. - */ - public static EnumSet permissionsFromString(final String value) { - final char[] chars = value.toCharArray(); - final EnumSet retSet = EnumSet.noneOf(SharedAccessTablePermissions.class); - - for (final char c : chars) { - switch (c) { - case 'r': - retSet.add(SharedAccessTablePermissions.QUERY); - break; - case 'a': - retSet.add(SharedAccessTablePermissions.ADD); - break; - case 'u': - retSet.add(SharedAccessTablePermissions.UPDATE); - break; - case 'd': - retSet.add(SharedAccessTablePermissions.DELETE); - break; - default: - throw new IllegalArgumentException("value"); - } - } - - return retSet; - } - - /** - * Converts the permissions specified for the shared access policy to a string. - * - * @param permissions - * A set of {@link SharedAccessTablePermissions} objects that represent the shared access permissions. - * - * @return A String that represents the shared access permissions in the "rwdl" format, which is - * described at {@link SharedAccessTablePolicy#permissionsFromString(String)}. - */ - public static String permissionsToString(final EnumSet permissions) { - if (permissions == null) { - return Constants.EMPTY_STRING; - } - - // The service supports a fixed order => rwdl - final StringBuilder builder = new StringBuilder(); - - if (permissions.contains(SharedAccessTablePermissions.QUERY)) { - builder.append("r"); - } - - if (permissions.contains(SharedAccessTablePermissions.ADD)) { - builder.append("a"); - } - - if (permissions.contains(SharedAccessTablePermissions.UPDATE)) { - builder.append("u"); - } - - if (permissions.contains(SharedAccessTablePermissions.DELETE)) { - builder.append("d"); - } - - return builder.toString(); - } - - /** - * The permissions for a shared access signature associated with this shared access policy. - */ - private EnumSet permissions; - - /** - * The expiry time for a shared access signature associated with this shared access policy. - */ - private Date sharedAccessExpiryTime; - - /** - * The start time for a shared access signature associated with this shared access policy. - */ - private Date sharedAccessStartTime; - - /** - * Creates an instance of the SharedAccessTablePolicy class. - * */ - public SharedAccessTablePolicy() { - // Empty Default Ctor - } - - /** - * Gets the permissions for a shared access signature associated with this shared access policy. - * - * @return A java.util.EnumSet object that contains {@link SharedAccessTablePermissions} values that - * represents the set of shared access permissions. - */ - public EnumSet getPermissions() { - return this.permissions; - } - - /** - * Gets the expiry time for a shared access signature associated with this shared access policy. - * - * @return A Date object that contains the shared access signature expiry time. - */ - public Date getSharedAccessExpiryTime() { - return this.sharedAccessExpiryTime; - } - - /** - * Gets the start time for a shared access signature associated with this shared access policy. - * - * @return A Date object that contains the shared access signature start time. - */ - public Date getSharedAccessStartTime() { - return this.sharedAccessStartTime; - } - - /** - * Sets the permissions for a shared access signature associated with this shared access policy. - * - * @param permissions - * The permissions, represented by a java.util.EnumSet object that contains - * {@link SharedAccessTablePermissions} values, to set for the shared access signature. - */ - public void setPermissions(final EnumSet permissions) { - this.permissions = permissions; - } - - /** - * Sets the expiry time for a shared access signature associated with this shared access policy. - * - * @param sharedAccessExpiryTime - * The expiry time to set for the shared access signature. - */ - public void setSharedAccessExpiryTime(final Date sharedAccessExpiryTime) { - this.sharedAccessExpiryTime = sharedAccessExpiryTime; - } - - /** - * Sets the start time for a shared access signature associated with this shared access policy. - * - * @param sharedAccessStartTime - * The start time to set for the shared access signature. - */ - public void setSharedAccessStartTime(final Date sharedAccessStartTime) { - this.sharedAccessStartTime = sharedAccessStartTime; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/StoreAs.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/StoreAs.java deleted file mode 100644 index 1f80c27122fdc..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/StoreAs.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * An annotation used to override the name a property is serialized and deserialized with using reflection. Use this - * annotation to specify the property name to associate with the data stored by a setter method or retrieved by a getter - * method in a class implementing {@link TableEntity} that uses reflection-based serialization and deserialization. Note - * that the names "PartitionKey", "RowKey", "Timestamp", and "Etag" are reserved and will be ignored if set with the - * @StoreAs annotation. - *

- * Example: - *

- * @StoreAs(name = "EntityPropertyName")
public String getObjectPropertyName() { ... }
- *

- * @StoreAs(name = "EntityPropertyName")
public void setObjectPropertyName(String name) { ... }
- *

- * This example shows how the methods that would get and set an entity property named ObjectPropertyName in the - * default case can be annotated to get and set an entity property named EntityPropertyName. See the - * documentation for {@link TableServiceEntity} for more information on using reflection-based serialization and - * deserialization. - * - * @see Ignore - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Documented -public @interface StoreAs { - public String name(); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableAccessPolicyResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableAccessPolicyResponse.java deleted file mode 100644 index 31b35dc81bf29..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableAccessPolicyResponse.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import java.io.InputStream; -import java.text.ParseException; - -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.AccessPolicyResponseBase; -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * RESERVED FOR INTERNAL USE. A class used to parse SharedAccessPolicies from an input stream. - */ -final class TableAccessPolicyResponse extends AccessPolicyResponseBase { - - /** - * Initializes the AccessPolicyResponse object - * - * @param stream - * the input stream to read error details from. - */ - public TableAccessPolicyResponse(final InputStream stream) { - super(stream); - } - - /** - * Populates the object from the XMLStreamReader, reader must be at Start element of AccessPolicy. - * - * @param xmlr - * the XMLStreamReader object - * @throws XMLStreamException - * if there is a parsing exception - * @throws ParseException - * if a date value is not correctly encoded - */ - @Override - protected SharedAccessTablePolicy readPolicyFromXML(final XMLStreamReader xmlr) throws XMLStreamException, - ParseException { - int eventType = xmlr.getEventType(); - - xmlr.require(XMLStreamConstants.START_ELEMENT, null, Constants.ACCESS_POLICY); - final SharedAccessTablePolicy retPolicy = new SharedAccessTablePolicy(); - - while (xmlr.hasNext()) { - eventType = xmlr.next(); - - if (eventType == XMLStreamConstants.START_ELEMENT || eventType == XMLStreamConstants.END_ELEMENT) { - final String name = xmlr.getName().toString(); - - if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.PERMISSION)) { - retPolicy.setPermissions(SharedAccessTablePolicy.permissionsFromString(Utility - .readElementFromXMLReader(xmlr, Constants.PERMISSION))); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.START)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.START); - retPolicy.setSharedAccessStartTime(Utility.parseISO8061LongDateFromString(tempString)); - } - else if (eventType == XMLStreamConstants.START_ELEMENT && name.equals(Constants.EXPIRY)) { - final String tempString = Utility.readElementFromXMLReader(xmlr, Constants.EXPIRY); - retPolicy.setSharedAccessExpiryTime(Utility.parseISO8061LongDateFromString(tempString)); - } - else if (eventType == XMLStreamConstants.END_ELEMENT && name.equals(Constants.ACCESS_POLICY)) { - break; - } - } - } - - xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.ACCESS_POLICY); - return retPolicy; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableBatchOperation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableBatchOperation.java deleted file mode 100644 index cef17a1c030b7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableBatchOperation.java +++ /dev/null @@ -1,510 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.InputStream; -import java.io.StringReader; -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.UUID; - -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * A class which represents a batch operation. A batch operation is a collection of table operations which are executed - * by the Storage Service REST API as a single atomic operation, by invoking an Entity Group Transaction. - *

- * A batch operation may contain up to 100 individual table operations, with the requirement that each operation entity - * must have same partition key. A batch with a retrieve operation cannot contain any other operations. Note that the - * total payload of a batch operation is limited to 4MB. - */ -public class TableBatchOperation extends ArrayList { - private static final long serialVersionUID = -1192644463287355790L; - private boolean hasQuery = false; - private String partitionKey = null; - - /** - * Adds the table operation at the specified index in the batch operation ArrayList. - * - * @param index - * The index in the batch operation ArrayList to add the table operation at. - * @param element - * The {@link TableOperation} to add to the batch operation. - */ - @Override - public void add(final int index, final TableOperation element) { - Utility.assertNotNull("element", element); - - this.checkSingleQueryPerBatch(element); - - if (element.getOperationType() == TableOperationType.RETRIEVE) { - this.lockToPartitionKey(((QueryTableOperation) element).getPartitionKey()); - } - else { - this.lockToPartitionKey(element.getEntity().getPartitionKey()); - } - super.add(index, element); - } - - /** - * Adds the table operation to the batch operation ArrayList. - * - * @param element - * The {@link TableOperation} to add to the batch operation. - * @return - * true if the operation was added successfully. - */ - @Override - public boolean add(final TableOperation element) { - Utility.assertNotNull("element", element); - this.checkSingleQueryPerBatch(element); - if (element.getEntity() == null) { - // Query operation - this.lockToPartitionKey(((QueryTableOperation) element).getPartitionKey()); - } - else { - this.lockToPartitionKey(element.getEntity().getPartitionKey()); - } - - return super.add(element); - } - - /** - * Adds the collection of table operations to the batch operation ArrayList starting at the specified - * index. - * - * @param index - * The index in the batch operation ArrayList to add the table operation at. - * @param c - * The collection of {@link TableOperation} objects to add to the batch operation. - * @return - * true if the operations were added successfully. - */ - @Override - public boolean addAll(final int index, final java.util.Collection c) { - for (final TableOperation operation : c) { - Utility.assertNotNull("operation", operation); - this.checkSingleQueryPerBatch(operation); - - if (operation.getEntity() == null) { - // Query operation - this.lockToPartitionKey(((QueryTableOperation) operation).getPartitionKey()); - } - else { - this.lockToPartitionKey(operation.getEntity().getPartitionKey()); - } - } - - return super.addAll(index, c); - } - - /** - * Adds the collection of table operations to the batch operation ArrayList. - * - * @param c - * The collection of {@link TableOperation} objects to add to the batch operation. - * @return - * true if the operations were added successfully. - */ - @Override - public boolean addAll(final java.util.Collection c) { - for (final TableOperation operation : c) { - Utility.assertNotNull("operation", operation); - this.checkSingleQueryPerBatch(operation); - - if (operation.getEntity() == null) { - // Query operation - this.lockToPartitionKey(((QueryTableOperation) operation).getPartitionKey()); - } - else { - this.lockToPartitionKey(operation.getEntity().getPartitionKey()); - } - } - - return super.addAll(c); - } - - /** - * Clears all table operations from the batch operation. - */ - @Override - public void clear() { - super.clear(); - checkResetEntityLocks(); - } - - /** - * Adds a table operation to delete the specified entity to the batch operation. - * - * @param entity - * The {@link TableEntity} to delete. - */ - public void delete(final TableEntity entity) { - this.lockToPartitionKey(entity.getPartitionKey()); - this.add(TableOperation.delete(entity)); - } - - /** - * Adds a table operation to insert the specified entity to the batch operation. - * - * @param entity - * The {@link TableEntity} to insert. - */ - public void insert(final TableEntity entity) { - this.lockToPartitionKey(entity.getPartitionKey()); - this.add(TableOperation.insert(entity)); - } - - /** - * Adds a table operation to insert or merge the specified entity to the batch operation. - * - * @param entity - * The {@link TableEntity} to insert if not found or to merge if it exists. - */ - public void insertOrMerge(final TableEntity entity) { - this.lockToPartitionKey(entity.getPartitionKey()); - this.add(TableOperation.insertOrMerge(entity)); - } - - /** - * Adds a table operation to insert or replace the specified entity to the batch operation. - * - * @param entity - * The {@link TableEntity} to insert if not found or to replace if it exists. - */ - public void insertOrReplace(final TableEntity entity) { - this.lockToPartitionKey(entity.getPartitionKey()); - this.add(TableOperation.insertOrReplace(entity)); - } - - /** - * Adds a table operation to merge the specified entity to the batch operation. - * - * @param entity - * The {@link TableEntity} to merge. - */ - public void merge(final TableEntity entity) { - this.lockToPartitionKey(entity.getPartitionKey()); - this.add(TableOperation.merge(entity)); - } - - /** - * Adds a table operation to retrieve an entity of the specified class type with the specified PartitionKey and - * RowKey to the batch operation. - * - * @param partitionKey - * A String containing the PartitionKey of the entity to retrieve. - * @param rowKey - * A String containing the RowKey of the entity to retrieve. - * @param clazzType - * The class of the {@link TableEntity} type for the entity to retrieve. - */ - public void retrieve(final String partitionKey, final String rowKey, final Class clazzType) { - this.lockToPartitionKey(partitionKey); - this.add(TableOperation.retrieve(partitionKey, rowKey, clazzType)); - } - - /** - * Adds a table operation to retrieve an entity of the specified class type with the specified PartitionKey and - * RowKey to the batch operation. - * - * @param partitionKey - * A String containing the PartitionKey of the entity to retrieve. - * @param rowKey - * A String containing the RowKey of the entity to retrieve. - * @param resolver - * The {@link EntityResolver} implementation to project the entity to retrieve as a particular type in - * the result. - */ - public void retrieve(final String partitionKey, final String rowKey, final EntityResolver resolver) { - this.lockToPartitionKey(partitionKey); - this.add(TableOperation.retrieve(partitionKey, rowKey, resolver)); - } - - /** - * Removes the table operation at the specified index from the batch operation. - * - * @param index - * The index in the ArrayList of the table operation to remove from the batch operation. - */ - @Override - public TableOperation remove(int index) { - TableOperation op = super.remove(index); - checkResetEntityLocks(); - return op; - } - - /** - * Removes the specified Object from the batch operation. - * - * @param o - * The Object to remove from the batch operation. - * @return - * true if the object was removed successfully. - */ - @Override - public boolean remove(Object o) { - boolean ret = super.remove(o); - checkResetEntityLocks(); - return ret; - } - - /** - * Removes all elements of the specified collection from the batch operation. - * - * @param c - * The collection of elements to remove from the batch operation. - * @return - * true if the objects in the collection were removed successfully. - */ - @Override - public boolean removeAll(java.util.Collection c) { - boolean ret = super.removeAll(c); - checkResetEntityLocks(); - return ret; - } - - /** - * Adds a table operation to replace the specified entity to the batch operation. - * - * @param entity - * The {@link TableEntity} to replace. - */ - public void replace(final TableEntity entity) { - this.lockToPartitionKey(entity.getPartitionKey()); - this.add(TableOperation.replace(entity)); - } - - /** - * Reserved for internal use. Clears internal fields when the batch operation is empty. - */ - private void checkResetEntityLocks() { - if (this.size() == 0) { - this.partitionKey = null; - this.hasQuery = false; - } - } - - /** - * Reserved for internal use. Verifies that the batch operation either contains no retrieve operations, or contains - * only a single retrieve operation. - * - * @param op - * The {@link TableOperation} to be added if the verification succeeds. - */ - private void checkSingleQueryPerBatch(final TableOperation op) { - // if this has a query then no other operations can be added. - if (this.hasQuery) { - throw new IllegalArgumentException( - "A batch transaction with a retrieve operation cannot contain any other operations."); - } - - if (op.opType == TableOperationType.RETRIEVE) { - if (this.size() > 0) { - throw new IllegalArgumentException( - "A batch transaction with a retrieve operation cannot contain any other operations."); - } - else { - this.hasQuery = true; - } - } - } - - /** - * Reserved for internal use. Verifies that the specified PartitionKey value matches the value in the batch - * operation. - * - * @param partitionKey - * The String containing the PartitionKey value to check. - */ - private void lockToPartitionKey(final String partitionKey) { - if (this.partitionKey == null) { - this.partitionKey = partitionKey; - } - else { - if (partitionKey.length() != partitionKey.length() || !this.partitionKey.equals(partitionKey)) { - throw new IllegalArgumentException("All entities in a given batch must have the same partition key."); - } - } - } - - /** - * Reserved for internal use. Executes this batch operation on the specified table, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Storage Service REST API to execute this batch operation, using the Table service - * endpoint and storage account credentials in the {@link CloudTableClient} object. - * - * @param client - * A {@link CloudTableClient} instance specifying the Table service endpoint and storage account - * credentials to use. - * @param tableName - * A String containing the name of the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * An ArrayList of {@link TableResult} containing the results of executing the operation. - * - * @throws StorageException - * if an error occurs in the storage operation. - */ - protected ArrayList execute(final CloudTableClient client, final String tableName, - final TableRequestOptions options, final OperationContext opContext) throws StorageException { - - Utility.assertNotNullOrEmpty("TableName", tableName); - - if (this.size() == 0) { - throw new IllegalArgumentException("Cannot Execute an empty batch operation"); - } - - final StorageOperation> impl = new StorageOperation>( - options) { - @Override - public ArrayList execute(final CloudTableClient client, final TableBatchOperation batch, - final OperationContext opContext) throws Exception { - final String batchID = String.format("batch_%s", UUID.randomUUID().toString()); - final String changeSet = String.format("changeset_%s", UUID.randomUUID().toString()); - - final HttpURLConnection request = TableRequest.batch(client.getTransformedEndPoint(opContext), - options.getTimeoutIntervalInMs(), batchID, null, options, opContext); - this.setConnection(request); - - this.signTableRequest(client, request, -1L, opContext); - - MimeHelper.writeBatchToStream(request.getOutputStream(), tableName, batch, batchID, changeSet, - opContext); - - final InputStream streamRef = ExecutionEngine.getInputStream(request, opContext, this.getResult()); - ArrayList responseParts = null; - - final String contentType = request.getHeaderField(Constants.HeaderConstants.CONTENT_TYPE); - - final String[] headerVals = contentType.split("multipart/mixed; boundary="); - if (headerVals == null || headerVals.length != 2) { - throw new StorageException(StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, - "An incorrect Content-type was returned from the server.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, null); - } - - responseParts = MimeHelper.readBatchResponseStream(streamRef, headerVals[1], opContext); - - ExecutionEngine.getResponseCode(this.getResult(), request, opContext); - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { - this.setNonExceptionedRetryableFailure(true); - return null; - } - - final ArrayList result = new ArrayList(); - for (int m = 0; m < batch.size(); m++) { - final TableOperation currOp = batch.get(m); - final MimePart currMimePart = responseParts.get(m); - - boolean failFlag = false; - - // Validate response - if (currOp.opType == TableOperationType.INSERT) { - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - throw new TableServiceException(currMimePart.httpStatusCode, - currMimePart.httpStatusMessage, currOp, new StringReader(currMimePart.payload)); - } - - // Insert should receive created. - if (currMimePart.httpStatusCode != HttpURLConnection.HTTP_CREATED) { - failFlag = true; - } - } - else if (currOp.opType == TableOperationType.RETRIEVE) { - if (currMimePart.httpStatusCode == HttpURLConnection.HTTP_NOT_FOUND) { - // Empty result - result.add(new TableResult(currMimePart.httpStatusCode)); - return result; - } - - // Point query should receive ok. - if (currMimePart.httpStatusCode != HttpURLConnection.HTTP_OK) { - failFlag = true; - } - } - else { - // Validate response code. - if (currMimePart.httpStatusCode == HttpURLConnection.HTTP_NOT_FOUND) { - // Throw so as to not retry. - throw new TableServiceException(currMimePart.httpStatusCode, - currMimePart.httpStatusMessage, currOp, new StringReader(currMimePart.payload)); - } - - if (currMimePart.httpStatusCode != HttpURLConnection.HTTP_NO_CONTENT) { - // All others should receive no content. (delete, merge, upsert etc) - failFlag = true; - } - } - - if (failFlag) { - TableServiceException potentiallyRetryableException = new TableServiceException( - currMimePart.httpStatusCode, currMimePart.httpStatusMessage, currOp, new StringReader( - currMimePart.payload)); - potentiallyRetryableException.setRetryable(true); - throw potentiallyRetryableException; - } - - XMLStreamReader xmlr = null; - - if (currOp.opType == TableOperationType.INSERT || currOp.opType == TableOperationType.RETRIEVE) { - xmlr = Utility.createXMLStreamReaderFromReader(new StringReader(currMimePart.payload)); - } - - result.add(currOp.parseResponse(xmlr, currMimePart.httpStatusCode, - currMimePart.headers.get(TableConstants.HeaderConstants.ETAG), opContext)); - } - - return result; - } - }; - - return ExecutionEngine.executeWithRetry(client, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Reserved for internal use. Removes all the table operations at indexes in the specified range from the batch - * operation ArrayList. - * - * @param fromIndex - * The inclusive lower bound of the range of {@link TableOperation} objects to remove from the batch - * operation ArrayList. - * @param toIndex - * The exclusive upper bound of the range of {@link TableOperation} objects to remove from the batch - * operation ArrayList. - */ - @Override - protected void removeRange(int fromIndex, int toIndex) { - super.removeRange(fromIndex, toIndex); - checkResetEntityLocks(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableConstants.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableConstants.java deleted file mode 100644 index 2822c5e47856e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableConstants.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -/** - * Holds the constants used for the Table Service. - */ -public final class TableConstants { - /** - * The constants used in HTML header fields for Table service requests. - */ - public static class HeaderConstants { - /** - * The ETag header field label. - */ - public static final String ETAG = "ETag"; - - /** - * The Accept header value to send. - */ - public static final String ACCEPT_TYPE = "application/atom+xml,application/xml"; - - /** - * The Content-Type header value to send for single operations. - */ - public static final String ATOMPUB_TYPE = "application/atom+xml"; - - /** - * The Content-Type header value to send for batch operations. - */ - public static final String MULTIPART_MIXED_FORMAT = "multipart/mixed; boundary=%s"; - - /** - * The DataServiceVersion header field label. - */ - public static final String DATA_SERVICE_VERSION = "DataServiceVersion"; - - /** - * The DataServiceVersion header value to send. - */ - public static final String DATA_SERVICE_VERSION_VALUE = "1.0;NetFx"; - - /** - * The MaxDataServiceVersion header field label. - */ - public static final String MAX_DATA_SERVICE_VERSION = "MaxDataServiceVersion"; - - /** - * The MaxDataServiceVersion header value to send. - */ - public static final String MAX_DATA_SERVICE_VERSION_VALUE = "2.0;NetFx"; - } - - /** - * Default client side timeout, in milliseconds, for table clients. - */ - public static final int TABLE_DEFAULT_TIMEOUT_IN_MS = 60 * 1000; - - /** - * Stores the header prefix for continuation information. - */ - public static final String TABLE_SERVICE_PREFIX_FOR_TABLE_CONTINUATION = "x-ms-continuation-"; - - /** - * Stores the header suffix for the next partition key. - */ - public static final String TABLE_SERVICE_NEXT_PARTITION_KEY = "NextPartitionKey"; - - /** - * Stores the header suffix for the next row key. - */ - public static final String TABLE_SERVICE_NEXT_ROW_KEY = "NextRowKey"; - - /** - * Stores the header suffix for the next marker. - */ - public static final String TABLE_SERVICE_NEXT_MARKER = "NextMarker"; - - /** - * Stores the table suffix for the next table name. - */ - public static final String TABLE_SERVICE_NEXT_TABLE_NAME = "NextTableName"; - - /** - * The name of the partition key property. - */ - public static final String PARTITION_KEY = "PartitionKey"; - - /** - * The name of the row key property. - */ - public static final String ROW_KEY = "RowKey"; - - /** - * The name of the Timestamp property. - */ - public static final String TIMESTAMP = "Timestamp"; - - /** - * The name of the special table used to store tables. - */ - public static final String TABLES_SERVICE_TABLES_NAME = "Tables"; - - /** - * The name of the property that stores the table name. - */ - public static final String TABLE_NAME = "TableName"; - - /** - * The query filter clause name. - */ - public static final String FILTER = "$filter"; - - /** - * The query top clause name. - */ - public static final String TOP = "$top"; - - /** - * The query select clause name. - */ - public static final String SELECT = "$select"; - - /** - * Private Default Constructor. - */ - private TableConstants() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableEntity.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableEntity.java deleted file mode 100644 index 702a42bb86f9c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableEntity.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.Date; -import java.util.HashMap; - -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * An interface required for table entity types. The {@link TableEntity} interface declares getter and setter methods - * for the common entity properties, and writeEntity and readEntity methods for serialization - * and deserialization of all entity properties using a property map. Create classes implementing {@link TableEntity} to - * customize property storage, retrieval, serialization and deserialization, and to provide additional custom logic for - * a table entity. - *

- * The Storage client library includes two implementations of {@link TableEntity} that provide for simple property - * access and serialization: - *

- * {@link DynamicTableEntity} implements {@link TableEntity} and provides a simple property map to store and retrieve - * properties. Use a {@link DynamicTableEntity} for simple access to entity properties when only a subset of properties - * are returned (for example, by a select clause in a query), or for when your query can return multiple entity types - * with different properties. You can also use this type to perform bulk table updates of heterogeneous entities without - * losing property information. - *

- * {@link TableServiceEntity} is an implementation of {@link TableEntity} that uses reflection-based serialization and - * deserialization behavior in its writeEntity and readEntity methods. - * {@link TableServiceEntity}-derived classes with methods that follow a convention for types and naming are serialized - * and deserialized automatically. - *

- * Any class that implements {@link TableEntity} can take advantage of the automatic reflection-based serialization and - * deserialization behavior in {@link TableServiceEntity} by invoking the static methods - * TableServiceEntity.readEntityWithReflection in readEntity and - * TableServiceEntity.writeEntityWithReflection in writeEntity. The class must provide methods - * that follow the type and naming convention to be serialized and deserialized automatically. When both a getter method - * and setter method are found for a given property name and data type, then the appropriate method is invoked - * automatically to serialize or deserialize the data. The reflection code looks for getter and setter methods in pairs - * of the form - *

- * public type getPropertyName() { ... } - *

- * and - *

- * public void setPropertyName(type parameter) { ... } - *

- * where PropertyName is a property name for the table entity, and type is a Java type compatible with - * the EDM data type of the property. See the table in the class description for {@link TableServiceEntity} for a map of - * property types to their Java equivalents. The {@link StoreAs} annotation may be applied with a name - * attribute to specify a property name for reflection on getter and setter methods that do not follow the property name - * convention. Method names and the name attribute of {@link StoreAs} annotations are case sensitive for - * matching property names with reflection. Use the {@link Ignore} annotation to prevent methods from being used by - * reflection for automatic serialization and deserialization. Note that the names "PartitionKey", "RowKey", - * "Timestamp", and "Etag" are reserved and will be ignored if set with the {@link StoreAs} annotation in a subclass - * that uses the reflection methods. - *

- * - * @see TableServiceEntity - * @see DynamicTableEntity - */ -public interface TableEntity { - - /** - * Gets the Etag value for the entity. This value is used to determine if the table entity has changed since it was - * last read from Windows Azure storage. - * - * @return - * A String containing the Etag for the entity. - */ - public String getEtag(); - - /** - * Gets the PartitionKey value for the entity. - * - * @return - * A String containing the PartitionKey value for the entity. - */ - public String getPartitionKey(); - - /** - * Gets the RowKey value for the entity. - * - * @return - * A String containing the RowKey value for the entity. - */ - public String getRowKey(); - - /** - * Gets the Timestamp for the entity. - * - * @return - * A Date containing the Timestamp value for the entity. - */ - public Date getTimestamp(); - - /** - * Populates an instance of the object implementing {@link TableEntity} using the specified properties parameter, - * containing a map of String property names to {@link EntityProperty} data typed values. - * - * @param properties - * The java.util.HashMap of String to {@link EntityProperty} data typed values - * to use to populate the table entity instance. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * @throws StorageException - * if an error occurs during the operation. - */ - public void readEntity(HashMap properties, OperationContext opContext) - throws StorageException; - - /** - * Sets the Etag for the entity. - * - * @param etag - * The String containing the Etag to set for the entity. - */ - public void setEtag(String etag); - - /** - * Sets the PartitionKey value for the entity. - * - * @param partitionKey - * The String containing the PartitionKey value to set for the entity. - */ - public void setPartitionKey(String partitionKey); - - /** - * Sets the RowKey value for the entity. - * - * @param rowKey - * The String containing the RowKey value to set for the entity. - */ - public void setRowKey(String rowKey); - - /** - * Sets the Timestamp value for the entity. - * - * @param timeStamp - * The Date containing the Timestamp value to set for the entity. - */ - public void setTimestamp(Date timeStamp); - - /** - * Returns a map of String property names to {@link EntityProperty} data typed values - * that represents the serialized content of the table entity instance. - * - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * @return - * The java.util.HashMap of String property names to {@link EntityProperty} data - * typed values representing the properties of the table entity. - * - * @throws StorageException - * if an error occurs during the operation. - */ - public HashMap writeEntity(OperationContext opContext) throws StorageException; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableOperation.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableOperation.java deleted file mode 100644 index 81b030426817f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableOperation.java +++ /dev/null @@ -1,706 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.text.ParseException; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; - -/** - * A class which represents a single table operation. - *

- * Use the static factory methods to construct {@link TableOperation} instances for operations on tables that insert, - * update, merge, delete, replace or retrieve table entities. To execute a {@link TableOperation} instance, call the - * execute method on a {@link CloudTableClient} instance. A {@link TableOperation} may be executed directly - * or as part of a {@link TableBatchOperation}. If a {@link TableOperation} returns an entity result, it is stored in - * the corresponding {@link TableResult} returned by the execute method. - * - */ -public class TableOperation { - /** - * A static factory method returning a {@link TableOperation} instance to delete the specified entity from Windows - * Azure storage. To execute this {@link TableOperation} on a given table, call the - * {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance with the - * table name and the {@link TableOperation} as arguments. - * - * @param entity - * The object instance implementing {@link TableEntity} to associate with the operation. - * @return - * A new {@link TableOperation} instance to insert the table entity. - */ - public static TableOperation delete(final TableEntity entity) { - Utility.assertNotNull("Entity", entity); - Utility.assertNotNullOrEmpty("Entity Etag", entity.getEtag()); - return new TableOperation(entity, TableOperationType.DELETE); - } - - /** - * A static factory method returning a {@link TableOperation} instance to insert the specified entity into Windows - * Azure storage. To execute this {@link TableOperation} on a given table, call the - * {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance with the - * table name and the {@link TableOperation} as arguments. - * - * @param entity - * The object instance implementing {@link TableEntity} to associate with the operation. - * @return - * A new {@link TableOperation} instance to insert the table entity. - */ - public static TableOperation insert(final TableEntity entity) { - Utility.assertNotNull("Entity", entity); - return new TableOperation(entity, TableOperationType.INSERT); - } - - /** - * A static factory method returning a {@link TableOperation} instance to merge the specified entity into Windows - * Azure storage, or insert it if it does not exist. To execute this {@link TableOperation} on a given table, call - * the {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance with - * the table name and the {@link TableOperation} as arguments. - * - * @param entity - * The object instance implementing {@link TableEntity} to associate with the operation. - * @return - * A new {@link TableOperation} instance for inserting or merging the table entity. - */ - public static TableOperation insertOrMerge(final TableEntity entity) { - Utility.assertNotNull("Entity", entity); - return new TableOperation(entity, TableOperationType.INSERT_OR_MERGE); - } - - /** - * A static factory method returning a {@link TableOperation} instance to replace the specified entity in Windows - * Azure storage, or insert it if it does not exist. To execute this {@link TableOperation} on a given table, call - * the {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance with - * the table name and the {@link TableOperation} as arguments. - * - * @param entity - * The object instance implementing {@link TableEntity} to associate with the operation. - * @return - * A new {@link TableOperation} instance for inserting or replacing the table entity. - */ - public static TableOperation insertOrReplace(final TableEntity entity) { - Utility.assertNotNull("Entity", entity); - return new TableOperation(entity, TableOperationType.INSERT_OR_REPLACE); - } - - /** - * A static factory method returning a {@link TableOperation} instance to merge the specified table entity into - * Windows Azure storage. To execute this {@link TableOperation} on a given table, call the - * {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance with the - * table name and the {@link TableOperation} as arguments. - * - * @param entity - * The object instance implementing {@link TableEntity} to associate with the operation. - * @return - * A new {@link TableOperation} instance for merging the table entity. - */ - public static TableOperation merge(final TableEntity entity) { - Utility.assertNotNull("Entity", entity); - Utility.assertNotNullOrEmpty("Entity Etag", entity.getEtag()); - return new TableOperation(entity, TableOperationType.MERGE); - } - - /** - * A static factory method returning a {@link TableOperation} instance to retrieve the specified table entity and - * return it as the specified type. To execute this {@link TableOperation} on a given table, call the - * {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance with the - * table name and the {@link TableOperation} as arguments. - * - * @param partitionKey - * A String containing the PartitionKey value for the entity to retrieve. - * @param rowKey - * A String containing the RowKey value for the entity to retrieve. - * @param clazzType - * The class type of the table entity object to retrieve. - * @return - * A new {@link TableOperation} instance for retrieving the table entity. - */ - public static TableOperation retrieve(final String partitionKey, final String rowKey, - final Class clazzType) { - final QueryTableOperation retOp = new QueryTableOperation(partitionKey, rowKey); - retOp.setClazzType(clazzType); - return retOp; - } - - /** - * A static factory method returning a {@link TableOperation} instance to retrieve the specified table entity and - * return a projection of it using the specified resolver. To execute this {@link TableOperation} on a given table, - * call the {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance - * with the table name and the {@link TableOperation} as arguments. - * - * @param partitionKey - * A String containing the PartitionKey value for the entity to retrieve. - * @param rowKey - * A String containing the RowKey value for the entity to retrieve. - * @param resolver - * The implementation of {@link EntityResolver} to use to project the result entity as type T. - * @return - * A new {@link TableOperation} instance for retrieving the table entity. - */ - public static TableOperation retrieve(final String partitionKey, final String rowKey, - final EntityResolver resolver) { - final QueryTableOperation retOp = new QueryTableOperation(partitionKey, rowKey); - retOp.setResolver(resolver); - return retOp; - } - - /** - * A static factory method returning a {@link TableOperation} instance to replace the specified table entity. To - * execute this {@link TableOperation} on a given table, call the - * {@link CloudTableClient#execute(String, TableOperation)} method on a {@link CloudTableClient} instance with the - * table name and the {@link TableOperation} as arguments. - * - * @param entity - * The object instance implementing {@link TableEntity} to associate with the operation. - * @return - * A new {@link TableOperation} instance for replacing the table entity. - */ - public static TableOperation replace(final TableEntity entity) { - Utility.assertNotNullOrEmpty("Entity Etag", entity.getEtag()); - return new TableOperation(entity, TableOperationType.REPLACE); - } - - /** - * The table entity instance associated with the operation. - */ - TableEntity entity; - - /** - * The {@link TableOperationType} enumeration value for the operation type. - */ - TableOperationType opType = null; - - /** - * Nullary Default Constructor. - */ - protected TableOperation() { - // empty ctor - } - - /** - * Reserved for internal use. Constructs a {@link TableOperation} with the specified table entity and operation - * type. - * - * @param entity - * The object instance implementing {@link TableEntity} to associate with the operation. - * @param opType - * The {@link TableOperationType} enumeration value for the operation type. - */ - protected TableOperation(final TableEntity entity, final TableOperationType opType) { - this.entity = entity; - this.opType = opType; - } - - /** - * Reserved for internal use. Performs a delete operation on the specified table, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Delete - * Entity REST API to execute this table operation, using the Table service endpoint and storage account - * credentials in the {@link CloudTableClient} object. - * - * @param client - * A {@link CloudTableClient} instance specifying the Table service endpoint, storage account - * credentials, and any additional query parameters. - * @param tableName - * A String containing the name of the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * A {@link TableResult} containing the results of executing the operation. - * - * @throws StorageException - * if an error occurs in the storage operation. - */ - private TableResult performDelete(final CloudTableClient client, final String tableName, - final TableRequestOptions options, final OperationContext opContext) throws StorageException { - final boolean isTableEntry = TableConstants.TABLES_SERVICE_TABLES_NAME.equals(tableName); - final String tableIdentity = isTableEntry ? this.getEntity().writeEntity(opContext) - .get(TableConstants.TABLE_NAME).getValueAsString() : null; - - if (!isTableEntry) { - Utility.assertNotNullOrEmpty("Delete requires a valid ETag", this.getEntity().getEtag()); - Utility.assertNotNullOrEmpty("Delete requires a valid PartitionKey", this.getEntity().getPartitionKey()); - Utility.assertNotNullOrEmpty("Delete requires a valid RowKey", this.getEntity().getRowKey()); - } - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public TableResult execute(final CloudTableClient client, final TableOperation operation, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = TableRequest.delete(client.getTransformedEndPoint(opContext), - tableName, generateRequestIdentity(isTableEntry, tableIdentity, false), operation.getEntity() - .getEtag(), options.getTimeoutIntervalInMs(), null, options, opContext); - this.setConnection(request); - - this.signTableRequest(client, request, -1L, opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND - || this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - throw TableServiceException.generateTableServiceException(false, this.getResult(), operation, - request.getErrorStream()); - } - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { - throw TableServiceException.generateTableServiceException(true, this.getResult(), operation, - request.getErrorStream()); - } - - return operation.parseResponse(null, this.getResult().getStatusCode(), null, opContext); - } - }; - - return ExecutionEngine.executeWithRetry(client, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Reserved for internal use. Performs an insert operation on the specified table, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Insert Entity REST API to execute this table operation, using the Table service - * endpoint and storage account credentials in the {@link CloudTableClient} object. - * - * @param client - * A {@link CloudTableClient} instance specifying the Table service endpoint, storage account - * credentials, and any additional query parameters. - * @param tableName - * A String containing the name of the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * A {@link TableResult} containing the results of executing the operation. - * - * @throws StorageException - * if an error occurs in the storage operation. - */ - private TableResult performInsert(final CloudTableClient client, final String tableName, - final TableRequestOptions options, final OperationContext opContext) throws StorageException { - final boolean isTableEntry = TableConstants.TABLES_SERVICE_TABLES_NAME.equals(tableName); - final String tableIdentity = isTableEntry ? this.getEntity().writeEntity(opContext) - .get(TableConstants.TABLE_NAME).getValueAsString() : null; - - // Upserts need row key and partition key - if (!isTableEntry && this.opType != TableOperationType.INSERT) { - Utility.assertNotNullOrEmpty("Upserts require a valid PartitionKey", this.getEntity().getPartitionKey()); - Utility.assertNotNullOrEmpty("Upserts require a valid RowKey", this.getEntity().getRowKey()); - } - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public TableResult execute(final CloudTableClient client, final TableOperation operation, - final OperationContext opContext) throws Exception { - final HttpURLConnection request = TableRequest.insert(client.getTransformedEndPoint(opContext), - tableName, generateRequestIdentity(isTableEntry, tableIdentity, false), - operation.opType != TableOperationType.INSERT ? operation.getEntity().getEtag() : null, - operation.opType.getUpdateType(), options.getTimeoutIntervalInMs(), null, options, opContext); - this.setConnection(request); - - this.signTableRequest(client, request, -1L, opContext); - - AtomPubParser.writeSingleEntityToStream(operation.getEntity(), isTableEntry, request.getOutputStream(), - opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - if (operation.opType == TableOperationType.INSERT) { - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - throw TableServiceException.generateTableServiceException(false, this.getResult(), operation, - request.getErrorStream()); - } - - if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { - throw TableServiceException.generateTableServiceException(true, this.getResult(), operation, - request.getErrorStream()); - } - - InputStream inStream = request.getInputStream(); - TableResult res = null; - - final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream); - res = operation.parseResponse(xmlr, this.getResult().getStatusCode(), null, opContext); - - return res; - } - else { - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return operation.parseResponse(null, this.getResult().getStatusCode(), - request.getHeaderField(TableConstants.HeaderConstants.ETAG), opContext); - } - else { - throw TableServiceException.generateTableServiceException(true, this.getResult(), operation, - request.getErrorStream()); - } - } - } - }; - - return ExecutionEngine.executeWithRetry(client, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Reserved for internal use. Perform a merge operation on the specified table, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Merge Entity REST API to execute this table operation, using the Table service - * endpoint and storage account credentials in the {@link CloudTableClient} object. - * - * @param client - * A {@link CloudTableClient} instance specifying the Table service endpoint, storage account - * credentials, and any additional query parameters. - * @param tableName - * A String containing the name of the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * A {@link TableResult} containing the results of executing the operation. - * - * @throws StorageException - * if an error occurs in the storage operation. - */ - private TableResult performMerge(final CloudTableClient client, final String tableName, - final TableRequestOptions options, final OperationContext opContext) throws StorageException { - Utility.assertNotNullOrEmpty("Merge requires a valid ETag", this.getEntity().getEtag()); - Utility.assertNotNullOrEmpty("Merge requires a valid PartitionKey", this.getEntity().getPartitionKey()); - Utility.assertNotNullOrEmpty("Merge requires a valid RowKey", this.getEntity().getRowKey()); - - final StorageOperation impl = new StorageOperation( - options) { - @Override - public TableResult execute(final CloudTableClient client, final TableOperation operation, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = TableRequest.merge(client.getTransformedEndPoint(opContext), - tableName, generateRequestIdentity(false, null, false), operation.getEntity().getEtag(), - options.getTimeoutIntervalInMs(), null, options, opContext); - this.setConnection(request); - - this.signTableRequest(client, request, -1L, opContext); - - AtomPubParser.writeSingleEntityToStream(operation.getEntity(), false, request.getOutputStream(), - opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND - || this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - throw TableServiceException.generateTableServiceException(false, this.getResult(), operation, - request.getErrorStream()); - } - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return operation.parseResponse(null, this.getResult().getStatusCode(), - request.getHeaderField(TableConstants.HeaderConstants.ETAG), opContext); - } - else { - throw TableServiceException.generateTableServiceException(true, this.getResult(), operation, - request.getErrorStream()); - } - } - }; - - return ExecutionEngine.executeWithRetry(client, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Reserved for internal use. Perform an update operation on the specified table, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Storage Service REST API to execute this table operation, using the Table service - * endpoint and storage account credentials in the {@link CloudTableClient} object. - * - * @param client - * A {@link CloudTableClient} instance specifying the Table service endpoint, storage account - * credentials, and any additional query parameters. - * @param tableName - * A String containing the name of the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * A {@link TableResult} containing the results of executing the operation. - * - * @throws StorageException - * if an error occurs in the storage operation. - */ - private TableResult performUpdate(final CloudTableClient client, final String tableName, - final TableRequestOptions options, final OperationContext opContext) throws StorageException { - Utility.assertNotNullOrEmpty("Update requires a valid ETag", this.getEntity().getEtag()); - Utility.assertNotNullOrEmpty("Update requires a valid PartitionKey", this.getEntity().getPartitionKey()); - Utility.assertNotNullOrEmpty("Update requires a valid RowKey", this.getEntity().getRowKey()); - final StorageOperation impl = new StorageOperation( - options) { - @Override - public TableResult execute(final CloudTableClient client, final TableOperation operation, - final OperationContext opContext) throws Exception { - - final HttpURLConnection request = TableRequest.update(client.getTransformedEndPoint(opContext), - tableName, generateRequestIdentity(false, null, false), operation.getEntity().getEtag(), - options.getTimeoutIntervalInMs(), null, options, opContext); - this.setConnection(request); - - this.signTableRequest(client, request, -1L, opContext); - - AtomPubParser.writeSingleEntityToStream(operation.getEntity(), false, request.getOutputStream(), - opContext); - - ExecutionEngine.processRequest(request, opContext, this.getResult()); - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND - || this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { - throw TableServiceException.generateTableServiceException(false, this.getResult(), operation, - request.getErrorStream()); - } - - if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { - return operation.parseResponse(null, this.getResult().getStatusCode(), - request.getHeaderField(TableConstants.HeaderConstants.ETAG), opContext); - } - else { - throw TableServiceException.generateTableServiceException(true, this.getResult(), operation, - request.getErrorStream()); - } - } - }; - - return ExecutionEngine.executeWithRetry(client, this, impl, options.getRetryPolicyFactory(), opContext); - } - - /** - * Reserved for internal use. Execute this table operation on the specified table, using the specified - * {@link TableRequestOptions} and {@link OperationContext}. - *

- * This method will invoke the Storage Service REST API to execute this table operation, using the Table service - * endpoint and storage account credentials in the {@link CloudTableClient} object. - * - * @param client - * A {@link CloudTableClient} instance specifying the Table service endpoint, storage account - * credentials, and any additional query parameters. - * @param tableName - * A String containing the name of the table. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * A {@link TableResult} containing the results of executing the operation. - * - * @throws StorageException - * if an error occurs in the storage operation. - */ - protected TableResult execute(final CloudTableClient client, final String tableName, TableRequestOptions options, - OperationContext opContext) throws StorageException { - if (opContext == null) { - opContext = new OperationContext(); - } - - if (options == null) { - options = new TableRequestOptions(); - } - - opContext.initialize(); - options.applyDefaults(client); - Utility.assertNotNullOrEmpty("TableName", tableName); - - if (this.getOperationType() == TableOperationType.INSERT - || this.getOperationType() == TableOperationType.INSERT_OR_MERGE - || this.getOperationType() == TableOperationType.INSERT_OR_REPLACE) { - return this.performInsert(client, tableName, options, opContext); - } - else if (this.getOperationType() == TableOperationType.DELETE) { - return this.performDelete(client, tableName, options, opContext); - } - else if (this.getOperationType() == TableOperationType.MERGE) { - return this.performMerge(client, tableName, options, opContext); - } - else if (this.getOperationType() == TableOperationType.REPLACE) { - return this.performUpdate(client, tableName, options, opContext); - } - else if (this.getOperationType() == TableOperationType.RETRIEVE) { - return ((QueryTableOperation) this).performRetrieve(client, tableName, options, opContext); - } - else { - throw new IllegalArgumentException("Unknown table operation"); - } - } - - /** - * Reserved for internal use. Generates the request identity, consisting of the specified entry name, or the - * PartitionKey and RowKey pair from the operation, to identify the operation target. - * - * @param isSingleIndexEntry - * Pass true to use the specified entryName parameter, or false to - * use PartitionKey and RowKey values from the operation as the request identity. - * @param entryName - * The entry name to use as the request identity if the isSingleIndexEntry parameter is - * true. - * @param encodeKeys - * Pass true to url encode the partition & row keys - * @return - * A String containing the formatted request identity string. - * @throws StorageException - * If a storage service error occurred. - */ - protected String generateRequestIdentity(boolean isSingleIndexEntry, final String entryName, boolean encodeKeys) - throws StorageException { - if (isSingleIndexEntry) { - return String.format("'%s'", entryName); - } - - if (this.opType == TableOperationType.INSERT) { - return Constants.EMPTY_STRING; - } - else { - String pk = null; - String rk = null; - - if (this.opType == TableOperationType.RETRIEVE) { - final QueryTableOperation qOp = (QueryTableOperation) this; - pk = qOp.getPartitionKey(); - rk = qOp.getRowKey(); - } - else { - pk = this.getEntity().getPartitionKey(); - rk = this.getEntity().getRowKey(); - } - - return String.format("%s='%s',%s='%s'", TableConstants.PARTITION_KEY, encodeKeys ? Utility.safeEncode(pk) - : pk, TableConstants.ROW_KEY, encodeKeys ? Utility.safeEncode(rk) : rk); - } - } - - /** - * Reserved for internal use. Generates the request identity string for the specified table. The request identity - * string combines the table name with the PartitionKey and RowKey from the operation to identify specific table - * entities. This request identity is already UrlEncoded. - * - * @param tableName - * A String containing the name of the table. - * @return - * A String containing the formatted request identity string for the specified table. - * @throws StorageException - */ - protected String generateRequestIdentityWithTable(final String tableName) throws StorageException { - return String.format("/%s(%s)", tableName, generateRequestIdentity(false, null, true)); - } - - /** - * Reserved for internal use. Gets the table entity associated with this operation. - * - * @return - * The {@link TableEntity} instance associated with this operation. - */ - protected synchronized final TableEntity getEntity() { - return this.entity; - } - - /** - * Reserved for internal use. Gets the operation type for this operation. - * - * @return the opType - * The {@link TableOperationType} instance associated with this operation. - */ - protected synchronized final TableOperationType getOperationType() { - return this.opType; - } - - /** - * Reserved for internal use. Parses the table operation response into a {@link TableResult} to return. - * - * @param xmlr - * An XMLStreamReader containing the response to an insert operation. - * @param httpStatusCode - * The HTTP status code returned from the operation request. - * @param etagFromHeader - * The String containing the Etag returned with the operation response. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. - * - * @return - * The {@link TableResult} representing the result of the operation. - * - * @throws XMLStreamException - * if an error occurs accessing the XMLStreamReader. - * @throws ParseException - * if an error occurs in parsing the response. - * @throws InstantiationException - * if an error occurs in object construction. - * @throws IllegalAccessException - * if an error occurs in reflection on an object type. - * @throws StorageException - * if an error occurs in the storage operation. - */ - protected TableResult parseResponse(final XMLStreamReader xmlr, final int httpStatusCode, - final String etagFromHeader, final OperationContext opContext) throws XMLStreamException, ParseException, - InstantiationException, IllegalAccessException, StorageException { - TableResult resObj = null; - if (this.opType == TableOperationType.INSERT) { - // Sending null for class type and resolver will ignore parsing the return payload. - resObj = AtomPubParser.parseSingleOpResponse(xmlr, httpStatusCode, null, null, opContext); - resObj.updateResultObject(this.getEntity()); - } - else { - resObj = new TableResult(httpStatusCode); - resObj.setResult(this.getEntity()); - - if (this.opType != TableOperationType.DELETE && etagFromHeader != null) { - resObj.setEtag(etagFromHeader); - this.getEntity().setEtag(etagFromHeader); - } - } - - return resObj; - } - - /** - * Reserved for internal use. Sets the {@link TableEntity} instance for the table operation. - * - * @param entity - * The {@link TableEntity} instance to set. - */ - protected synchronized final void setEntity(final TableEntity entity) { - this.entity = entity; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableOperationType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableOperationType.java deleted file mode 100644 index ccfd867a98085..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableOperationType.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -/** - * Reserved for internal use. An enumeration type which represents the type of operation a {@link TableOperation} - * represents. - */ -enum TableOperationType { - INSERT, DELETE, REPLACE, RETRIEVE, MERGE, INSERT_OR_REPLACE, INSERT_OR_MERGE; - - /** - * Gets the {@link TableUpdateType} associated the operation type, if applicable. Applies to - * {@link #INSERT_OR_MERGE} and {@link #INSERT_OR_REPLACE} values. - * - * @return - * The applicable {@link TableUpdateType}, or null. - */ - public TableUpdateType getUpdateType() { - if (this == INSERT_OR_MERGE) { - return TableUpdateType.MERGE; - } - else if (this == INSERT_OR_REPLACE) { - return TableUpdateType.REPLACE; - } - else { - return null; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TablePermissions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TablePermissions.java deleted file mode 100644 index 15b9ad5d3f118..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TablePermissions.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.HashMap; - - -/** - * Represents the permissions for a table. - */ - -public final class TablePermissions { - - /** - * Gets the set of shared access policies for the table. - */ - private HashMap sharedAccessPolicies; - - /** - * Creates an instance of the TablePermissions class. - */ - public TablePermissions() { - this.sharedAccessPolicies = new HashMap(); - } - - /** - * Returns the set of shared access policies for the table. - * - * @return A HashMap object of {@link SharedAccessTablePolicy} objects that represent the set of shared - * access policies for the table. - */ - public HashMap getSharedAccessPolicies() { - return this.sharedAccessPolicies; - } - - /** - * Sets the set of shared access policies for the table. - * - * @param sharedAccessPolicies - * The set of shared access policies to set for the table, represented by a HashMap object of - * {@link SharedAccessTablePolicy} objects. - */ - public void setSharedAccessPolicies(final HashMap sharedAccessPolicies) { - this.sharedAccessPolicies = sharedAccessPolicies; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableQuery.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableQuery.java deleted file mode 100644 index 924ab0fead225..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableQuery.java +++ /dev/null @@ -1,777 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.Date; -import java.util.Formatter; -import java.util.UUID; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; - -/** - * A class which represents a query against a specified table. A {@link TableQuery} instance aggregates the query - * parameters to use when the query is executed. One of the execute or executeSegmented - * methods of {@link CloudTableClient} must be called to execute the query. The parameters are encoded and passed to the - * server when the table query is executed. - *

- * To create a table query with fluent syntax, the {@link #from} static factory method and the {@link #where}, - * {@link #select}, and {@link #take} mutator methods each return a reference to the object which can be chained into a - * single expression. Use the {@link TableQuery#from(String, Class)} static class factory method to create a - * TableQuery instance that executes on the named table with entities of the specified {@link TableEntity} - * implementing type. Use the {@link #where} method to specify a filter expression for the entities returned. Use the - * {@link #select} method to specify the table entity properties to return. Use the {@link #take} method to limit the - * number of entities returned by the query. Note that nothing prevents calling these methods more than once on a - * TableQuery, so the values saved in the TableQuery will be the last encountered in order of - * execution. - *

- * As an example, you could construct a table query using fluent syntax: - *

- * TableQuery<TableServiceEntity> myQuery = TableQuery.from("Products", DynamicTableEntity.class)
- *     .where("(PartitionKey eq 'ProductsMNO') and (RowKey ge 'Napkin')")
- *     .take(25)
- *     .select(new String[] {"InventoryCount"});
- *

- * This example creates a query on the "Products" table for all entities where the PartitionKey value is "ProductsMNO" - * and the RowKey value is greater than or equal to "Napkin" and requests the first 25 matching entities, selecting only - * the common properties and the property named "InventoryCount", and returns them as {@link DynamicTableEntity} - * objects. - *

- * Filter expressions for use with the {@link #where} method or {@link #setFilterString} method can be created using - * fluent syntax with the overloaded {@link #generateFilterCondition} methods and {@link #combineFilters} method, using - * the comparison operators defined in {@link QueryComparisons} and the logical operators defined in {@link Operators}. - * Note that the first operand in a filter comparison must be a property name, and the second operand must evaluate to a - * constant. The PartitionKey and RowKey property values are String types for comparison purposes. - *

- * The values that may be used in table queries are explained in more detail in the MSDN topic Querying Tables and Entities, but note - * that the space characters within values do not need to be URL-encoded, as this will be done when the query is - * executed. - *

- * The {@link TableQuery#TableQuery(String, Class)} constructor and {@link TableQuery#from(String, Class)} static - * factory methods require a class type which implements {@link TableEntity} and contains a nullary constructor. If the - * query will be executed using an {@link EntityResolver}, the caller may specify {@link TableServiceEntity} - * .class as the class type. - * - * @param - * A class type which implements {@link TableEntity} and contains a nullary constructor. Note: when using an - * inner class to define the class type, mark the class as static. - */ -public class TableQuery { - /** - * A static class that maps identifiers to filter expression operators. - */ - public static class Operators { - /** - * And - */ - public static final String AND = "and"; - - /** - * Not - */ - public static final String NOT = "not"; - - /** - * Or - */ - public static final String OR = "or"; - } - - /** - * A static class that maps identifiers to filter property comparison operators. - */ - public static class QueryComparisons { - /** - * Equal - */ - public static final String EQUAL = "eq"; - - /** - * Not Equal - */ - public static final String NOT_EQUAL = "ne"; - - /** - * Greater Than - */ - public static final String GREATER_THAN = "gt"; - - /** - * Greater Than Or Equal - */ - public static final String GREATER_THAN_OR_EQUAL = "ge"; - - /** - * Less Than - */ - public static final String LESS_THAN = "lt"; - - /** - * Less Than Or Equal - */ - public static final String LESS_THAN_OR_EQUAL = "le"; - } - - /** - * A static factory method that constructs a {@link TableQuery} instance and defines its source table and - * table entity type. The method returns the {@link TableQuery} instance reference, allowing additional methods to - * be chained to modify the query. - *

- * The created {@link TableQuery} instance is specialized for table entities of the specified class type T, using - * the table with the specified name as data source. Callers may specify {@link TableServiceEntity} - * .class as the class type parameter if no more specialized type is required. - * - * @param tablename - * A String containing the name of the source table to query. - * @param clazzType - * The java.lang.Class of the class T implementing the {@link TableEntity} - * interface that - * represents the table entity type for the query. - * - * @return - * The {@link TableQuery} instance with the source table name and entity type specialization set. - */ - public static TableQuery from(final String tablename, final Class clazzType) { - return new TableQuery(tablename, clazzType); - } - - /** - * Generates a property filter condition string for a boolean value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as a - * boolean, as in the following example: - *

- * String condition = generateFilterCondition("BooleanProperty", QueryComparisons.EQUAL, false); - *

- * This statement sets condition to the following value: - *

- * BooleanProperty eq false - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A boolean containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final boolean value) { - return generateFilterCondition(propertyName, operation, value ? Constants.TRUE : Constants.FALSE, - EdmType.BOOLEAN); - } - - /** - * Generates a property filter condition string for a byte[] value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as a - * binary value, as in the following example: - *

- * String condition = generateFilterCondition("ByteArray", QueryComparisons.EQUAL, new byte[] {0x01, 0x0f}); - *

- * This statement sets condition to the following value: - *

- * ByteArray eq X'010f' - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A byte[] containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final byte[] value) { - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb); - for (byte b : value) { - formatter.format("%02x", b); - } - formatter.flush(); - formatter.close(); - - return generateFilterCondition(propertyName, operation, sb.toString(), EdmType.BINARY); - } - - /** - * Generates a property filter condition string for a Byte[] value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as a - * binary value, as in the following example: - *

- * String condition = generateFilterCondition("ByteArray", QueryComparisons.EQUAL, new Byte[] {0x01, 0xfe}); - *

- * This statement sets condition to the following value: - *

- * ByteArray eq X'01fe' - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A Byte[] containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final Byte[] value) { - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb); - for (byte b : value) { - formatter.format("%02x", b); - } - formatter.flush(); - formatter.close(); - - return generateFilterCondition(propertyName, operation, sb.toString(), EdmType.BINARY); - } - - /** - * Generates a property filter condition string for a Date value. Creates a formatted string to use in - * a filter expression that uses the specified operation to compare the property with the value, formatted as a - * datetime value, as in the following example: - *

- * String condition = generateFilterCondition("FutureDate", QueryComparisons.GREATER_THAN, new Date()); - *

- * This statement sets condition to something like the following value: - *

- * FutureDate gt datetime'2013-01-31T09:00:00' - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A Date containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final Date value) { - return generateFilterCondition(propertyName, operation, - Utility.getTimeByZoneAndFormat(value, Utility.UTC_ZONE, Utility.ISO8061_LONG_PATTERN), - EdmType.DATE_TIME); - } - - /** - * Generates a property filter condition string for a double value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as - * a double value, as in the following example: - *

- * String condition = generateFilterCondition("Circumference", QueryComparisons.EQUAL, 2 * 3.141592); - *

- * This statement sets condition to the following value: - *

- * Circumference eq 6.283184 - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A double containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final double value) { - return generateFilterCondition(propertyName, operation, Double.toString(value), EdmType.DOUBLE); - } - - /** - * Generates a property filter condition string for an int value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as - * a numeric value, as in the following example: - *

- * String condition = generateFilterCondition("Population", QueryComparisons.GREATER_THAN, 1000); - *

- * This statement sets condition to the following value: - *

- * Population gt 1000 - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * An int containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final int value) { - return generateFilterCondition(propertyName, operation, Integer.toString(value), EdmType.INT32); - } - - /** - * Generates a property filter condition string for a long value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as - * a numeric value, as in the following example: - *

- * String condition = generateFilterCondition("StellarMass", QueryComparisons.GREATER_THAN, 7000000000L); - *

- * This statement sets condition to the following value: - *

- * StellarMass gt 7000000000 - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A long containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final long value) { - return generateFilterCondition(propertyName, operation, Long.toString(value), EdmType.INT64); - } - - /** - * Generates a property filter condition string for a String value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as - * a string value, as in the following example: - *

- * String condition = generateFilterCondition("Platform", QueryComparisons.EQUAL, "Windows Azure"); - *

- * This statement sets condition to the following value: - *

- * Platform eq 'Windows Azure' - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A String containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final String value) { - return generateFilterCondition(propertyName, operation, value, EdmType.STRING); - } - - /** - * Generates a property filter condition string. Creates a formatted string to use in a filter expression that uses - * the specified operation to compare the property with the value, formatted as the specified {@link EdmType}. - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A String containing the value to compare with the property. - * @param edmType - * The {@link EdmType} to format the value as. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, String value, EdmType edmType) { - String valueOperand = null; - - if (edmType == EdmType.BOOLEAN || edmType == EdmType.DOUBLE || edmType == EdmType.INT32 - || edmType == EdmType.INT64) { - valueOperand = value; - } - else if (edmType == EdmType.DATE_TIME) { - valueOperand = String.format("datetime'%s'", value); - } - else if (edmType == EdmType.GUID) { - valueOperand = String.format("guid'%s'", value); - } - else if (edmType == EdmType.BINARY) { - valueOperand = String.format("X'%s'", value); - } - else { - valueOperand = String.format("'%s'", value); - } - - return String.format("%s %s %s", propertyName, operation, valueOperand); - } - - /** - * Generates a property filter condition string for a UUID value. Creates a formatted string to use - * in a filter expression that uses the specified operation to compare the property with the value, formatted as - * a UUID value, as in the following example: - *

- * String condition = generateFilterCondition("Identity", QueryComparisons.EQUAL, UUID.fromString( - * "c9da6455-213d-42c9-9a79-3e9149a57833")); - *

- * This statement sets condition to the following value: - *

- * Identity eq guid'c9da6455-213d-42c9-9a79-3e9149a57833' - * - * @param propertyName - * A String containing the name of the property to compare. - * @param operation - * A String containing the comparison operator to use. - * @param value - * A UUID containing the value to compare with the property. - * @return - * A String containing the formatted filter condition. - */ - public static String generateFilterCondition(String propertyName, String operation, final UUID value) { - return generateFilterCondition(propertyName, operation, value.toString(), EdmType.GUID); - } - - /** - * Creates a filter condition using the specified logical operator on two filter conditions. - * - * @param filterA - * A String containing the first formatted filter condition. - * @param operator - * A String containing Operators.AND or Operators.OR. - * @param filterB - * A String containing the first formatted filter condition. - * @return - * A String containing the combined filter expression. - */ - public static String combineFilters(String filterA, String operator, String filterB) { - return String.format("(%s) %s (%s)", filterA, operator, filterB); - } - - private Class clazzType = null; - private String sourceTableName = null; - private String[] columns = null; - private Integer takeCount; - private String filterString = null; - - /** - * Initializes an empty {@link TableQuery} instance. This table query cannot be executed without - * setting a source table and a table entity type. - */ - public TableQuery() { - // empty ctor - } - - /** - * Initializes a {@link TableQuery} with the specified source table and table entity type. Callers may specify - * {@link TableServiceEntity}.class as the class type parameter if no more specialized type is - * required. - * - * @param tableName - * A String containing the name of the source table to query. - * @param clazzType - * The java.lang.Class of the class T that represents the table entity type for - * the query. Class T must be a type that implements {@link TableEntity} and has a nullary - * constructor, - */ - public TableQuery(final String tableName, final Class clazzType) { - this.setSourceTableName(tableName); - this.setClazzType(clazzType); - } - - /** - * Gets the class type of the table entities returned by the query. - * - * @return - * The java.lang.Class of the class T that represents the table entity type for - * the query. - */ - public Class getClazzType() { - return this.clazzType; - } - - /** - * Gets an array of the table entity property names specified in the table query. All properties in the table are - * returned by default if no property names are specified with a select clause in the table query. The table entity - * properties to return may be specified with a call to the {@link #setColumns} or {@link #select} methods with a - * array of property names as parameter. - *

- * Note that the system properties PartitionKey, RowKey, and Timestamp are - * automatically requested from the table service whether specified in the {@link TableQuery} or not. - * - * @return - * An array of String objects containing the property names of the table entity properties to - * return in the query. - */ - public String[] getColumns() { - return this.columns; - } - - /** - * Gets the class type of the table entities returned by the query. - * - * @return - * The java.lang.Class of the class T implementing the {@link TableEntity} - * interface that - * represents the table entity type for the query. - */ - public Class getEntityClass() { - return this.clazzType; - } - - /** - * Gets the filter expression specified in the table query. All entities in the table are returned by - * default if no filter expression is specified in the table query. A filter for the entities to return may be - * specified with a call to the {@link #setFilterString} or {@link #where} methods. - * - * @return - * A String containing the filter expression used in the query. - */ - public String getFilterString() { - return this.filterString; - } - - /** - * Gets the name of the source table specified in the table query. - * - * @return - * A String containing the name of the source table used in the query. - */ - public String getSourceTableName() { - return this.sourceTableName; - } - - /** - * Gets the number of entities the query returns specified in the table query. If this value is not - * specified in a table query, a maximum of 1,000 entries will be returned. The number of entities to return may be - * specified with a call to the {@link #setTakeCount} or {@link #take} methods. - *

- * If the value returned by getTakeCount is greater than 1,000, the query will throw a - * {@link StorageException} when executed. - * - * @return - * The maximum number of entities for the table query to return. - */ - public Integer getTakeCount() { - return this.takeCount; - } - - /** - * Defines the property names of the table entity properties to return when the table query is executed. The - * select clause is optional on a table query, used to limit the table properties returned from the - * server. By default, a query will return all properties from the table entity. - *

- * Note that the system properties PartitionKey, RowKey, and Timestamp are - * automatically requested from the table service whether specified in the {@link TableQuery} or not. - * - * @param columns - * An array of String objects containing the property names of the table entity properties - * to return when the query is executed. - * - * @return - * A reference to the {@link TableQuery} instance with the table entity properties to return set. - */ - public TableQuery select(final String[] columns) { - this.setColumns(columns); - return this; - } - - /** - * Sets the class type of the table entities returned by the query. A class type is required to execute a table - * query. - *

- * Callers may specify {@link TableServiceEntity}.class as the class type parameter if no more - * specialized type is required. - * - * @param clazzType - * The java.lang.Class of the class T that represents the table entity type for - * the query. Class T must be a type that implements {@link TableEntity} and has a nullary - * constructor, - */ - public void setClazzType(final Class clazzType) { - Utility.assertNotNull("Query requires a valid class type.", clazzType); - Utility.checkNullaryCtor(clazzType); - this.clazzType = clazzType; - } - - /** - * Sets the property names of the table entity properties to return when the table query is executed. By default, a - * query will return all properties from the table entity. - *

- * Note that the system properties PartitionKey, RowKey, and Timestamp are - * automatically requested from the table service whether specified in the {@link TableQuery} or not. - * - * @param columns - * An array of String objects containing the property names of the table entity properties - * to return when the query is executed. - */ - public void setColumns(final String[] columns) { - this.columns = columns; - } - - /** - * Sets the filter expression to use in the table query. A filter expression is optional; by default a table query - * will return all entities in the table. - *

- * Filter expressions for use with the {@link #setFilterString} method can be created using fluent syntax with the - * overloaded {@link #generateFilterCondition} methods and {@link #combineFilters} method, using the comparison - * operators defined in {@link QueryComparisons} and the logical operators defined in {@link Operators}. Note that - * the first operand in a filter comparison must be a property name, and the second operand must evaluate to a - * constant. The PartitionKey and RowKey property values are String types for comparison purposes. For - * example, to query all entities with a PartitionKey value of "AccessLogs" on table query myQuery: - *

- *     myQuery.setFilterString("PartitionKey eq 'AccessLogs'"); - *

- * The values that may be used in table queries are explained in more detail in the MSDN topic - * - * Querying Tables and Entities, - * but note that the space characters within values do not need to be URL-encoded, as this will be done when the - * query is executed. - *

- * Note that no more than 15 discrete comparisons are permitted within a filter string. - * - * @param filterString - * A String containing the filter expression to use in the query. - */ - public void setFilterString(final String filterString) { - Utility.assertNotNullOrEmpty("filterString", filterString); - this.filterString = filterString; - } - - /** - * Sets the name of the source table for the table query. A table query must have a source table to be executed. - * - * @param sourceTableName - * A String containing the name of the source table to use in the query. - */ - public void setSourceTableName(final String sourceTableName) { - Utility.assertNotNullOrEmpty("tableName", sourceTableName); - this.sourceTableName = sourceTableName; - } - - /** - * Sets the upper bound for the number of entities the query returns. If this value is not specified in a table - * query, by default a maximum of 1,000 entries will be returned. - *

- * If the value specified for the takeCount parameter is greater than 1,000, the query will throw a - * {@link StorageException} when executed. - * - * @param takeCount - * The maximum number of entities for the table query to return. - */ - public void setTakeCount(final Integer takeCount) { - if (takeCount != null && takeCount <= 0) { - throw new IllegalArgumentException("Take count must be positive and greater than 0."); - } - - this.takeCount = takeCount; - } - - /** - * Defines the upper bound for the number of entities the query returns. If this value is not specified in a table - * query, by default a maximum of 1,000 entries will be returned. - *

- * If the value specified for the take parameter is greater than 1,000, the query will throw a - * {@link StorageException} when executed. - * - * @param take - * The maximum number of entities for the table query to return. - * - * @return - * A reference to the {@link TableQuery} instance with the number of entities to return set. - */ - public TableQuery take(final Integer take) { - if (take != null) { - this.setTakeCount(take); - } - return this; - } - - /** - * Defines a filter expression for the table query. Only entities that satisfy the specified filter expression will - * be returned by the query. Setting a filter expression is optional; by default, all entities in the table are - * returned if no filter expression is specified in the table query. - *

- * Filter expressions for use with the {@link #where} method can be created using fluent syntax with the overloaded - * {@link #generateFilterCondition} methods and {@link #combineFilters} method, using the comparison operators - * defined in {@link QueryComparisons} and the logical operators defined in {@link Operators}. Note that the first - * operand in a filter comparison must be a property name, and the second operand must evaluate to a constant. The - * PartitionKey and RowKey property values are String types for comparison purposes. For example, to - * query all entities with a PartitionKey value of "AccessLogs" on table query myQuery: - *

- *     myQuery = myQuery.where("PartitionKey eq 'AccessLogs'"); - *

- * The values that may be used in table queries are explained in more detail in the MSDN topic - * - * Querying Tables and Entities, - * but note that the space characters within values do not need to be URL-encoded, as this will be done when the - * query is executed. - *

- * Note that no more than 15 discrete comparisons are permitted within a filter string. - * - * @param filter - * A String containing the filter expression to apply to the table query. - * @return - * A reference to the {@link TableQuery} instance with the filter on entities to return set. - */ - public TableQuery where(final String filter) { - this.setFilterString(filter); - return this; - } - - /** - * Reserved for internal use. Creates a {@link UriQueryBuilder} object representing the table query. - * - * @return - * A {@link UriQueryBuilder} object representing the table query. - * @throws StorageException - * if an error occurs in adding or encoding the query parameters. - */ - protected UriQueryBuilder generateQueryBuilder() throws StorageException { - final UriQueryBuilder builder = new UriQueryBuilder(); - if (!Utility.isNullOrEmpty(this.filterString)) { - builder.add(TableConstants.FILTER, this.filterString); - } - - if (this.takeCount != null) { - builder.add(TableConstants.TOP, this.takeCount.toString()); - } - - if (this.columns != null && this.columns.length > 0) { - final StringBuilder colBuilder = new StringBuilder(); - - boolean foundRk = false; - boolean foundPk = false; - boolean roundTs = false; - - for (int m = 0; m < this.columns.length; m++) { - if (TableConstants.ROW_KEY.equals(this.columns[m])) { - foundRk = true; - } - else if (TableConstants.PARTITION_KEY.equals(this.columns[m])) { - foundPk = true; - } - else if (TableConstants.TIMESTAMP.equals(this.columns[m])) { - roundTs = true; - } - - colBuilder.append(this.columns[m]); - if (m < this.columns.length - 1) { - colBuilder.append(","); - } - } - - if (!foundPk) { - colBuilder.append(","); - colBuilder.append(TableConstants.PARTITION_KEY); - } - - if (!foundRk) { - colBuilder.append(","); - colBuilder.append(TableConstants.ROW_KEY); - } - - if (!roundTs) { - colBuilder.append(","); - colBuilder.append(TableConstants.TIMESTAMP); - } - - builder.add(TableConstants.SELECT, colBuilder.toString()); - } - - return builder; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableRequest.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableRequest.java deleted file mode 100644 index 171d8cbc254fb..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableRequest.java +++ /dev/null @@ -1,585 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.IOException; -import java.io.StringWriter; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map.Entry; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; -import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; -import com.microsoft.windowsazure.services.core.storage.utils.Utility; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.BaseRequest; - -/** - * Reserved for internal use. A class used to generate requests for Table objects. - */ -final class TableRequest { - /** - * Reserved for internal use. Adds continuation token values to the specified query builder, if set. - * - * @param builder - * The {@link UriQueryBuilder} object to apply the continuation token properties to. - * @param continuationToken - * The {@link ResultContinuation} object containing the continuation token values to apply to the query - * builder. Specify null if no continuation token values are set. - * - * @throws StorageException - * if an error occurs in accessing the query builder or continuation token. - */ - protected static void applyContinuationToQueryBuilder(final UriQueryBuilder builder, - final ResultContinuation continuationToken) throws StorageException { - if (continuationToken != null) { - if (continuationToken.getNextPartitionKey() != null) { - builder.add(TableConstants.TABLE_SERVICE_NEXT_PARTITION_KEY, continuationToken.getNextPartitionKey()); - } - - if (continuationToken.getNextRowKey() != null) { - builder.add(TableConstants.TABLE_SERVICE_NEXT_ROW_KEY, continuationToken.getNextRowKey()); - } - - if (continuationToken.getNextTableName() != null) { - builder.add(TableConstants.TABLE_SERVICE_NEXT_TABLE_NAME, continuationToken.getNextTableName()); - } - } - } - - /** - * Reserved for internal use. Constructs an HttpURLConnection to perform a table batch operation. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param batchID - * The String containing the batch identifier. - * @param queryBuilder - * The {@link UriQueryBuilder} for the operation. - * @param tableOptions - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. This parameter is unused. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * An HttpURLConnection to use to perform the operation. - * - * @throws IOException - * if there is an error opening the connection. - * @throws URISyntaxException - * if the resource URI is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - protected static HttpURLConnection batch(final URI rootUri, final int timeoutInMs, final String batchID, - final UriQueryBuilder queryBuilder, final TableRequestOptions tableOptions, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - final URI queryUri = PathUtility.appendPathToUri(rootUri, "$batch"); - - final HttpURLConnection retConnection = BaseRequest.createURLConnection(queryUri, timeoutInMs, queryBuilder, - opContext); - // Note : accept behavior, java by default sends Accept behavior - // as text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 - retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT, TableConstants.HeaderConstants.ACCEPT_TYPE); - retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_CHARSET, "UTF8"); - retConnection.setRequestProperty(TableConstants.HeaderConstants.MAX_DATA_SERVICE_VERSION, - TableConstants.HeaderConstants.MAX_DATA_SERVICE_VERSION_VALUE); - - retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, - String.format(TableConstants.HeaderConstants.MULTIPART_MIXED_FORMAT, batchID)); - - retConnection.setRequestMethod("POST"); - retConnection.setDoOutput(true); - return retConnection; - } - - /** - * Reserved for internal use. Constructs the core HttpURLConnection to perform an operation. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param identity - * The identity of the entity, to pass in the Service Managment REST operation URI as - * tableName(identity). If null, only the tableName - * value will be passed. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param queryBuilder - * The UriQueryBuilder for the request. - * @param requestMethod - * The HTTP request method to set. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. This parameter is unused. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. - * - * @return - * An HttpURLConnection to use to perform the operation. - * - * @throws IOException - * if there is an error opening the connection. - * @throws URISyntaxException - * if the resource URI is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - protected static HttpURLConnection coreCreate(final URI rootUri, final String tableName, final String eTag, - final String identity, final int timeoutInMs, final UriQueryBuilder queryBuilder, - final String requestMethod, final TableRequestOptions tableOptions, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - - URI queryUri = null; - - // Do point query / delete etc. - if (!Utility.isNullOrEmpty(identity)) { - queryUri = PathUtility.appendPathToUri(rootUri, tableName.concat(String.format("(%s)", identity))); - } - else { - queryUri = PathUtility.appendPathToUri(rootUri, tableName); - } - - final HttpURLConnection retConnection = BaseRequest.createURLConnection(queryUri, timeoutInMs, queryBuilder, - opContext); - // Note : accept behavior, java by default sends Accept behavior - // as text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 - retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT, TableConstants.HeaderConstants.ACCEPT_TYPE); - retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_CHARSET, "UTF-8"); - retConnection.setRequestProperty(TableConstants.HeaderConstants.MAX_DATA_SERVICE_VERSION, - TableConstants.HeaderConstants.MAX_DATA_SERVICE_VERSION_VALUE); - - retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, - TableConstants.HeaderConstants.ATOMPUB_TYPE); - - if (!Utility.isNullOrEmpty(eTag)) { - retConnection.setRequestProperty(Constants.HeaderConstants.IF_MATCH, eTag); - } - - retConnection.setRequestMethod(requestMethod); - return retConnection; - } - - /** - * Reserved for internal use. Constructs an HttpURLConnection to perform a delete operation. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param identity - * The identity of the entity. The resulting request will be formatted as /tableName(identity) if not - * null or empty. - * @param eTag - * The etag of the entity. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param queryBuilder - * The {@link UriQueryBuilder} for the operation. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * An HttpURLConnection to use to perform the operation. - * - * @throws IOException - * if there is an error opening the connection. - * @throws URISyntaxException - * if the resource URI is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - protected static HttpURLConnection delete(final URI rootUri, final String tableName, final String identity, - final String eTag, final int timeoutInMs, final UriQueryBuilder queryBuilder, - final TableRequestOptions tableOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - - return coreCreate(rootUri, tableName, eTag, identity, timeoutInMs, queryBuilder, "DELETE", tableOptions, - opContext); - } - - /** - * Reserved for internal use. Constructs an HttpURLConnection to perform an insert operation. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param identity - * The identity of the entity. The resulting request will be formatted as /tableName(identity) if not - * null or empty. - * @param eTag - * The etag of the entity, can be null for straight inserts. - * @param updateType - * The {@link TableUpdateType} type of update to be performed. Specify null for straight - * inserts. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param queryBuilder - * The {@link UriQueryBuilder} for the operation. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * An HttpURLConnection to use to perform the operation. - * - * @throws IOException - * if there is an error opening the connection. - * @throws URISyntaxException - * if the resource URI is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - protected static HttpURLConnection insert(final URI rootUri, final String tableName, final String identity, - final String eTag, final TableUpdateType updateType, final int timeoutInMs, - final UriQueryBuilder queryBuilder, final TableRequestOptions tableOptions, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - HttpURLConnection retConnection = null; - - if (updateType == null) { - retConnection = coreCreate(rootUri, tableName, eTag, null/* identity */, timeoutInMs, queryBuilder, - "POST", tableOptions, opContext); - } - else if (updateType == TableUpdateType.MERGE) { - retConnection = coreCreate(rootUri, tableName, null/* ETAG */, identity, timeoutInMs, queryBuilder, - "POST", tableOptions, opContext); - - retConnection.setRequestProperty("X-HTTP-Method", "MERGE"); - } - else if (updateType == TableUpdateType.REPLACE) { - retConnection = coreCreate(rootUri, tableName, null/* ETAG */, identity, timeoutInMs, queryBuilder, "PUT", - tableOptions, opContext); - } - - retConnection.setDoOutput(true); - - return retConnection; - } - - /** - * Reserved for internal use. Constructs an HttpURLConnection to perform a merge operation. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param identity - * The identity of the entity. The resulting request will be formatted as /tableName(identity) if not - * null or empty. - * @param eTag - * The etag of the entity. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param queryBuilder - * The {@link UriQueryBuilder} for the operation. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * An HttpURLConnection to use to perform the operation. - * - * @throws IOException - * if there is an error opening the connection. - * @throws URISyntaxException - * if the resource URI is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - protected static HttpURLConnection merge(final URI rootUri, final String tableName, final String identity, - final String eTag, final int timeoutInMs, final UriQueryBuilder queryBuilder, - final TableRequestOptions tableOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - final HttpURLConnection retConnection = coreCreate(rootUri, tableName, eTag, identity, timeoutInMs, - queryBuilder, "POST", tableOptions, opContext); - retConnection.setRequestProperty("X-HTTP-Method", "MERGE"); - retConnection.setDoOutput(true); - return retConnection; - } - - /** - * Reserved for internal use. Constructs an HttpURLConnection to perform a single entity query operation. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param identity - * The identity of the entity. The resulting request will be formatted as /tableName(identity) if not - * null or empty. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param queryBuilder - * The {@link UriQueryBuilder} for the operation. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * An HttpURLConnection to use to perform the operation. - * - * @throws IOException - * if there is an error opening the connection. - * @throws URISyntaxException - * if the resource URI is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - protected static HttpURLConnection query(final URI rootUri, final String tableName, final String identity, - final int timeoutInMs, UriQueryBuilder queryBuilder, final ResultContinuation continuationToken, - final TableRequestOptions tableOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - if (queryBuilder == null) { - queryBuilder = new UriQueryBuilder(); - } - - applyContinuationToQueryBuilder(queryBuilder, continuationToken); - final HttpURLConnection retConnection = coreCreate(rootUri, tableName, null, identity, timeoutInMs, - queryBuilder, "GET", tableOptions, opContext); - - return retConnection; - } - - /** - * Reserved for internal use. Constructs an HttpURLConnection to perform an update operation. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param identity - * A String representing the identity of the entity. The resulting request will be formatted - * using /tableName(identity) if identity is not >code>null or empty. - * @param eTag - * The etag of the entity. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param queryBuilder - * The {@link UriQueryBuilder} for the operation. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return - * An HttpURLConnection to use to perform the operation. - * - * @throws IOException - * if there is an error opening the connection. - * @throws URISyntaxException - * if the resource URI is invalid. - * @throws StorageException - * if a storage service error occurred during the operation. - */ - protected static HttpURLConnection update(final URI rootUri, final String tableName, final String identity, - final String eTag, final int timeoutInMs, final UriQueryBuilder queryBuilder, - final TableRequestOptions tableOptions, final OperationContext opContext) throws IOException, - URISyntaxException, StorageException { - final HttpURLConnection retConnection = coreCreate(rootUri, tableName, eTag, identity, timeoutInMs, - queryBuilder, "PUT", tableOptions, opContext); - - retConnection.setDoOutput(true); - return retConnection; - } - - /** - * Sets the ACL for the table. , Sign with length of aclBytes. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - * */ - public static HttpURLConnection setAcl(final URI rootUri, final int timeoutInMs, final OperationContext opContext) - throws IOException, URISyntaxException, StorageException { - - UriQueryBuilder queryBuilder = new UriQueryBuilder(); - queryBuilder.add("comp", "acl"); - - final HttpURLConnection retConnection = BaseRequest.createURLConnection(rootUri, timeoutInMs, queryBuilder, - opContext); - retConnection.setRequestMethod("PUT"); - retConnection.setDoOutput(true); - retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, - TableConstants.HeaderConstants.ATOMPUB_TYPE); - - return retConnection; - } - - /** - * Writes a collection of shared access policies to the specified stream in XML format. - * - * @param sharedAccessPolicies - * A collection of shared access policies - * @param outWriter - * an sink to write the output to. - * @throws XMLStreamException - */ - public static void writeSharedAccessIdentifiersToStream( - final HashMap sharedAccessPolicies, final StringWriter outWriter) - throws XMLStreamException { - Utility.assertNotNull("sharedAccessPolicies", sharedAccessPolicies); - Utility.assertNotNull("outWriter", outWriter); - - final XMLOutputFactory xmlOutFactoryInst = XMLOutputFactory.newInstance(); - final XMLStreamWriter xmlw = xmlOutFactoryInst.createXMLStreamWriter(outWriter); - - if (sharedAccessPolicies.keySet().size() > Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS) { - final String errorMessage = String - .format("Too many %d shared access policy identifiers provided. Server does not support setting more than %d on a single container.", - sharedAccessPolicies.keySet().size(), Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS); - - throw new IllegalArgumentException(errorMessage); - } - - // default is UTF8 - xmlw.writeStartDocument(); - xmlw.writeStartElement(Constants.SIGNED_IDENTIFIERS_ELEMENT); - - for (final Entry entry : sharedAccessPolicies.entrySet()) { - final SharedAccessTablePolicy policy = entry.getValue(); - xmlw.writeStartElement(Constants.SIGNED_IDENTIFIER_ELEMENT); - - // Set the identifier - xmlw.writeStartElement(Constants.ID); - xmlw.writeCharacters(entry.getKey()); - xmlw.writeEndElement(); - - xmlw.writeStartElement(Constants.ACCESS_POLICY); - - // Set the Start Time - xmlw.writeStartElement(Constants.START); - xmlw.writeCharacters(Utility.getUTCTimeOrEmpty(policy.getSharedAccessStartTime())); - // end Start - xmlw.writeEndElement(); - - // Set the Expiry Time - xmlw.writeStartElement(Constants.EXPIRY); - xmlw.writeCharacters(Utility.getUTCTimeOrEmpty(policy.getSharedAccessExpiryTime())); - // end Expiry - xmlw.writeEndElement(); - - // Set the Permissions - xmlw.writeStartElement(Constants.PERMISSION); - xmlw.writeCharacters(SharedAccessTablePolicy.permissionsToString(policy.getPermissions())); - // end Permission - xmlw.writeEndElement(); - - // end AccessPolicy - xmlw.writeEndElement(); - // end SignedIdentifier - xmlw.writeEndElement(); - } - - // end SignedIdentifiers - xmlw.writeEndElement(); - // end doc - xmlw.writeEndDocument(); - } - - /** - * Constructs a web request to return the ACL for this table. Sign with no length specified. - * - * @param rootUri - * A java.net.URI containing an absolute URI to the resource. - * @param tableName - * The name of the table. - * @param timeoutInMs - * The server timeout interval in milliseconds. - * @param options - * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout - * settings for the operation. Specify null to use the request options specified on the - * {@link CloudTableClient}. - * @param opContext - * An {@link OperationContext} object for tracking the current operation. Specify null to - * safely ignore operation context. - * - * @return a HttpURLConnection configured for the operation. - * @throws StorageException - */ - public static HttpURLConnection getAcl(final URI rootUri, final String tableName, final int timeoutInMs, - final OperationContext opContext) throws IOException, URISyntaxException, StorageException { - - UriQueryBuilder queryBuilder = new UriQueryBuilder(); - queryBuilder.add("comp", "acl"); - - final HttpURLConnection retConnection = BaseRequest.createURLConnection(rootUri, timeoutInMs, queryBuilder, - opContext); - retConnection.setRequestMethod("GET"); - retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT, TableConstants.HeaderConstants.ACCEPT_TYPE); - retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_CHARSET, "UTF8"); - retConnection.setRequestProperty(TableConstants.HeaderConstants.MAX_DATA_SERVICE_VERSION, - TableConstants.HeaderConstants.MAX_DATA_SERVICE_VERSION_VALUE); - retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, - TableConstants.HeaderConstants.ATOMPUB_TYPE); - - return retConnection; - } - - /** - * Private Default Constructor. - */ - private TableRequest() { - // No op - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableRequestOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableRequestOptions.java deleted file mode 100644 index 030eee752beec..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableRequestOptions.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import com.microsoft.windowsazure.services.core.storage.RequestOptions; - -/** - * Represents a set of timeout and retry policy options that may be specified for a table operation request. - */ -public class TableRequestOptions extends RequestOptions { - /** - * Reserved for internal use. Initializes the timeout and retry policy for this TableRequestOptions - * instance, if they are currently null, using the values specified in the {@link CloudTableClient} - * parameter. - * - * @param client - * The {@link CloudTableClient} client object to copy the timeout and retry policy from. - */ - protected void applyDefaults(final CloudTableClient client) { - super.applyBaseDefaults(client); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableResponse.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableResponse.java deleted file mode 100644 index 6f2d7d9c8d861..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableResponse.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.net.HttpURLConnection; - -import com.microsoft.windowsazure.services.core.storage.ResultContinuation; -import com.microsoft.windowsazure.services.core.storage.ResultContinuationType; - -/** - * Reserved for internal use. A class used to help parse responses from the Table service. - */ -class TableResponse { - /** - * Reserved for internal use. A static factory method that constructs a {@link ResultContinuation} instance from the - * continuation token information in a table operation response, if any. - * - * @param queryRequest - * The java.net.HttpURLConnection request response to parse for continuation token - * information. - * - * @return - * A {@link ResultContinuation} instance from continuation token information in the response, or - * null if none is found. - */ - protected static ResultContinuation getTableContinuationFromResponse(final HttpURLConnection queryRequest) { - final ResultContinuation retVal = new ResultContinuation(); - retVal.setContinuationType(ResultContinuationType.TABLE); - - boolean foundToken = false; - - String tString = queryRequest.getHeaderField(TableConstants.TABLE_SERVICE_PREFIX_FOR_TABLE_CONTINUATION - .concat(TableConstants.TABLE_SERVICE_NEXT_PARTITION_KEY)); - if (tString != null) { - retVal.setNextPartitionKey(tString); - foundToken = true; - } - - tString = queryRequest.getHeaderField(TableConstants.TABLE_SERVICE_PREFIX_FOR_TABLE_CONTINUATION - .concat(TableConstants.TABLE_SERVICE_NEXT_ROW_KEY)); - if (tString != null) { - retVal.setNextRowKey(tString); - foundToken = true; - } - - tString = queryRequest.getHeaderField(TableConstants.TABLE_SERVICE_PREFIX_FOR_TABLE_CONTINUATION - .concat(TableConstants.TABLE_SERVICE_NEXT_MARKER)); - if (tString != null) { - retVal.setNextMarker(tString); - foundToken = true; - } - - tString = queryRequest.getHeaderField(TableConstants.TABLE_SERVICE_PREFIX_FOR_TABLE_CONTINUATION - .concat(TableConstants.TABLE_SERVICE_NEXT_TABLE_NAME)); - if (tString != null) { - retVal.setNextTableName(tString); - foundToken = true; - } - - return foundToken ? retVal : null; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableResult.java deleted file mode 100644 index 6ede801908f5b..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableResult.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.util.HashMap; - -/** - * A class which represents the result of a table operation. The {@link TableResult} class encapsulates the HTTP - * response - * and any table entity results returned by the Storage Service REST API operation called for a particular - * {@link TableOperation}. - * - */ -public class TableResult { - private Object result; - - private int httpStatusCode = -1; - - private String id; - - private String etag; - - private HashMap properties; - - /** - * Initializes an empty {@link TableResult} instance. - */ - public TableResult() { - // empty ctor - } - - /** - * Initializes a {@link TableResult} instance with the specified HTTP status code. - * - * @param httpStatusCode - * The HTTP status code for the table operation returned by the server. - */ - public TableResult(final int httpStatusCode) { - this.httpStatusCode = httpStatusCode; - } - - /** - * Gets the Etag returned with the table operation results. The server will return the same Etag value for a - * table, entity, or entity group returned by an operation as long as it is unchanged on the server. - * - * @return - * A String containing the Etag returned by the server with the table operation results. - */ - public String getEtag() { - return this.etag; - } - - /** - * Gets the HTTP status code returned by a table operation request. - * - * @return - * The HTTP status code for the table operation returned by the server. - */ - public int getHttpStatusCode() { - return this.httpStatusCode; - } - - /** - * Gets the AtomPub Entry Request ID value for the result returned by a table operation request. - * - * @return - * The Entry Request ID for the table operation result. - */ - public String getId() { - return this.id; - } - - /** - * Gets the map of properties for a table entity returned by the table operation. - * - * @return - * A java.util.HashMap of String property names to {@link EntityProperty} data - * typed values representing the properties of a table entity. - */ - public HashMap getProperties() { - return this.properties; - } - - /** - * Gets the result returned by the table operation as an Object. - * - * @return - * The result returned by the table operation as an Object. - */ - public Object getResult() { - return this.result; - } - - /** - * Gets the result returned by the table operation as an instance of the specified type. - * - * @return - * The result returned by the table operation as an instance of type T. - */ - @SuppressWarnings("unchecked") - public T getResultAsType() { - return (T) this.getResult(); - } - - /** - * Reserved for internal use. Sets the Etag associated with the table operation results. - * - * @param etag - * A String containing an Etag to associate with the table operation results. - */ - protected void setEtag(final String etag) { - this.etag = etag; - } - - /** - * Reserved for internal use. Sets the HTTP status code associated with the table operation results. - * - * @param httpStatusCode - * The HTTP status code value to associate with the table operation results. - */ - protected void setHttpStatusCode(final int httpStatusCode) { - this.httpStatusCode = httpStatusCode; - } - - /** - * Reserved for internal use. Sets the AtomPub Entry Request ID associated with the table operation result. - * - * @param id - * A String containing the request ID to associate with the table operation result. - */ - protected void setId(final String id) { - this.id = id; - } - - /** - * Reserved for internal use. Sets the map of properties for a table entity to associate with the table operation. - * - * @param properties - * A java.util.HashMap of String property names to {@link EntityProperty} data - * typed values representing the properties of a table entity to associate with the table operation. - */ - protected void setProperties(final HashMap properties) { - this.properties = properties; - } - - /** - * Reserved for internal use. Sets a result Object instance to associate with the table operation. - * - * @param result - * An instance of a result Object to associate with the table operation. - */ - protected void setResult(final Object result) { - this.result = result; - } - - /** - * Reserved for internal use. Sets the result to associate with the table operation as a {@link TableEntity}. - * - * @param ent - * An instance of an object implementing {@link TableEntity} to associate with the table operation. - */ - protected void updateResultObject(final TableEntity ent) { - this.result = ent; - ent.setEtag(this.etag); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableServiceEntity.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableServiceEntity.java deleted file mode 100644 index fe8efb7ec1f76..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableServiceEntity.java +++ /dev/null @@ -1,414 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.lang.reflect.InvocationTargetException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map.Entry; - -import com.microsoft.windowsazure.services.core.storage.Constants; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * The {@link TableServiceEntity} class represents the base object type for a table entity in the Storage service. - * {@link TableServiceEntity} provides a base implementation for the {@link TableEntity} interface that provides - * readEntity and writeEntity methods that by default serialize and deserialize all properties - * via reflection. A table entity class may extend this class and override the readEntity and - * writeEntity methods to provide customized or more performant serialization logic. - *

- * The use of reflection allows subclasses of {@link TableServiceEntity} to be serialized and deserialized without - * having to implement the serialization code themselves. When both a getter method and setter method are found for a - * given property name and data type, then the appropriate method is invoked automatically to serialize or deserialize - * the data. To take advantage of the automatic serialization code, your table entity classes should provide getter and - * setter methods for each property in the corresponding table entity in Windows Azure table storage. The reflection - * code looks for getter and setter methods in pairs of the form - *

- * public type getPropertyName() { ... } - *

- * and - *

- * public void setPropertyName(type parameter) { ... } - *

- * where PropertyName is a property name for the table entity, and type is a Java type compatible with - * the EDM data type of the property. See the table below for a map of property types to their Java equivalents. The - * {@link StoreAs} annotation may be applied with a name attribute to specify a property name for - * reflection on getter and setter methods that do not follow the property name convention. Method names and the - * name attribute of {@link StoreAs} annotations are case sensitive for matching property names with - * reflection. Use the {@link Ignore} annotation to prevent methods from being used by reflection for automatic - * serialization and deserialization. Note that the names "PartitionKey", "RowKey", "Timestamp", and "Etag" are reserved - * and will be ignored if set with the {@link StoreAs} annotation in a subclass. - *

- * The following table shows the supported property data types in Windows Azure storage and the corresponding Java types - * when deserialized. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Storage TypeEdmType ValueJava TypeDescription
Edm.Binary{@link EdmType#BINARY}byte[], Byte[]An array of bytes up to 64 KB in size.
Edm.Boolean{@link EdmType#BOOLEAN}boolean, BooleanA Boolean value.
Edm.Byte{@link EdmType#BYTE}byte, ByteAn 8-bit integer value.
Edm.DateTime{@link EdmType#DATE_TIME}DateA 64-bit value expressed as Coordinated Universal Time (UTC). The supported range begins from 12:00 midnight, - * January 1, 1601 A.D. (C.E.), UTC. The range ends at December 31, 9999.
Edm.Double{@link EdmType#DOUBLE}double, DoubleA 64-bit double-precision floating point value.
Edm.Guid{@link EdmType#GUID}UUIDA 128-bit globally unique identifier.
Edm.Int32{@link EdmType#INT32}int, IntegerA 32-bit integer value.
Edm.Int64{@link EdmType#INT64}long, LongA 64-bit integer value.
Edm.String{@link EdmType#STRING}StringA UTF-16-encoded value. String values may be up to 64 KB in size.
- *

- * See the MSDN topic Understanding the - * Table Service Data Model for an overview of tables, entities, and properties as used in the Windows Azure Storage - * service. - *

- * For an overview of the available EDM primitive data types and names, see the - * - * Primitive Data Types section of - * the OData Protocol Overview. - *

- * - * @see EdmType - */ -public class TableServiceEntity implements TableEntity { - /** - * Deserializes the table entity property map into the specified object instance using reflection. - *

- * This static method takes an object instance that represents a table entity type and uses reflection on its class - * type to find methods to deserialize the data from the property map into the instance. - *

- * Each property name and data type in the properties map is compared with the methods in the class type for a pair - * of getter and setter methods to use for serialization and deserialization. The class is scanned for methods with - * names that match the property name with "get" and "set" prepended, or with the {@link StoreAs} annotation set - * with the property name. The methods must have return types or parameter data types that match the data type of - * the corresponding {@link EntityProperty} value. If such a pair is found, the data is copied into the instance - * object by invoking the setter method on the instance. Properties that do not match a method pair by name and data - * type are not copied. - * - * @param instance - * A reference to an instance of a class implementing {@link TableEntity} to deserialize the table entity - * data into. - * @param properties - * A map of String property names to {@link EntityProperty} objects containing typed data - * values to deserialize into the instance parameter object. - * @param opContext - * An {@link OperationContext} object that represents the context for the current operation. - * - * @throws IllegalArgumentException - * if the table entity response received is invalid or improperly formatted. - * @throws IllegalAccessException - * if the table entity threw an exception during deserialization. - * @throws InvocationTargetException - * if a method invoked on the instance parameter threw an exception during deserialization. - */ - public static void readEntityWithReflection(final Object instance, - final HashMap properties, final OperationContext opContext) - throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - final HashMap props = PropertyPair.generatePropertyPairs(instance.getClass()); - - for (final Entry p : properties.entrySet()) { - if (props.containsKey(p.getKey())) { - // TODO add logging - // System.out.println("Consuming " + p.getKey() + ":" + p.getValue().getValueAsString()); - props.get(p.getKey()).consumeTableProperty(p.getValue(), instance); - } - } - } - - /** - * Serializes the property data from a table entity instance into a property map using reflection. - *

- * This static method takes an object instance that represents a table entity type and uses reflection on its class - * type to find methods to serialize the data from the instance into the property map. - *

- * Each property name and data type in the properties map is compared with the methods in the class type for a pair - * of getter and setter methods to use for serialization and deserialization. The class is scanned for methods with - * names that match the property name with "get" and "set" prepended, or with the {@link StoreAs} annotation set - * with the property name. The methods must have return types or parameter data types that match the data type of - * the corresponding {@link EntityProperty} value. If such a pair is found, the data is copied from the instance - * object by invoking the getter method on the instance. Properties that do not have a method pair with matching - * name and data type are not copied. - * - * @param instance - * A reference to an instance of a class implementing {@link TableEntity} to serialize the table entity - * data from. - * @return - * A map of String property names to {@link EntityProperty} objects containing typed data - * values serialized from the instance parameter object. - * - * @throws IllegalArgumentException - * if the table entity is invalid or improperly formatted. - * @throws IllegalAccessException - * if the table entity threw an exception during serialization. - * @throws InvocationTargetException - * if a method invoked on the instance parameter threw an exception during serialization. - */ - public static HashMap writeEntityWithReflection(final Object instance) - throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - final HashMap props = PropertyPair.generatePropertyPairs(instance.getClass()); - - final HashMap retVal = new HashMap(); - for (final Entry p : props.entrySet()) { - retVal.put(p.getValue().effectiveName, p.getValue().generateTableProperty(instance)); - } - - return retVal; - } - - /** - * Reserved for internal use. The value of the partition key in the entity. - */ - protected String partitionKey = null; - - /** - * Reserved for internal use. The value of the row key in the entity. - */ - protected String rowKey = null; - - /** - * Reserved for internal use. The value of the Etag for the entity. - */ - protected String etag = null; - - /** - * Reserved for internal use. The value of the Timestamp in the entity. - */ - protected Date timeStamp = new Date(); - - /** - * Initializes an empty {@link TableServiceEntity} instance. - */ - public TableServiceEntity() { - // Empty ctor - } - - /** - * Gets the Etag value for the entity. This value is used to determine if the table entity has changed since it was - * last read from Windows Azure storage. - * - * @return - * A String containing the Etag for the entity. - */ - @Override - public String getEtag() { - return this.etag; - } - - /** - * Gets the PartitionKey value for the entity. - * - * @return - * A String containing the PartitionKey value for the entity. - */ - @Override - public String getPartitionKey() { - return this.partitionKey; - } - - /** - * Gets the RowKey value for the entity. - * - * @return - * A String containing the RowKey value for the entity. - */ - @Override - public String getRowKey() { - return this.rowKey; - } - - /** - * Gets the Timestamp value for the entity. - * - * @return - * A Date containing the Timestamp value for the entity. - */ - @Override - public Date getTimestamp() { - return this.timeStamp; - } - - /** - * Populates this table entity instance using the map of property names to {@link EntityProperty} data typed values. - *

- * This method invokes {@link TableServiceEntity#readEntityWithReflection} to populate the table entity instance the - * method is called on using reflection. Table entity classes that extend {@link TableServiceEntity} can take - * advantage of this behavior by implementing getter and setter methods for the particular properties of the table - * entity in Windows Azure storage the class represents. - *

- * Override this method in classes that extend {@link TableServiceEntity} to invoke custom serialization code. - * - * @param properties - * The java.util.HashMap of String property names to {@link EntityProperty} - * data values to deserialize and store in this table entity instance. - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * @throws StorageException - * if an error occurs during the deserialization. - */ - @Override - public void readEntity(final HashMap properties, final OperationContext opContext) - throws StorageException { - try { - readEntityWithReflection(this, properties, opContext); - } - catch (IllegalArgumentException e) { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The response received is invalid or improperly formatted.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, e); - } - catch (IllegalAccessException e) { - throw new StorageException(StorageErrorCodeStrings.INVALID_XML_DOCUMENT, - "The entity threw an exception during deserialization", Constants.HeaderConstants.HTTP_UNUSED_306, - null, e); - } - catch (InvocationTargetException e) { - throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, - "The entity threw an exception during deserialization", Constants.HeaderConstants.HTTP_UNUSED_306, - null, e); - } - } - - /** - * Sets the Etag value for the entity. This value is used to determine if the table entity has changed since it was - * last read from Windows Azure storage. - * - * @param etag - * A String containing the Etag for the entity. - */ - @Override - public void setEtag(final String etag) { - this.etag = etag; - } - - /** - * Sets the PartitionKey value for the entity. - * - * @param partitionKey - * A String containing the PartitionKey value for the entity. - */ - @Override - public void setPartitionKey(final String partitionKey) { - this.partitionKey = partitionKey; - } - - /** - * Sets the RowKey value for the entity. - * - * @param rowKey - * A String containing the RowKey value for the entity. - */ - @Override - public void setRowKey(final String rowKey) { - this.rowKey = rowKey; - } - - /** - * Sets the Timestamp value for the entity. - * - * @param timeStamp - * A Date containing the Timestamp value for the entity. - */ - @Override - public void setTimestamp(final Date timeStamp) { - this.timeStamp = timeStamp; - } - - /** - * Returns a map of property names to {@link EntityProperty} data typed values created by serializing this table - * entity instance. - *

- * This method invokes {@link #writeEntityWithReflection} to serialize the table entity instance the method is - * called on using reflection. Table entity classes that extend {@link TableServiceEntity} can take advantage of - * this behavior by implementing getter and setter methods for the particular properties of the table entity in - * Windows Azure storage the class represents. Note that the property names "PartitionKey", "RowKey", and - * "Timestamp" are reserved and will be ignored if set on other methods with the {@link StoreAs} annotation. - *

- * Override this method in classes that extend {@link TableServiceEntity} to invoke custom serialization code. - * - * @param opContext - * An {@link OperationContext} object used to track the execution of the operation. - * @return - * A java.util.HashMap of String property names to {@link EntityProperty} data - * typed values representing the properties serialized from this table entity instance. - * @throws StorageException - * if an error occurs during the serialization. - */ - @Override - public HashMap writeEntity(final OperationContext opContext) throws StorageException { - try { - return writeEntityWithReflection(this); - } - catch (final IllegalAccessException e) { - throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, - "An attempt was made to access an inaccessible member of the entity during serialization.", - Constants.HeaderConstants.HTTP_UNUSED_306, null, e); - } - catch (final InvocationTargetException e) { - throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, - "The entity threw an exception during serialization", Constants.HeaderConstants.HTTP_UNUSED_306, - null, e); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableServiceException.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableServiceException.java deleted file mode 100644 index 494a304abcc4e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableServiceException.java +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; - -import javax.xml.stream.XMLStreamException; - -import com.microsoft.windowsazure.services.core.storage.RequestResult; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.core.storage.StorageExtendedErrorInformation; -import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageErrorResponse; - -/** - * An exception that results when a table storage service operation fails to complete successfully. - */ -public class TableServiceException extends StorageException { - - private static final long serialVersionUID = 6037366449663934891L; - - /** - * Reserved for internal use. A static factory method to create a {@link TableServiceException} instance using - * the specified parameters. - * - * @param retryable - * A flag indicating the table operation can be retried. - * @param res - * A {@link RequestResult} containing the result of the table storage service operation. - * @param op - * The {@link TableOperation} representing the table operation that caused the exception. - * @param inStream - * The java.io.InputStream of the error response from the table operation request. - * @return - * A {@link TableServiceException} instance initialized with values from the input parameters. - * @throws IOException - * if an IO error occurs. - */ - protected static TableServiceException generateTableServiceException(boolean retryable, RequestResult res, - TableOperation op, InputStream inStream) throws IOException { - try { - TableServiceException retryableException = new TableServiceException(res.getStatusCode(), - res.getStatusMessage(), op, new InputStreamReader(inStream)); - retryableException.retryable = retryable; - - return retryableException; - } - finally { - inStream.close(); - } - } - - private TableOperation operation; - - /** - * Reserved for internal use. This flag indicates whether the operation that threw the exception can be retried. - */ - protected boolean retryable = false; - - /** - * Constructs a TableServiceException instance using the specified error code, message, status code, - * extended error information and inner exception. - * - * @param errorCode - * A String that represents the error code returned by the table operation. - * @param message - * A String that represents the error message returned by the table operation. - * @param statusCode - * The HTTP status code returned by the table operation. - * @param extendedErrorInfo - * A {@link StorageExtendedErrorInformation} object that represents the extended error information - * returned by the table operation. - * @param innerException - * An Exception object that represents a reference to the initial exception, if one exists. - */ - public TableServiceException(final String errorCode, final String message, final int statusCode, - final StorageExtendedErrorInformation extendedErrorInfo, final Exception innerException) { - super(errorCode, message, statusCode, extendedErrorInfo, innerException); - } - - /** - * Reserved for internal use. Constructs a TableServiceException instance using the specified HTTP - * status code, message, operation, and stream reader. - * - * @param httpStatusCode - * The int HTTP Status Code value returned by the table operation that caused the exception. - * @param message - * A String description of the error that caused the exception. - * @param operation - * The {@link TableOperation} object representing the table operation that was in progress when the - * exception occurred. - * @param reader - * The Java.IO.Stream derived stream reader for the HTTP request results returned by the - * table operation, if any. - */ - protected TableServiceException(final int httpStatusCode, final String message, final TableOperation operation, - final Reader reader) { - super(null, message, httpStatusCode, null, null); - this.operation = operation; - - if (reader != null) { - try { - final StorageErrorResponse error = new StorageErrorResponse(reader); - this.extendedErrorInformation = error.getExtendedErrorInformation(); - this.errorCode = this.extendedErrorInformation.getErrorCode(); - } - catch (XMLStreamException e) { - // no-op, if error parsing fails, just throw first exception. - } - } - } - - /** - * Gets the table operation that caused the TableServiceException to be thrown. - * - * @return - * The {@link TableOperation} object representing the table operation that caused this - * {@link TableServiceException} to be thrown. - */ - public TableOperation getOperation() { - return this.operation; - } - - /** - * Reserved for internal use. Gets a flag indicating the table operation can be retried. - * - * @return - * The boolean flag indicating whether the table operation that caused the exception can be - * retried. - */ - public boolean isRetryable() { - return this.retryable; - } - - /** - * Reserved for internal use. Sets the table operation that caused the TableServiceException to be - * thrown. - * - * @param operation - * The {@link TableOperation} object representing the table operation that caused this - * {@link TableServiceException} to be thrown. - */ - protected void setOperation(final TableOperation operation) { - this.operation = operation; - } - - /** - * Reserved for internal use. Sets a flag indicating the table operation can be retried. - * - * @param retryable - * The boolean flag to set indicating whether the table operation that caused the exception - * can be retried. - */ - protected void setRetryable(boolean retryable) { - this.retryable = retryable; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableUpdateType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableUpdateType.java deleted file mode 100644 index 94e63a882be3f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/TableUpdateType.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.table.client; - -/** - * Reserved for internal use. An enum that represents the type of update a given upsert operation will perform. - */ -enum TableUpdateType { - /** - * The table operation updates an existing entity. - */ - MERGE, - - /** - * The table operation replaces an existing entity. - */ - REPLACE; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/package.html deleted file mode 100644 index 6a84c85156b23..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/client/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the integrated table service client classes and implementation. - - diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/AtomReaderWriter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/AtomReaderWriter.java deleted file mode 100644 index 18e20e08abb58..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/AtomReaderWriter.java +++ /dev/null @@ -1,356 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.inject.Inject; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamWriter; - -import com.microsoft.windowsazure.services.core.ISO8601DateConverter; -import com.microsoft.windowsazure.services.core.utils.DateFactory; -import com.microsoft.windowsazure.services.table.EdmValueConverter; -import com.microsoft.windowsazure.services.table.models.Entity; -import com.microsoft.windowsazure.services.table.models.Property; -import com.microsoft.windowsazure.services.table.models.TableEntry; - -public class AtomReaderWriter { - private final XMLStreamFactory xmlStreamFactory; - private final DateFactory dateFactory; - private final ISO8601DateConverter iso8601DateConverter; - private final EdmValueConverter edmValueConverter; - - @Inject - public AtomReaderWriter(XMLStreamFactory xmlStreamFactory, DateFactory dateFactory, - ISO8601DateConverter iso8601DateConverter, EdmValueConverter edmValueConverter) { - this.xmlStreamFactory = xmlStreamFactory; - this.dateFactory = dateFactory; - this.iso8601DateConverter = iso8601DateConverter; - this.edmValueConverter = edmValueConverter; - } - - public InputStream generateTableEntry(String table) { - final String tableTemp = table; - return generateEntry(new PropertiesWriter() { - @Override - public void write(XMLStreamWriter writer) throws XMLStreamException { - writer.writeStartElement("d:TableName"); - writer.writeCharacters(tableTemp); - writer.writeEndElement(); // d:TableName - } - }); - } - - public InputStream generateEntityEntry(Entity entity) { - final Entity entityTemp = entity; - return generateEntry(new PropertiesWriter() { - @Override - public void write(XMLStreamWriter writer) throws XMLStreamException { - for (Entry entry : entityTemp.getProperties().entrySet()) { - writer.writeStartElement("d:" + entry.getKey()); - - String edmType = entry.getValue().getEdmType(); - if (edmType != null) { - writer.writeAttribute("m:type", edmType); - } - - String value = edmValueConverter.serialize(edmType, entry.getValue().getValue()); - - if ((edmType != null) && (edmType == "Edm.String")) { - value = encodeNumericCharacterReference(value); - } - - if (value != null) { - writer.writeCharacters(value); - } - else { - writer.writeAttribute("m:null", "true"); - } - - writer.writeEndElement(); // property name - - } - } - }); - } - - public List parseTableEntries(InputStream stream) { - try { - XMLStreamReader xmlr = xmlStreamFactory.getReader(stream); - - expect(xmlr, XMLStreamConstants.START_DOCUMENT); - expect(xmlr, XMLStreamConstants.START_ELEMENT, "feed"); - - List result = new ArrayList(); - while (!isEndElement(xmlr, "feed")) { - // Process "entry" elements only - if (isStartElement(xmlr, "entry")) { - result.add(parseTableEntry(xmlr)); - } - else { - nextSignificant(xmlr); - } - } - - expect(xmlr, XMLStreamConstants.END_ELEMENT, "feed"); - expect(xmlr, XMLStreamConstants.END_DOCUMENT); - - return result; - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - public TableEntry parseTableEntry(InputStream stream) { - try { - XMLStreamReader xmlr = xmlStreamFactory.getReader(stream); - - expect(xmlr, XMLStreamConstants.START_DOCUMENT); - TableEntry result = parseTableEntry(xmlr); - expect(xmlr, XMLStreamConstants.END_DOCUMENT); - - return result; - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - public List parseEntityEntries(InputStream stream) { - try { - XMLStreamReader xmlr = xmlStreamFactory.getReader(stream); - - expect(xmlr, XMLStreamConstants.START_DOCUMENT); - expect(xmlr, XMLStreamConstants.START_ELEMENT, "feed"); - - List result = new ArrayList(); - while (!isEndElement(xmlr, "feed")) { - // Process "entry" elements only - if (isStartElement(xmlr, "entry")) { - result.add(parseEntityEntry(xmlr)); - } - else { - nextSignificant(xmlr); - } - } - - expect(xmlr, XMLStreamConstants.END_ELEMENT, "feed"); - expect(xmlr, XMLStreamConstants.END_DOCUMENT); - - return result; - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - public Entity parseEntityEntry(InputStream stream) { - try { - XMLStreamReader xmlr = xmlStreamFactory.getReader(stream); - - expect(xmlr, XMLStreamConstants.START_DOCUMENT); - Entity result = parseEntityEntry(xmlr); - expect(xmlr, XMLStreamConstants.END_DOCUMENT); - - return result; - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - private interface PropertiesWriter { - void write(XMLStreamWriter writer) throws XMLStreamException; - } - - private InputStream generateEntry(PropertiesWriter propertiesWriter) { - try { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - XMLStreamWriter writer = xmlStreamFactory.getWriter(stream); - writer.writeStartDocument("utf-8", "1.0"); - - writer.writeStartElement("entry"); - writer.writeAttribute("xmlns:d", "http://schemas.microsoft.com/ado/2007/08/dataservices"); - writer.writeAttribute("xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"); - writer.writeAttribute("xmlns", "http://www.w3.org/2005/Atom"); - - writer.writeStartElement("title"); - writer.writeEndElement(); // title - - writer.writeStartElement("updated"); - writer.writeCharacters(iso8601DateConverter.format(dateFactory.getDate())); - writer.writeEndElement(); // updated - - writer.writeStartElement("author"); - writer.writeStartElement("name"); - writer.writeEndElement(); // name - writer.writeEndElement(); // author - - writer.writeStartElement("id"); - writer.writeEndElement(); // id - - writer.writeStartElement("content"); - writer.writeAttribute("type", "application/xml"); - - writer.writeStartElement("m:properties"); - propertiesWriter.write(writer); - writer.writeEndElement(); // m:properties - - writer.writeEndElement(); // content - - writer.writeEndElement(); // entry - - writer.writeEndDocument(); - writer.close(); - - return new ByteArrayInputStream(stream.toByteArray()); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - private TableEntry parseTableEntry(XMLStreamReader xmlr) throws XMLStreamException { - TableEntry result = new TableEntry(); - - expect(xmlr, XMLStreamConstants.START_ELEMENT, "entry"); - - while (!isEndElement(xmlr, "entry")) { - if (isStartElement(xmlr, "properties")) { - Map properties = parseEntryProperties(xmlr); - - result.setName((String) properties.get("TableName").getValue()); - } - else { - nextSignificant(xmlr); - } - } - - expect(xmlr, XMLStreamConstants.END_ELEMENT, "entry"); - - return result; - } - - private Entity parseEntityEntry(XMLStreamReader xmlr) throws XMLStreamException { - Entity result = new Entity(); - - result.setEtag(xmlr.getAttributeValue(null, "etag")); - expect(xmlr, XMLStreamConstants.START_ELEMENT, "entry"); - - while (!isEndElement(xmlr, "entry")) { - if (isStartElement(xmlr, "properties")) { - result.setProperties(parseEntryProperties(xmlr)); - } - else { - nextSignificant(xmlr); - } - } - - expect(xmlr, XMLStreamConstants.END_ELEMENT, "entry"); - - return result; - } - - private Map parseEntryProperties(XMLStreamReader xmlr) throws XMLStreamException { - Map result = new HashMap(); - - expect(xmlr, XMLStreamConstants.START_ELEMENT, "properties"); - - while (!isEndElement(xmlr, "properties")) { - String name = xmlr.getLocalName(); - String edmType = xmlr.getAttributeValue(null, "type"); - - xmlr.next(); - - // Use concatenation instead of StringBuilder as most text is just one element. - String serializedValue = ""; - while (!xmlr.isEndElement()) { - serializedValue += xmlr.getText(); - xmlr.next(); - } - - Object value = edmValueConverter.deserialize(edmType, serializedValue); - - result.put(name, new Property().setEdmType(edmType).setValue(value)); - - expect(xmlr, XMLStreamConstants.END_ELEMENT, name); - } - - expect(xmlr, XMLStreamConstants.END_ELEMENT, "properties"); - - return result; - } - - private void nextSignificant(XMLStreamReader xmlr) throws XMLStreamException { - if (!xmlr.hasNext()) - return; - xmlr.next(); - - while (xmlr.isCharacters()) { - if (!xmlr.hasNext()) - return; - xmlr.next(); - } - } - - private boolean isStartElement(XMLStreamReader xmlr, String localName) { - return xmlr.isStartElement() && localName.equals(xmlr.getLocalName()); - } - - private boolean isEndElement(XMLStreamReader xmlr, String localName) { - return xmlr.isEndElement() && localName.equals(xmlr.getLocalName()); - } - - private void expect(XMLStreamReader xmlr, int eventType) throws XMLStreamException { - expect(xmlr, eventType, null); - } - - private void expect(XMLStreamReader xmlr, int eventType, String localName) throws XMLStreamException { - xmlr.require(eventType, null, localName); - nextSignificant(xmlr); - } - - private String encodeNumericCharacterReference(String value) { - if (value == null) { - return null; - } - else { - char[] charArray = value.toCharArray(); - StringBuffer stringBuffer = new StringBuffer(); - for (int index = 0; index < charArray.length; index++) { - if (isIllegalChar(charArray[index])) - stringBuffer.append("&#x").append(Integer.toHexString(charArray[index])).append(";"); - else - stringBuffer.append(charArray[index]); - } - return stringBuffer.toString(); - } - } - - private boolean isIllegalChar(char c) { - return !(c == 9 || c == 0xA || c == 0xD || (c >= 0x20 && c < 0xFFFE)); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/DefaultEdmValueConverter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/DefaultEdmValueConverter.java deleted file mode 100644 index de73a55c8c627..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/DefaultEdmValueConverter.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.text.ParseException; -import java.util.Date; -import java.util.UUID; - -import javax.inject.Inject; - -import com.microsoft.windowsazure.services.core.ISO8601DateConverter; -import com.microsoft.windowsazure.services.table.EdmValueConverter; -import com.microsoft.windowsazure.services.table.models.EdmType; -import com.sun.jersey.core.util.Base64; - -public class DefaultEdmValueConverter implements EdmValueConverter { - - private final ISO8601DateConverter iso8601DateConverter; - - @Inject - public DefaultEdmValueConverter(ISO8601DateConverter iso8601DateConverter) { - this.iso8601DateConverter = iso8601DateConverter; - } - - @Override - public String serialize(String edmType, Object value) { - if (value == null) - return null; - - String serializedValue; - if (value instanceof Date) { - serializedValue = iso8601DateConverter.format((Date) value); - } - else if (value instanceof byte[]) { - serializedValue = new String(Base64.encode((byte[]) value)); - } - else { - serializedValue = value.toString(); - } - - return serializedValue; - } - - @Override - public Object deserialize(String edmType, String value) { - if (edmType == null) - return value; - - if (EdmType.DATETIME.equals(edmType)) { - try { - return iso8601DateConverter.parse(value); - } - catch (ParseException e) { - throw new RuntimeException(e); - } - } - else if (EdmType.BOOLEAN.equals(edmType)) { - return Boolean.parseBoolean(value); - } - else if (EdmType.DOUBLE.equals(edmType)) { - return Double.parseDouble(value); - } - else if (EdmType.INT32.equals(edmType)) { - return Integer.parseInt(value); - } - else if (EdmType.INT64.equals(edmType)) { - return Long.parseLong(value); - } - else if (EdmType.BINARY.equals(edmType)) { - return Base64.decode(value); - } - else if (EdmType.GUID.equals(edmType)) { - return UUID.fromString(value); - } - - return value; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/DefaultXMLStreamFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/DefaultXMLStreamFactory.java deleted file mode 100644 index 9447472f8cb2a..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/DefaultXMLStreamFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamWriter; - -public class DefaultXMLStreamFactory implements XMLStreamFactory { - private final XMLOutputFactory xmlOutputFactory; - private final XMLInputFactory xmlInputFactory; - - public DefaultXMLStreamFactory() { - this.xmlOutputFactory = XMLOutputFactory.newInstance(); - this.xmlInputFactory = XMLInputFactory.newInstance(); - } - - @Override - public XMLStreamWriter getWriter(OutputStream stream) { - try { - return xmlOutputFactory.createXMLStreamWriter(stream, "UTF-8"); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - @Override - public XMLStreamReader getReader(InputStream stream) { - try { - return xmlInputFactory.createXMLStreamReader(stream); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/HttpReaderWriter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/HttpReaderWriter.java deleted file mode 100644 index 10dd2360c8557..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/HttpReaderWriter.java +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.Enumeration; - -import javax.activation.DataSource; -import javax.inject.Inject; -import javax.mail.Header; -import javax.mail.MessagingException; -import javax.mail.internet.InternetHeaders; - -import com.sun.mail.util.LineInputStream; - -public class HttpReaderWriter { - - @Inject - public HttpReaderWriter() { - } - - public StatusLine parseStatusLine(DataSource ds) { - try { - LineInputStream stream = new LineInputStream(ds.getInputStream()); - try { - String line = stream.readLine(); - StringReader lineReader = new StringReader(line); - - expect(lineReader, "HTTP/1.1"); - expect(lineReader, " "); - String statusString = extractInput(lineReader, ' '); - String reason = extractInput(lineReader, -1); - - return new StatusLine().setStatus(Integer.parseInt(statusString)).setReason(reason); - } - finally { - stream.close(); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public InternetHeaders parseHeaders(DataSource ds) { - try { - return new InternetHeaders(ds.getInputStream()); - } - catch (MessagingException e) { - throw new RuntimeException(e); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public InputStream parseEntity(DataSource ds) { - try { - return ds.getInputStream(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void appendMethod(OutputStream stream, String verb, URI uri) { - try { - String method = String.format("%s %s %s\r\n", verb, uri, "HTTP/1.1"); - stream.write(method.getBytes("UTF-8")); - } - catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void appendHeaders(OutputStream stream, InternetHeaders headers) { - try { - // Headers - @SuppressWarnings("unchecked") - Enumeration

e = headers.getAllHeaders(); - while (e.hasMoreElements()) { - Header header = e.nextElement(); - - String headerLine = String.format("%s: %s\r\n", header.getName(), header.getValue()); - stream.write(headerLine.getBytes("UTF-8")); - } - - // Empty line - stream.write("\r\n".getBytes("UTF-8")); - } - catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void appendEntity(OutputStream stream, InputStream entity) { - try { - byte[] buffer = new byte[1024]; - while (true) { - int n = entity.read(buffer); - if (n == -1) - break; - stream.write(buffer, 0, n); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - private void expect(Reader reader, String string) { - try { - for (int i = 0; i < string.length(); i++) { - int ch = reader.read(); - if (ch < 0) - throw new RuntimeException(String.format("Expected '%s', found '%s' instead", string, - string.substring(0, i) + ch)); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - private String extractInput(Reader reader, int delimiter) { - try { - StringBuilder sb = new StringBuilder(); - while (true) { - int ch = reader.read(); - if (ch == -1 || ch == delimiter) - break; - - sb.append((char) ch); - } - return sb.toString(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public class StatusLine { - private int status; - private String reason; - - public int getStatus() { - return status; - } - - public StatusLine setStatus(int status) { - this.status = status; - return this; - } - - public String getReason() { - return reason; - } - - public StatusLine setReason(String reason) { - this.reason = reason; - return this; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/MimeReaderWriter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/MimeReaderWriter.java deleted file mode 100644 index efcc33f78b2cc..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/MimeReaderWriter.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.inject.Inject; -import javax.mail.BodyPart; -import javax.mail.MessagingException; -import javax.mail.MultipartDataSource; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMultipart; -import javax.mail.internet.MimePartDataSource; - -public class MimeReaderWriter { - - @Inject - public MimeReaderWriter() { - } - - public MimeMultipart getMimeMultipart(List bodyPartContents) { - try { - return getMimeMultipartCore(bodyPartContents); - } - catch (MessagingException e) { - throw new RuntimeException(e); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - private MimeMultipart getMimeMultipartCore(List bodyPartContents) throws MessagingException, - IOException { - // Create unique part boundary strings - String batchId = String.format("batch_%s", UUID.randomUUID().toString()); - String changeSet = String.format("changeset_%s", UUID.randomUUID().toString()); - - // - // Build inner list of change sets containing the list of body part content - // - MimeMultipart changeSets = new MimeMultipart(new SetBoundaryMultipartDataSource(changeSet)); - - for (DataSource bodyPart : bodyPartContents) { - MimeBodyPart mimeBodyPart = new MimeBodyPart(); - - mimeBodyPart.setDataHandler(new DataHandler(bodyPart)); - mimeBodyPart.setHeader("Content-Type", bodyPart.getContentType()); - mimeBodyPart.setHeader("Content-Transfer-Encoding", "binary"); - - changeSets.addBodyPart(mimeBodyPart); - } - - // - // Build outer "batch" body part - // - MimeBodyPart batchbody = new MimeBodyPart(); - batchbody.setContent(changeSets); - //Note: Both content type and encoding need to be set *after* setting content, because - // MimeBodyPart implementation replaces them when calling "setContent". - batchbody.setHeader("Content-Type", changeSets.getContentType()); - - // - // Build outer "batch" multipart - // - MimeMultipart batch = new MimeMultipart(new SetBoundaryMultipartDataSource(batchId)); - batch.addBodyPart(batchbody); - return batch; - } - - /** - * The only purpose of this class is to force the boundary of a MimeMultipart instance. - * This is done by simple passing an instance of this class to the constructor of MimeMultipart. - */ - private class SetBoundaryMultipartDataSource implements MultipartDataSource { - - private final String boundary; - - public SetBoundaryMultipartDataSource(String boundary) { - this.boundary = boundary; - } - - @Override - public String getContentType() { - return "multipart/mixed; boundary=" + boundary; - } - - @Override - public InputStream getInputStream() throws IOException { - return null; - } - - @Override - public String getName() { - return null; - } - - @Override - public OutputStream getOutputStream() throws IOException { - return null; - } - - @Override - public int getCount() { - return 0; - } - - @Override - public BodyPart getBodyPart(int index) throws MessagingException { - return null; - } - } - - public List parseParts(final InputStream entityInputStream, final String contentType) { - try { - return parsePartsCore(entityInputStream, contentType); - } - catch (IOException e) { - throw new RuntimeException(e); - } - catch (MessagingException e) { - throw new RuntimeException(e); - } - } - - private List parsePartsCore(InputStream entityInputStream, String contentType) - throws MessagingException, IOException { - DataSource ds = new InputStreamDataSource(entityInputStream, contentType); - MimeMultipart batch = new MimeMultipart(ds); - MimeBodyPart batchBody = (MimeBodyPart) batch.getBodyPart(0); - - MimeMultipart changeSets = new MimeMultipart(new MimePartDataSource(batchBody)); - - List result = new ArrayList(); - for (int i = 0; i < changeSets.getCount(); i++) { - BodyPart part = changeSets.getBodyPart(i); - - result.add(new InputStreamDataSource(part.getInputStream(), part.getContentType())); - } - return result; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/SharedKeyFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/SharedKeyFilter.java deleted file mode 100644 index 352115a45dbae..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/SharedKeyFilter.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.util.List; - -import javax.inject.Named; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.blob.implementation.SharedKeyUtils; -import com.microsoft.windowsazure.services.blob.implementation.SharedKeyUtils.QueryParam; -import com.microsoft.windowsazure.services.table.TableConfiguration; -import com.sun.jersey.api.client.ClientRequest; - -public class SharedKeyFilter extends com.microsoft.windowsazure.services.blob.implementation.SharedKeyFilter { - private static Log log = LogFactory.getLog(SharedKeyFilter.class); - - public SharedKeyFilter(@Named(TableConfiguration.ACCOUNT_NAME) String accountName, - @Named(TableConfiguration.ACCOUNT_KEY) String accountKey) { - super(accountName, accountKey); - } - - /* - * StringToSign = VERB + "\n" + - * Content-MD5 + "\n" + - * Content-Type + "\n" + - * Date + "\n" + - * CanonicalizedResource; - */ - @Override - public void sign(ClientRequest cr) { - // gather signed material - addOptionalDateHeader(cr); - - // build signed string - String stringToSign = cr.getMethod() + "\n" + getHeader(cr, "Content-MD5") + "\n" - + getHeader(cr, "Content-Type") + "\n" + getHeader(cr, "Date") + "\n"; - - stringToSign += getCanonicalizedResource(cr); - - if (log.isDebugEnabled()) { - log.debug(String.format("String to sign: \"%s\"", stringToSign)); - } - - String signature = this.getSigner().sign(stringToSign); - cr.getHeaders().putSingle("Authorization", "SharedKey " + this.getAccountName() + ":" + signature); - } - - /** - * This format supports Shared Key and Shared Key Lite for all versions of the Table service, and Shared Key Lite - * for the 2009-09-19 version of the Blob and Queue services. This format is identical to that used with previous - * versions of the storage services. Construct the CanonicalizedResource string in this format as follows: - * - * 1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns - * the resource being accessed. - * - * 2. Append the resource's encoded URI path. If the request URI addresses a component of the resource, append the - * appropriate query string. The query string should include the question mark and the comp parameter (for example, - * ?comp=metadata). No other parameters should be included on the query string. - */ - private String getCanonicalizedResource(ClientRequest cr) { - String result = "/" + this.getAccountName(); - - result += cr.getURI().getRawPath(); - - List queryParams = SharedKeyUtils.getQueryParams(cr.getURI().getQuery()); - for (QueryParam p : queryParams) { - if ("comp".equals(p.getName())) { - result += "?" + p.getName() + "=" + p.getValues().get(0); - } - } - return result; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/SharedKeyLiteFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/SharedKeyLiteFilter.java deleted file mode 100644 index cc048c5c8d3d2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/SharedKeyLiteFilter.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import javax.inject.Named; - -import com.microsoft.windowsazure.services.table.TableConfiguration; - -public class SharedKeyLiteFilter extends com.microsoft.windowsazure.services.blob.implementation.SharedKeyLiteFilter { - public SharedKeyLiteFilter(@Named(TableConfiguration.ACCOUNT_NAME) String accountName, - @Named(TableConfiguration.ACCOUNT_KEY) String accountKey) { - super(accountName, accountKey); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/TableExceptionProcessor.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/TableExceptionProcessor.java deleted file mode 100644 index 3642189a8168f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/TableExceptionProcessor.java +++ /dev/null @@ -1,464 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import javax.inject.Inject; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.microsoft.windowsazure.services.table.TableContract; -import com.microsoft.windowsazure.services.table.models.BatchOperations; -import com.microsoft.windowsazure.services.table.models.BatchResult; -import com.microsoft.windowsazure.services.table.models.DeleteEntityOptions; -import com.microsoft.windowsazure.services.table.models.Entity; -import com.microsoft.windowsazure.services.table.models.GetEntityResult; -import com.microsoft.windowsazure.services.table.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.table.models.GetTableResult; -import com.microsoft.windowsazure.services.table.models.InsertEntityResult; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesOptions; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesResult; -import com.microsoft.windowsazure.services.table.models.QueryTablesOptions; -import com.microsoft.windowsazure.services.table.models.QueryTablesResult; -import com.microsoft.windowsazure.services.table.models.ServiceProperties; -import com.microsoft.windowsazure.services.table.models.TableServiceOptions; -import com.microsoft.windowsazure.services.table.models.UpdateEntityResult; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.UniformInterfaceException; - -public class TableExceptionProcessor implements TableContract { - private static Log log = LogFactory.getLog(TableExceptionProcessor.class); - private final TableContract service; - - @Inject - public TableExceptionProcessor(TableRestProxy service) { - this.service = service; - } - - public TableExceptionProcessor(TableContract service) { - this.service = service; - } - - @Override - public TableContract withFilter(ServiceFilter filter) { - return new TableExceptionProcessor(service.withFilter(filter)); - } - - private ServiceException processCatch(ServiceException e) { - log.warn(e.getMessage(), e.getCause()); - return ServiceExceptionFactory.process("table", e); - } - - @Override - public GetServicePropertiesResult getServiceProperties() throws ServiceException { - try { - return service.getServiceProperties(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetServicePropertiesResult getServiceProperties(TableServiceOptions options) throws ServiceException { - try { - return service.getServiceProperties(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException { - try { - service.setServiceProperties(serviceProperties); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties, TableServiceOptions options) - throws ServiceException { - try { - service.setServiceProperties(serviceProperties, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void createTable(String table) throws ServiceException { - try { - service.createTable(table); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void createTable(String table, TableServiceOptions options) throws ServiceException { - try { - service.createTable(table, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetTableResult getTable(String table) throws ServiceException { - try { - return service.getTable(table); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetTableResult getTable(String table, TableServiceOptions options) throws ServiceException { - try { - return service.getTable(table, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteTable(String table) throws ServiceException { - try { - service.deleteTable(table); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteTable(String table, TableServiceOptions options) throws ServiceException { - try { - service.deleteTable(table, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public QueryTablesResult queryTables() throws ServiceException { - try { - return service.queryTables(); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public QueryTablesResult queryTables(QueryTablesOptions options) throws ServiceException { - try { - return service.queryTables(options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public InsertEntityResult insertEntity(String table, Entity entity) throws ServiceException { - try { - return service.insertEntity(table, entity); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public InsertEntityResult insertEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - try { - return service.insertEntity(table, entity, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult updateEntity(String table, Entity entity) throws ServiceException { - try { - return service.updateEntity(table, entity); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult updateEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - try { - return service.updateEntity(table, entity, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult mergeEntity(String table, Entity entity) throws ServiceException { - try { - return service.mergeEntity(table, entity); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult mergeEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - try { - return service.mergeEntity(table, entity, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult insertOrReplaceEntity(String table, Entity entity) throws ServiceException { - try { - return service.insertOrReplaceEntity(table, entity); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult insertOrReplaceEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - try { - return service.insertOrReplaceEntity(table, entity, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult insertOrMergeEntity(String table, Entity entity) throws ServiceException { - try { - return service.insertOrMergeEntity(table, entity); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public UpdateEntityResult insertOrMergeEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - try { - return service.insertOrMergeEntity(table, entity, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteEntity(String table, String partitionKey, String rowKey) throws ServiceException { - try { - service.deleteEntity(table, partitionKey, rowKey); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public void deleteEntity(String table, String partitionKey, String rowKey, DeleteEntityOptions options) - throws ServiceException { - try { - service.deleteEntity(table, partitionKey, rowKey, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetEntityResult getEntity(String table, String partitionKey, String rowKey) throws ServiceException { - try { - return service.getEntity(table, partitionKey, rowKey); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public GetEntityResult getEntity(String table, String partitionKey, String rowKey, TableServiceOptions options) - throws ServiceException { - try { - return service.getEntity(table, partitionKey, rowKey, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public QueryEntitiesResult queryEntities(String table) throws ServiceException { - try { - return service.queryEntities(table); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public QueryEntitiesResult queryEntities(String table, QueryEntitiesOptions options) throws ServiceException { - try { - return service.queryEntities(table, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public BatchResult batch(BatchOperations operations) throws ServiceException { - try { - return service.batch(operations); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } - - @Override - public BatchResult batch(BatchOperations operations, TableServiceOptions options) throws ServiceException { - try { - return service.batch(operations, options); - } - catch (UniformInterfaceException e) { - throw processCatch(new ServiceException(e)); - } - catch (ClientHandlerException e) { - throw processCatch(new ServiceException(e)); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/TableRestProxy.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/TableRestProxy.java deleted file mode 100644 index 6b6f62b30860c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/TableRestProxy.java +++ /dev/null @@ -1,912 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.Enumeration; -import java.util.Formatter; -import java.util.List; -import java.util.UUID; - -import javax.activation.DataSource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.mail.Header; -import javax.mail.internet.InternetHeaders; -import javax.mail.internet.MimeMultipart; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import com.microsoft.windowsazure.services.core.ISO8601DateConverter; -import com.microsoft.windowsazure.services.core.RFC1123DateConverter; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.core.utils.CommaStringBuilder; -import com.microsoft.windowsazure.services.core.utils.DateFactory; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.microsoft.windowsazure.services.core.utils.pipeline.ClientFilterAdapter; -import com.microsoft.windowsazure.services.core.utils.pipeline.HttpURLConnectionClient; -import com.microsoft.windowsazure.services.core.utils.pipeline.PipelineHelpers; -import com.microsoft.windowsazure.services.table.TableConfiguration; -import com.microsoft.windowsazure.services.table.TableContract; -import com.microsoft.windowsazure.services.table.implementation.HttpReaderWriter.StatusLine; -import com.microsoft.windowsazure.services.table.models.BatchOperations; -import com.microsoft.windowsazure.services.table.models.BatchOperations.DeleteEntityOperation; -import com.microsoft.windowsazure.services.table.models.BatchOperations.InsertEntityOperation; -import com.microsoft.windowsazure.services.table.models.BatchOperations.InsertOrMergeEntityOperation; -import com.microsoft.windowsazure.services.table.models.BatchOperations.InsertOrReplaceEntityOperation; -import com.microsoft.windowsazure.services.table.models.BatchOperations.MergeEntityOperation; -import com.microsoft.windowsazure.services.table.models.BatchOperations.Operation; -import com.microsoft.windowsazure.services.table.models.BatchOperations.UpdateEntityOperation; -import com.microsoft.windowsazure.services.table.models.BatchResult; -import com.microsoft.windowsazure.services.table.models.BatchResult.DeleteEntity; -import com.microsoft.windowsazure.services.table.models.BatchResult.Entry; -import com.microsoft.windowsazure.services.table.models.BatchResult.Error; -import com.microsoft.windowsazure.services.table.models.BatchResult.InsertEntity; -import com.microsoft.windowsazure.services.table.models.BatchResult.UpdateEntity; -import com.microsoft.windowsazure.services.table.models.BinaryFilter; -import com.microsoft.windowsazure.services.table.models.ConstantFilter; -import com.microsoft.windowsazure.services.table.models.DeleteEntityOptions; -import com.microsoft.windowsazure.services.table.models.Entity; -import com.microsoft.windowsazure.services.table.models.Filter; -import com.microsoft.windowsazure.services.table.models.GetEntityResult; -import com.microsoft.windowsazure.services.table.models.GetServicePropertiesResult; -import com.microsoft.windowsazure.services.table.models.GetTableResult; -import com.microsoft.windowsazure.services.table.models.InsertEntityResult; -import com.microsoft.windowsazure.services.table.models.PropertyNameFilter; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesOptions; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesResult; -import com.microsoft.windowsazure.services.table.models.QueryStringFilter; -import com.microsoft.windowsazure.services.table.models.QueryTablesOptions; -import com.microsoft.windowsazure.services.table.models.QueryTablesResult; -import com.microsoft.windowsazure.services.table.models.ServiceProperties; -import com.microsoft.windowsazure.services.table.models.TableServiceOptions; -import com.microsoft.windowsazure.services.table.models.UnaryFilter; -import com.microsoft.windowsazure.services.table.models.UpdateEntityResult; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; -import com.sun.jersey.core.header.InBoundHeaders; -import com.sun.jersey.core.util.ReaderWriter; - -public class TableRestProxy implements TableContract { - private static final String API_VERSION = "2011-08-18"; - private final HttpURLConnectionClient channel; - private final String url; - private final RFC1123DateConverter dateMapper; - private final ISO8601DateConverter iso8601DateConverter; - private final DateFactory dateFactory; - private final ServiceFilter[] filters; - private final SharedKeyFilter filter; - private final AtomReaderWriter atomReaderWriter; - private final MimeReaderWriter mimeReaderWriter; - private final HttpReaderWriter httpReaderWriter; - - @Inject - public TableRestProxy(HttpURLConnectionClient channel, @Named(TableConfiguration.URI) String url, - SharedKeyFilter filter, UserAgentFilter userAgentFilter, DateFactory dateFactory, - ISO8601DateConverter iso8601DateConverter, AtomReaderWriter atomReaderWriter, - MimeReaderWriter mimeReaderWriter, HttpReaderWriter httpReaderWriter) { - - this.channel = channel; - this.url = url; - this.filter = filter; - this.dateMapper = new RFC1123DateConverter(); - this.iso8601DateConverter = iso8601DateConverter; - this.filters = new ServiceFilter[0]; - this.dateFactory = dateFactory; - this.atomReaderWriter = atomReaderWriter; - this.mimeReaderWriter = mimeReaderWriter; - this.httpReaderWriter = httpReaderWriter; - channel.addFilter(filter); - channel.addFilter(userAgentFilter); - } - - public TableRestProxy(HttpURLConnectionClient channel, ServiceFilter[] filters, String url, SharedKeyFilter filter, - DateFactory dateFactory, AtomReaderWriter atomReaderWriter, MimeReaderWriter mimeReaderWriter, - HttpReaderWriter httpReaderWriter, RFC1123DateConverter dateMapper, - ISO8601DateConverter iso8601DateConverter) { - - this.channel = channel; - this.filters = filters; - this.url = url; - this.filter = filter; - this.dateFactory = dateFactory; - this.atomReaderWriter = atomReaderWriter; - this.mimeReaderWriter = mimeReaderWriter; - this.httpReaderWriter = httpReaderWriter; - this.dateMapper = dateMapper; - this.iso8601DateConverter = iso8601DateConverter; - } - - @Override - public TableContract withFilter(ServiceFilter filter) { - ServiceFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1); - newFilters[filters.length] = filter; - return new TableRestProxy(this.channel, newFilters, this.url, this.filter, this.dateFactory, - this.atomReaderWriter, this.mimeReaderWriter, this.httpReaderWriter, this.dateMapper, - this.iso8601DateConverter); - } - - private void ThrowIfError(ClientResponse r) { - PipelineHelpers.ThrowIfError(r); - } - - private String encodeODataURIValue(String value) { - return value; - } - - private List encodeODataURIValues(List values) { - List list = new ArrayList(); - for (String value : values) { - list.add(encodeODataURIValue(value)); - } - return list; - } - - private String getEntityPath(String table, String partitionKey, String rowKey) { - return table + "(" + "PartitionKey='" + safeEncode(partitionKey) + "',RowKey='" + safeEncode(rowKey) + "')"; - } - - private String safeEncode(String input) { - String fixSingleQuotes = input.replace("'", "''"); - try { - return URLEncoder.encode(fixSingleQuotes, "UTF-8").replace("+", "%20"); - } - catch (UnsupportedEncodingException e) { - return fixSingleQuotes; - } - } - - private WebResource addOptionalQueryParam(WebResource webResource, String key, Object value) { - return PipelineHelpers.addOptionalQueryParam(webResource, key, value); - } - - private WebResource addOptionalQueryEntitiesOptions(WebResource webResource, - QueryEntitiesOptions queryEntitiesOptions) { - if (queryEntitiesOptions == null) - return webResource; - - if (queryEntitiesOptions.getSelectFields() != null && queryEntitiesOptions.getSelectFields().size() > 0) { - webResource = addOptionalQueryParam(webResource, "$select", - CommaStringBuilder.join(encodeODataURIValues(queryEntitiesOptions.getSelectFields()))); - } - - if (queryEntitiesOptions.getTop() != null) { - webResource = addOptionalQueryParam(webResource, "$top", encodeODataURIValue(queryEntitiesOptions.getTop() - .toString())); - } - - if (queryEntitiesOptions.getFilter() != null) { - webResource = addOptionalQueryParam(webResource, "$filter", - buildFilterExpression(queryEntitiesOptions.getFilter())); - } - - if (queryEntitiesOptions.getOrderByFields() != null) { - webResource = addOptionalQueryParam(webResource, "$orderby", - CommaStringBuilder.join(encodeODataURIValues(queryEntitiesOptions.getOrderByFields()))); - } - - return webResource; - } - - private String buildFilterExpression(Filter filter) { - StringBuilder sb = new StringBuilder(); - buildFilterExpression(filter, sb); - return sb.toString(); - } - - private void buildFilterExpression(Filter filter, StringBuilder sb) { - if (filter == null) - return; - - if (filter instanceof PropertyNameFilter) { - sb.append(((PropertyNameFilter) filter).getPropertyName()); - } - else if (filter instanceof ConstantFilter) { - Object value = ((ConstantFilter) filter).getValue(); - if (value == null) { - sb.append("null"); - } - else if (value.getClass() == Long.class) { - sb.append(value); - sb.append("L"); - } - else if (value.getClass() == Date.class) { - ISO8601DateConverter dateConverter = new ISO8601DateConverter(); - sb.append("datetime'"); - sb.append(dateConverter.format((Date) value)); - sb.append("'"); - } - else if (value.getClass() == UUID.class) { - sb.append("(guid'"); - sb.append(value); - sb.append("')"); - } - else if (value.getClass() == String.class) { - sb.append("'"); - sb.append(((String) value).replace("'", "''")); - sb.append("'"); - } - else if (value.getClass() == byte[].class) { - sb.append("X'"); - byte[] byteArray = (byte[]) value; - Formatter formatter = new Formatter(sb); - for (byte b : byteArray) { - formatter.format("%02x", b); - } - formatter.flush(); - formatter.close(); - sb.append("'"); - } - else if (value.getClass() == Byte[].class) { - sb.append("X'"); - Byte[] byteArray = (Byte[]) value; - Formatter formatter = new Formatter(sb); - for (Byte b : byteArray) { - formatter.format("%02x", b); - } - formatter.flush(); - formatter.close(); - sb.append("'"); - } - else { - sb.append(value); - } - } - else if (filter instanceof UnaryFilter) { - sb.append(((UnaryFilter) filter).getOperator()); - sb.append("("); - buildFilterExpression(((UnaryFilter) filter).getOperand(), sb); - sb.append(")"); - } - else if (filter instanceof BinaryFilter) { - sb.append("("); - buildFilterExpression(((BinaryFilter) filter).getLeft(), sb); - sb.append(" "); - sb.append(((BinaryFilter) filter).getOperator()); - sb.append(" "); - buildFilterExpression(((BinaryFilter) filter).getRight(), sb); - sb.append(")"); - } - else if (filter instanceof QueryStringFilter) { - sb.append(((QueryStringFilter) filter).getQueryString()); - } - } - - private Builder addOptionalHeader(Builder builder, String name, Object value) { - return PipelineHelpers.addOptionalHeader(builder, name, value); - } - - private WebResource.Builder addTableRequestHeaders(WebResource.Builder builder) { - builder = addOptionalHeader(builder, "x-ms-version", API_VERSION); - builder = addOptionalHeader(builder, "DataServiceVersion", "1.0;NetFx"); - builder = addOptionalHeader(builder, "MaxDataServiceVersion", "2.0;NetFx"); - builder = addOptionalHeader(builder, "Accept", "application/atom+xml,application/xml"); - builder = addOptionalHeader(builder, "Accept-Charset", "UTF-8"); - return builder; - } - - private WebResource.Builder addIfMatchHeader(WebResource.Builder builder, String eTag) { - builder = addOptionalHeader(builder, "If-Match", eTag == null ? "*" : eTag); - return builder; - } - - private WebResource getResource(TableServiceOptions options) { - WebResource webResource = channel.resource(url).path("/"); - for (ServiceFilter filter : filters) { - webResource.addFilter(new ClientFilterAdapter(filter)); - } - - return webResource; - } - - @Override - public GetServicePropertiesResult getServiceProperties() throws ServiceException { - return getServiceProperties(new TableServiceOptions()); - } - - @Override - public GetServicePropertiesResult getServiceProperties(TableServiceOptions options) throws ServiceException { - WebResource webResource = getResource(options).path("/").queryParam("resType", "service") - .queryParam("comp", "properties"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - - GetServicePropertiesResult result = new GetServicePropertiesResult(); - result.setValue(builder.get(ServiceProperties.class)); - return result; - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties) throws ServiceException { - setServiceProperties(serviceProperties, new TableServiceOptions()); - } - - @Override - public void setServiceProperties(ServiceProperties serviceProperties, TableServiceOptions options) - throws ServiceException { - if (serviceProperties == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path("/").queryParam("resType", "service") - .queryParam("comp", "properties"); - - WebResource.Builder builder = webResource.header("x-ms-version", API_VERSION); - - builder.put(serviceProperties); - } - - @Override - public GetTableResult getTable(String table) throws ServiceException { - return getTable(table, new TableServiceOptions()); - } - - @Override - public GetTableResult getTable(String table, TableServiceOptions options) throws ServiceException { - if (table == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path("Tables" + "('" + table + "')"); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - GetTableResult result = new GetTableResult(); - result.setTableEntry(atomReaderWriter.parseTableEntry(response.getEntityInputStream())); - return result; - } - - @Override - public QueryTablesResult queryTables() throws ServiceException { - return queryTables(new QueryTablesOptions()); - } - - @Override - public QueryTablesResult queryTables(QueryTablesOptions options) throws ServiceException { - Filter queryFilter = options.getFilter(); - String nextTableName = options.getNextTableName(); - String prefix = options.getPrefix(); - - if (prefix != null) { - // Append Max char to end '{' is 1 + 'z' in AsciiTable ==> upperBound is prefix + '{' - Filter prefixFilter = Filter.and(Filter.ge(Filter.propertyName("TableName"), Filter.constant(prefix)), - Filter.le(Filter.propertyName("TableName"), Filter.constant(prefix + "{"))); - - if (queryFilter == null) { - queryFilter = prefixFilter; - } - else { - queryFilter = Filter.and(queryFilter, prefixFilter); - } - } - - WebResource webResource = getResource(options).path("Tables"); - webResource = addOptionalQueryParam(webResource, "$filter", buildFilterExpression(queryFilter)); - webResource = addOptionalQueryParam(webResource, "NextTableName", nextTableName); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - QueryTablesResult result = new QueryTablesResult(); - result.setNextTableName(response.getHeaders().getFirst("x-ms-continuation-NextTableName")); - result.setTables(atomReaderWriter.parseTableEntries(response.getEntityInputStream())); - - return result; - } - - @Override - public void createTable(String table) throws ServiceException { - createTable(table, new TableServiceOptions()); - - } - - @Override - public void createTable(String table, TableServiceOptions options) throws ServiceException { - if (table == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path("Tables"); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - - builder.entity(atomReaderWriter.generateTableEntry(table), "application/atom+xml"); - - ClientResponse response = builder.post(ClientResponse.class); - ThrowIfError(response); - } - - @Override - public void deleteTable(String table) throws ServiceException { - deleteTable(table, new TableServiceOptions()); - } - - @Override - public void deleteTable(String table, TableServiceOptions options) throws ServiceException { - if (table == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path("Tables" + "('" + table + "')"); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - builder = addOptionalHeader(builder, "Content-Type", "application/atom+xml"); - - ClientResponse response = builder.delete(ClientResponse.class); - ThrowIfError(response); - } - - @Override - public InsertEntityResult insertEntity(String table, Entity entity) throws ServiceException { - return insertEntity(table, entity, new TableServiceOptions()); - } - - @Override - public InsertEntityResult insertEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - if (table == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(table); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - - builder = builder.entity(atomReaderWriter.generateEntityEntry(entity), "application/atom+xml"); - - ClientResponse response = builder.post(ClientResponse.class); - ThrowIfError(response); - - InsertEntityResult result = new InsertEntityResult(); - result.setEntity(atomReaderWriter.parseEntityEntry(response.getEntityInputStream())); - - return result; - } - - @Override - public UpdateEntityResult updateEntity(String table, Entity entity) throws ServiceException { - return updateEntity(table, entity, new TableServiceOptions()); - } - - @Override - public UpdateEntityResult updateEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - return putOrMergeEntityCore(table, entity, "PUT", true/*includeEtag*/, options); - } - - @Override - public UpdateEntityResult mergeEntity(String table, Entity entity) throws ServiceException { - return mergeEntity(table, entity, new TableServiceOptions()); - } - - @Override - public UpdateEntityResult mergeEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - return putOrMergeEntityCore(table, entity, "MERGE", true/*includeEtag*/, options); - } - - @Override - public UpdateEntityResult insertOrReplaceEntity(String table, Entity entity) throws ServiceException { - return insertOrReplaceEntity(table, entity, new TableServiceOptions()); - } - - @Override - public UpdateEntityResult insertOrReplaceEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - return putOrMergeEntityCore(table, entity, "PUT", false/*includeEtag*/, options); - } - - @Override - public UpdateEntityResult insertOrMergeEntity(String table, Entity entity) throws ServiceException { - return insertOrMergeEntity(table, entity, new TableServiceOptions()); - } - - @Override - public UpdateEntityResult insertOrMergeEntity(String table, Entity entity, TableServiceOptions options) - throws ServiceException { - return putOrMergeEntityCore(table, entity, "MERGE", false/*includeEtag*/, options); - } - - private UpdateEntityResult putOrMergeEntityCore(String table, Entity entity, String verb, boolean includeEtag, - TableServiceOptions options) throws ServiceException { - if (table == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path( - getEntityPath(table, entity.getPartitionKey(), entity.getRowKey())); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - if (includeEtag) { - builder = addIfMatchHeader(builder, entity.getEtag()); - } - if (verb == "MERGE") { - builder = builder.header("X-HTTP-Method", "MERGE"); - verb = "POST"; - } - - builder = builder.entity(atomReaderWriter.generateEntityEntry(entity), "application/atom+xml"); - - ClientResponse response = builder.method(verb, ClientResponse.class); - ThrowIfError(response); - - UpdateEntityResult result = new UpdateEntityResult(); - result.setEtag(response.getHeaders().getFirst("ETag")); - - return result; - } - - @Override - public void deleteEntity(String table, String partitionKey, String rowKey) throws ServiceException { - deleteEntity(table, partitionKey, rowKey, new DeleteEntityOptions()); - } - - @Override - public void deleteEntity(String table, String partitionKey, String rowKey, DeleteEntityOptions options) - throws ServiceException { - if (table == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(getEntityPath(table, partitionKey, rowKey)); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - builder = addIfMatchHeader(builder, options.getEtag()); - - ClientResponse response = builder.delete(ClientResponse.class); - ThrowIfError(response); - } - - @Override - public GetEntityResult getEntity(String table, String partitionKey, String rowKey) throws ServiceException { - return getEntity(table, partitionKey, rowKey, new TableServiceOptions()); - } - - @Override - public GetEntityResult getEntity(String table, String partitionKey, String rowKey, TableServiceOptions options) - throws ServiceException { - if (table == null) - throw new NullPointerException(); - - WebResource webResource = getResource(options).path(getEntityPath(table, partitionKey, rowKey)); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - GetEntityResult result = new GetEntityResult(); - result.setEntity(atomReaderWriter.parseEntityEntry(response.getEntityInputStream())); - - return result; - } - - @Override - public QueryEntitiesResult queryEntities(String table) throws ServiceException { - return queryEntities(table, new QueryEntitiesOptions()); - } - - @Override - public QueryEntitiesResult queryEntities(String table, QueryEntitiesOptions options) throws ServiceException { - if (table == null) - throw new NullPointerException(); - - if (options == null) - options = new QueryEntitiesOptions(); - - WebResource webResource = getResource(options).path(table); - webResource = addOptionalQueryEntitiesOptions(webResource, options); - webResource = addOptionalQueryParam(webResource, "NextPartitionKey", - encodeODataURIValue(options.getNextPartitionKey())); - webResource = addOptionalQueryParam(webResource, "NextRowKey", encodeODataURIValue(options.getNextRowKey())); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - - ClientResponse response = builder.get(ClientResponse.class); - ThrowIfError(response); - - QueryEntitiesResult result = new QueryEntitiesResult(); - result.setNextPartitionKey(response.getHeaders().getFirst("x-ms-continuation-NextPartitionKey")); - result.setNextRowKey(response.getHeaders().getFirst("x-ms-continuation-NextRowKey")); - result.setEntities(atomReaderWriter.parseEntityEntries(response.getEntityInputStream())); - - return result; - } - - @Override - public BatchResult batch(BatchOperations operations) throws ServiceException { - return batch(operations, new TableServiceOptions()); - } - - @Override - public BatchResult batch(BatchOperations operations, TableServiceOptions options) throws ServiceException { - WebResource webResource = getResource(options).path("$batch"); - - WebResource.Builder builder = webResource.getRequestBuilder(); - builder = addTableRequestHeaders(builder); - - MimeMultipart entity = createBatchRequestBody(operations); - builder = builder.type(entity.getContentType()); - - ClientResponse response = builder.post(ClientResponse.class, entity); - ThrowIfError(response); - - BatchResult result = new BatchResult(); - - try { - result.setEntries(parseBatchResponse(response, operations)); - } - catch (IOException e) { - throw new ServiceException(e); - } - - return result; - } - - private MimeMultipart createBatchRequestBody(BatchOperations operations) { - List bodyPartContents = new ArrayList(); - int contentId = 1; - for (Operation operation : operations.getOperations()) { - - DataSource bodyPartContent = null; - if (operation instanceof InsertEntityOperation) { - InsertEntityOperation op = (InsertEntityOperation) operation; - bodyPartContent = createBatchInsertOrUpdateEntityPart(op.getTable(), op.getEntity(), "POST", - false/*includeEtag*/, contentId); - contentId++; - } - else if (operation instanceof UpdateEntityOperation) { - UpdateEntityOperation op = (UpdateEntityOperation) operation; - bodyPartContent = createBatchInsertOrUpdateEntityPart(op.getTable(), op.getEntity(), "PUT", - true/*includeEtag*/, contentId); - contentId++; - } - else if (operation instanceof MergeEntityOperation) { - MergeEntityOperation op = (MergeEntityOperation) operation; - bodyPartContent = createBatchInsertOrUpdateEntityPart(op.getTable(), op.getEntity(), "MERGE", - true/*includeEtag*/, contentId); - contentId++; - } - else if (operation instanceof InsertOrReplaceEntityOperation) { - InsertOrReplaceEntityOperation op = (InsertOrReplaceEntityOperation) operation; - bodyPartContent = createBatchInsertOrUpdateEntityPart(op.getTable(), op.getEntity(), "PUT", - false/*includeEtag*/, contentId); - contentId++; - } - else if (operation instanceof InsertOrMergeEntityOperation) { - InsertOrMergeEntityOperation op = (InsertOrMergeEntityOperation) operation; - bodyPartContent = createBatchInsertOrUpdateEntityPart(op.getTable(), op.getEntity(), "MERGE", - false/*includeEtag*/, contentId); - contentId++; - } - else if (operation instanceof DeleteEntityOperation) { - DeleteEntityOperation op = (DeleteEntityOperation) operation; - bodyPartContent = createBatchDeleteEntityPart(op.getTable(), op.getPartitionKey(), op.getRowKey(), - op.getEtag(), contentId); - contentId++; - } - - if (bodyPartContent != null) { - bodyPartContents.add(bodyPartContent); - } - } - - return mimeReaderWriter.getMimeMultipart(bodyPartContents); - } - - private DataSource createBatchInsertOrUpdateEntityPart(String table, Entity entity, String verb, - boolean includeEtag, int contentId) { - - URI path; - if ("POST".equals(verb)) { - path = channel.resource(url).path(table).getURI(); - } - else { - path = channel.resource(url).path(getEntityPath(table, entity.getPartitionKey(), entity.getRowKey())) - .getURI(); - } - - // - // Stream content into byte[] so that we have the length - // - InputStream stream = atomReaderWriter.generateEntityEntry(entity); - byte[] bytes = inputStreamToByteArray(stream); - - // - // Create body of MIME part as the HTTP request - // - InternetHeaders headers = new InternetHeaders(); - headers.addHeader("Content-ID", Integer.toString(contentId)); - headers.addHeader("Content-Type", "application/atom+xml;type=entry"); - headers.addHeader("Content-Length", Integer.toString(bytes.length)); - if (includeEtag) { - headers.addHeader("If-Match", entity.getEtag()); - } - - ByteArrayOutputStream httpRequest = new ByteArrayOutputStream(); - httpReaderWriter.appendMethod(httpRequest, verb, path); - httpReaderWriter.appendHeaders(httpRequest, headers); - httpReaderWriter.appendEntity(httpRequest, new ByteArrayInputStream(bytes)); - - DataSource bodyPartContent = new InputStreamDataSource(new ByteArrayInputStream(httpRequest.toByteArray()), - "application/http"); - return bodyPartContent; - } - - private DataSource createBatchDeleteEntityPart(String table, String partitionKey, String rowKey, String etag, - int contentId) { - - URI path = channel.resource(url).path(getEntityPath(table, partitionKey, rowKey)).getURI(); - - // - // Create body of MIME part as the HTTP request - // - InternetHeaders headers = new InternetHeaders(); - headers.addHeader("Content-ID", Integer.toString(contentId)); - headers.addHeader("If-Match", etag == null ? "*" : etag); - - ByteArrayOutputStream httpRequest = new ByteArrayOutputStream(); - httpReaderWriter.appendMethod(httpRequest, "DELETE", path); - httpReaderWriter.appendHeaders(httpRequest, headers); - httpReaderWriter.appendEntity(httpRequest, new ByteArrayInputStream(new byte[0])); - - DataSource bodyPartContent = new InputStreamDataSource(new ByteArrayInputStream(httpRequest.toByteArray()), - "application/http"); - return bodyPartContent; - } - - private List parseBatchResponse(ClientResponse response, BatchOperations operations) throws IOException { - // Default stream cannot be reset, but it is needed by multiple parts of this method. - // Replace the default response stream with one that can be read multiple times. - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - InputStream inputStream = response.getEntityInputStream(); - ReaderWriter.writeTo(inputStream, byteArrayOutputStream); - response.setEntityInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); - - List parts = mimeReaderWriter.parseParts(response.getEntityInputStream(), response.getHeaders() - .getFirst("Content-Type")); - - if (parts.size() == 0 || parts.size() > operations.getOperations().size()) { - throw new UniformInterfaceException(String.format( - "Batch response from server does not contain the correct amount " - + "of parts (expecting %d, received %d instead)", parts.size(), operations.getOperations() - .size()), response); - } - - Entry[] entries = new Entry[operations.getOperations().size()]; - for (int i = 0; i < parts.size(); i++) { - DataSource ds = parts.get(i); - Operation operation = operations.getOperations().get(i); - - StatusLine status = httpReaderWriter.parseStatusLine(ds); - InternetHeaders headers = httpReaderWriter.parseHeaders(ds); - InputStream content = httpReaderWriter.parseEntity(ds); - ByteArrayOutputStream contentByteArrayOutputStream = new ByteArrayOutputStream(); - ReaderWriter.writeTo(content, contentByteArrayOutputStream); - content = new ByteArrayInputStream(contentByteArrayOutputStream.toByteArray()); - - if (status.getStatus() >= 400) { - // Create dummy client response with status, headers and content - InBoundHeaders inBoundHeaders = new InBoundHeaders(); - - @SuppressWarnings("unchecked") - Enumeration
e = headers.getAllHeaders(); - while (e.hasMoreElements()) { - Header header = e.nextElement(); - inBoundHeaders.putSingle(header.getName(), header.getValue()); - } - - ClientResponse dummyResponse = new ClientResponse(status.getStatus(), inBoundHeaders, content, null); - - // Wrap into a ServiceException - UniformInterfaceException exception = new UniformInterfaceException(dummyResponse); - ServiceException serviceException = new ServiceException(exception); - serviceException = ServiceExceptionFactory.process("table", serviceException); - Error error = new Error().setError(serviceException); - - // Parse the message to find which operation caused this error. - try { - XMLInputFactory xmlStreamFactory = XMLInputFactory.newFactory(); - content.reset(); - XMLStreamReader xmlStreamReader = xmlStreamFactory.createXMLStreamReader(content); - - while (xmlStreamReader.hasNext()) { - xmlStreamReader.next(); - if (xmlStreamReader.isStartElement() && "message".equals(xmlStreamReader.getLocalName())) { - xmlStreamReader.next(); - // Process "message" elements only - String message = xmlStreamReader.getText(); - int colonIndex = message.indexOf(':'); - String errorOpId = message.substring(0, colonIndex); - int opId = Integer.parseInt(errorOpId); - entries[opId] = error; - break; - } - } - xmlStreamReader.close(); - } - catch (XMLStreamException e1) { - throw new UniformInterfaceException( - "Batch response from server does not contain XML in the expected format", response); - } - } - else if (operation instanceof InsertEntityOperation) { - InsertEntity opResult = new InsertEntity().setEntity(atomReaderWriter.parseEntityEntry(content)); - entries[i] = opResult; - } - else if ((operation instanceof UpdateEntityOperation) || (operation instanceof MergeEntityOperation) - || (operation instanceof InsertOrReplaceEntityOperation) - || (operation instanceof InsertOrMergeEntityOperation)) { - UpdateEntity opResult = new UpdateEntity().setEtag(headers.getHeader("ETag", null)); - entries[i] = opResult; - } - else if (operation instanceof DeleteEntityOperation) { - DeleteEntity opResult = new DeleteEntity(); - entries[i] = opResult; - } - } - - List result = new ArrayList(); - for (int i = 0; i < entries.length; i++) { - result.add(entries[i]); - } - - return result; - } - - private byte[] inputStreamToByteArray(InputStream inputStream) { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - - byte[] buffer = new byte[1024]; - try { - while (true) { - int n = inputStream.read(buffer); - if (n == -1) - break; - outputStream.write(buffer, 0, n); - } - } - finally { - inputStream.close(); - } - return outputStream.toByteArray(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/XMLStreamFactory.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/XMLStreamFactory.java deleted file mode 100644 index cd61e66a59771..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/XMLStreamFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.XMLStreamWriter; - -public interface XMLStreamFactory { - XMLStreamWriter getWriter(OutputStream stream); - - XMLStreamReader getReader(InputStream stream); -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/package.html deleted file mode 100644 index 4032bfee5276f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/implementation/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the implementation of the table service classes and utilities. - - diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BatchOperations.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BatchOperations.java deleted file mode 100644 index 849d69c28e537..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BatchOperations.java +++ /dev/null @@ -1,613 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import java.util.ArrayList; -import java.util.List; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the collection of table operations that may be sent as a single batch transaction with a - * {@link TableContract#batch(BatchOperations)} or {@link TableContract#batch(BatchOperations, TableServiceOptions)} - * request. A batch transaction is executed by the Storage Service REST API as a single atomic operation, by invoking an - * Entity Group Transaction. - *

- * A batch operation may contain up to 100 individual table operations, with the requirement that the target entity of - * each operation must have same partition key. A batch with a query operation cannot contain any other operations. Note - * that the total payload of a batch operation is limited to 4MB. - *

- * The semantics for entity group transactions are defined by the WCF Data Services Batching Operations. The WCF Data - * Services specification defines the following concepts for batch requests: - *

    - *
  • A change set is a group of one or more insert, update, or delete operations.
  • - *
  • A batch is a container of operations, including one or more change sets and query operations.
  • - *
- *

- * The Table service supports a subset of the functionality defined by WCF Data Services: - *

    - *
  • The Table service supports only a single change set within a batch. The change set can include multiple insert, - * update, and delete operations. If a batch includes more than one change set, the first change set will be processed - * by the service, and additional change sets will be rejected with status code 400 (Bad Request).
    - *
    - * Important: Multiple operations against a single entity are not permitted within a change set.
    - *
    - *
  • - *
  • Note that a query operation is not permitted within a batch that contains insert, update, or delete operations; - * it must be submitted singly in the batch.
  • - *
  • Operations within a change set are processed atomically; that is, all operations in the change set either succeed - * or fail. Operations are processed in the order they are specified in the change set.
  • - *
  • The Table service does not support linking operations in a change set.
  • - *
  • The Table service supports a maximum of 100 operations in a change set.
  • - *
- *

- * An individual request within the change set is identical to a request made when that operation is being called by - * itself. - *

- * To specify an update, merge, or delete operation only succeeds when the entity has not changed since it was last seen - * by the client, include the entities' ETag value in the {@link Entity} instance passed to the operation in the change - * set. - */ -public class BatchOperations { - private List operations = new ArrayList(); - - /** - * Gets the collection of table operations in the batch. - * - * @return - * A {@link java.util.List} of {@link Operation} instances representing the table operations in the batch. - */ - public List getOperations() { - return operations; - } - - /** - * Sets the collection of table operations in the batch. - * - * @param operations - * A {@link java.util.List} of {@link Operation} instances representing the table operations in the - * batch. - */ - public void setOperations(List operations) { - this.operations = operations; - } - - /** - * Adds an insert entity operation to the collection of table operations in the batch. - *

- * The table parameter must refer to the same table as all other operations in the batch, and the - * entity parameter must have the same partition key as all other entities in the batch. - * - * @param table - * A {@link String} containing the name of the table to insert the entity into. - * @param entity - * The {@link Entity} instance to insert into the table. - * @return - * A reference to this {@link BatchOperations} instance. - */ - public BatchOperations addInsertEntity(String table, Entity entity) { - this.operations.add(new InsertEntityOperation().setTable(table).setEntity(entity)); - return this; - } - - /** - * Adds an update entity operation to the collection of table operations in the batch. An update operation replaces - * an existing entity with with the same primary key as the entity parameter. - *

- * The table parameter must refer to the same table as all other operations in the batch, and the - * entity parameter must have the same partition key as all other entities in the batch. - * - * @param table - * A {@link String} containing the name of the table to update the entity in. - * @param entity - * The {@link Entity} instance to update in the table. - * @return - * A reference to this {@link BatchOperations} instance. - */ - public BatchOperations addUpdateEntity(String table, Entity entity) { - this.operations.add(new UpdateEntityOperation().setTable(table).setEntity(entity)); - return this; - } - - /** - * Adds a merge entity operation to the collection of table operations in the batch. A merge operation replaces - * and inserts properties in an existing entity with with the same primary key as the entity parameter. - *

- * The table parameter must refer to the same table as all other operations in the batch, and the - * entity parameter must have the same partition key as all other entities in the batch. - * - * @param table - * A {@link String} containing the name of the table to merge the entity in. - * @param entity - * The {@link Entity} instance to merge in the table. - * @return - * A reference to this {@link BatchOperations} instance. - */ - public BatchOperations addMergeEntity(String table, Entity entity) { - this.operations.add(new MergeEntityOperation().setTable(table).setEntity(entity)); - return this; - } - - /** - * Adds an insert or replace entity operation to the collection of table operations in the batch. An insert or - * replace operation replaces an existing entity with with the same primary key as the entity parameter, or - * inserts the entity if no matching entity exists in the table. - *

- * The table parameter must refer to the same table as all other operations in the batch, and the - * entity parameter must have the same partition key as all other entities in the batch. - * - * @param table - * A {@link String} containing the name of the table to insert or replace the entity in. - * @param entity - * The {@link Entity} instance to insert or replace in the table. - * @return - * A reference to this {@link BatchOperations} instance. - */ - public BatchOperations addInsertOrReplaceEntity(String table, Entity entity) { - this.operations.add(new InsertOrReplaceEntityOperation().setTable(table).setEntity(entity)); - return this; - } - - /** - * Adds an insert or merge entity operation to the collection of table operations in the batch. An insert or - * merge operation replaces and inserts properties in an existing entity with with the same primary key as the - * entity parameter, or inserts the entity if no matching entity exists in the table. - *

- * The table parameter must refer to the same table as all other operations in the batch, and the - * entity parameter must have the same partition key as all other entities in the batch. - * - * @param table - * A {@link String} containing the name of the table to insert or replace the entity in. - * @param entity - * The {@link Entity} instance to insert or replace in the table. - * @return - * A reference to this {@link BatchOperations} instance. - */ - public BatchOperations addInsertOrMergeEntity(String table, Entity entity) { - this.operations.add(new InsertOrMergeEntityOperation().setTable(table).setEntity(entity)); - return this; - } - - /** - * Adds a delete entity operation to the collection of table operations in the batch. The delete operation removes - * the entity with with the specified partition key, row key, and ETag from the table. - *

- * The table parameter must refer to the same table as all other operations in the batch, and the - * partitionKey parameter must be the same partition key in all other operations in the batch. - * - * @param table - * A {@link String} containing the name of the table to delete the entity in. - * @param partitionKey - * A {@link String} containing the partition key of the entity to delete. - * @param rowKey - * A {@link String} containing the row key of the entity to delete. - * @param etag - * A {@link String} containing the ETag value of the entity to delete. - * @return - * A reference to this {@link BatchOperations} instance. - */ - public BatchOperations addDeleteEntity(String table, String partitionKey, String rowKey, String etag) { - this.operations.add(new DeleteEntityOperation().setTable(table).setPartitionKey(partitionKey).setRowKey(rowKey) - .setEtag(etag)); - return this; - } - - /** - * The abstract base class for all batch operations. - */ - public static abstract class Operation { - } - - /** - * Represents the parameters needed for an insert entity batch operation. - */ - public static class InsertEntityOperation extends Operation { - private String table; - private Entity entity; - - /** - * Gets the table name parameter for the insert entity batch operation set in this {@link InsertEntityOperation} - * instance. - * - * @return - * A {@link String} containing the name of the table that contains the entity to insert. - */ - public String getTable() { - return table; - } - - /** - * Sets the table name parameter for the insert entity batch operation. Note that this value must be the same - * for - * all operations in the batch. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to insert. - * @return - * A reference to this {@link InsertEntityOperation} instance. - */ - public InsertEntityOperation setTable(String table) { - this.table = table; - return this; - } - - /** - * Gets the entity parameter for the insert entity batch operation set in this {@link InsertEntityOperation} - * instance. - * - * @return - * The {@link Entity} instance containing the entity data to be inserted. - */ - public Entity getEntity() { - return entity; - } - - /** - * Sets the entity parameter for the insert entity batch operation. Note that the partition key value - * in the entity must be the same for all operations in the batch. - * - * @param entity - * The {@link Entity} instance containing the entity data to be inserted. - * @return - * A reference to this {@link InsertEntityOperation} instance. - */ - public InsertEntityOperation setEntity(Entity entity) { - this.entity = entity; - return this; - } - } - - /** - * Represents the parameters needed for an update entity batch operation. - */ - public static class UpdateEntityOperation extends Operation { - private String table; - private Entity entity; - - /** - * Gets the table name parameter for the update entity batch operation set in this {@link UpdateEntityOperation} - * instance. - * - * @return - * A {@link String} containing the name of the table that contains the entity to update. - */ - public String getTable() { - return table; - } - - /** - * Sets the table name parameter for the update entity batch operation. Note that this value must be the same - * for - * all operations in the batch. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to update. - * @return - * A reference to this {@link UpdateEntityOperation} instance. - */ - public UpdateEntityOperation setTable(String table) { - this.table = table; - return this; - } - - /** - * Gets the entity parameter for the update entity batch operation set in this {@link UpdateEntityOperation} - * instance. - * - * @return - * The {@link Entity} instance containing the entity data to be updated. - */ - public Entity getEntity() { - return entity; - } - - /** - * Sets the entity parameter for the update entity batch operation. Note that the partition key value - * in the entity must be the same for all operations in the batch. - * - * @param entity - * The {@link Entity} instance containing the entity data to be updated. - * @return - * A reference to this {@link UpdateEntityOperation} instance. - */ - public UpdateEntityOperation setEntity(Entity entity) { - this.entity = entity; - return this; - } - } - - /** - * Represents the parameters needed for a merge entity batch operation. - */ - public static class MergeEntityOperation extends Operation { - private String table; - private Entity entity; - - /** - * Gets the table name parameter for the merge entity batch operation set in this {@link MergeEntityOperation} - * instance. - * - * @return - * A {@link String} containing the name of the table that contains the entity to merge. - */ - public String getTable() { - return table; - } - - /** - * Sets the table name parameter for the merge entity batch operation. Note that this value must be the same for - * all operations in the batch. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to merge. - * @return - * A reference to this {@link MergeEntityOperation} instance. - */ - public MergeEntityOperation setTable(String table) { - this.table = table; - return this; - } - - /** - * Gets the entity parameter for the merge entity batch operation set in this {@link MergeEntityOperation} - * instance. - * - * @return - * The {@link Entity} instance containing the entity data to be merged. - */ - public Entity getEntity() { - return entity; - } - - /** - * Sets the entity parameter for the merge entity batch operation. Note that the partition key value - * in the entity must be the same for all operations in the batch. - * - * @param entity - * The {@link Entity} instance containing the entity data to be merged. - * @return - * A reference to this {@link MergeEntityOperation} instance. - */ - public MergeEntityOperation setEntity(Entity entity) { - this.entity = entity; - return this; - } - } - - /** - * Represents the parameters needed for an insert or replace entity batch operation. - */ - public static class InsertOrReplaceEntityOperation extends Operation { - private String table; - private Entity entity; - - /** - * Gets the table name parameter for the insert or replace entity batch operation set in this - * {@link InsertOrReplaceEntityOperation} instance. - * - * @return - * A {@link String} containing the name of the table that contains the entity to insert or replace. - */ - public String getTable() { - return table; - } - - /** - * Sets the table name parameter for the insert or replace entity batch operation. Note that this value must be - * the same for all operations in the batch. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to insert or replace. - * @return - * A reference to this {@link InsertOrReplaceEntityOperation} instance. - */ - public InsertOrReplaceEntityOperation setTable(String table) { - this.table = table; - return this; - } - - /** - * Gets the entity parameter for the insert or replace entity batch operation set in this - * {@link InsertOrReplaceEntityOperation} instance. - * - * @return - * The {@link Entity} instance containing the entity data to be inserted or replaced. - */ - public Entity getEntity() { - return entity; - } - - /** - * Sets the entity parameter for the insert or replace entity batch operation. Note that the partition key value - * in the entity must be the same for all operations in the batch. - * - * @param entity - * The {@link Entity} instance containing the entity data to be inserted or replaced. - * @return - * A reference to this {@link InsertOrReplaceEntityOperation} instance. - */ - public InsertOrReplaceEntityOperation setEntity(Entity entity) { - this.entity = entity; - return this; - } - } - - /** - * Represents the parameters needed for an insert or merge entity batch operation. - */ - public static class InsertOrMergeEntityOperation extends Operation { - private String table; - private Entity entity; - - /** - * Gets the table name parameter for the insert or merge entity batch operation set in this - * {@link InsertOrMergeEntityOperation} instance. - * - * @return - * A {@link String} containing the name of the table that contains the entity to insert or merge. - */ - public String getTable() { - return table; - } - - /** - * Sets the table name parameter for the insert or merge entity batch operation. Note that this value must be - * the same for all operations in the batch. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to insert or merge. - * @return - * A reference to this {@link InsertOrMergeEntityOperation} instance. - */ - public InsertOrMergeEntityOperation setTable(String table) { - this.table = table; - return this; - } - - /** - * Gets the entity parameter for the insert or merge entity batch operation set in this - * {@link InsertOrMergeEntityOperation} instance. - * - * @return - * The {@link Entity} instance containing the entity data to be inserted or merged. - */ - public Entity getEntity() { - return entity; - } - - /** - * Sets the entity parameter for the insert or merge entity batch operation. Note that the partition key value - * in the entity must be the same for all operations in the batch. - * - * @param entity - * The {@link Entity} instance containing the entity data to be inserted or merged. - * @return - * A reference to this {@link InsertOrMergeEntityOperation} instance. - */ - public InsertOrMergeEntityOperation setEntity(Entity entity) { - this.entity = entity; - return this; - } - } - - /** - * Represents the parameters needed for a delete entity operation. - */ - public static class DeleteEntityOperation extends Operation { - private String table; - private String partitionKey; - private String rowKey; - private String etag; - - /** - * Gets the table name parameter for the delete entity batch operation set in this {@link DeleteEntityOperation} - * instance. - * - * @return - * A {@link String} containing the name of the table that contains the entity to delete. - */ - public String getTable() { - return table; - } - - /** - * Sets the table name parameter for the delete entity batch operation. Note that this value must be the same - * for all operations in the batch. - * - * @param table - * A {@link String} containing the name of the table that contains the entity to delete. - * @return - * A reference to this {@link DeleteEntityOperation} instance. - */ - public DeleteEntityOperation setTable(String table) { - this.table = table; - return this; - } - - /** - * Gets the partition key parameter for the delete entity batch operation set in this - * {@link DeleteEntityOperation} instance. - * - * @return - * A {@link String} containing the partition key value of the entity to delete. - */ - public String getPartitionKey() { - return partitionKey; - } - - /** - * Sets the partition key parameter for the delete entity batch operation. Note that this value must be the same - * for all operations in the batch. - * - * @param partitionKey - * A {@link String} containing the partition key value of the entity to delete. - * @return - * A reference to this {@link DeleteEntityOperation} instance. - */ - public DeleteEntityOperation setPartitionKey(String partitionKey) { - this.partitionKey = partitionKey; - return this; - } - - /** - * Gets the row key parameter for the delete entity batch operation set in this {@link DeleteEntityOperation} - * instance. - * - * @return - * A {@link String} containing the row key value of the entity to delete. - */ - public String getRowKey() { - return rowKey; - } - - /** - * Sets the row key parameter for the delete entity batch operation. - * - * @param rowKey - * A {@link String} containing the row key value of the entity to delete. - * @return - * A reference to this {@link DeleteEntityOperation} instance. - */ - public DeleteEntityOperation setRowKey(String rowKey) { - this.rowKey = rowKey; - return this; - } - - /** - * Gets the ETag parameter for the delete entity batch operation set in this {@link DeleteEntityOperation} - * instance. - * - * @return - * A {@link String} containing the ETag value of the entity to delete. - */ - public String getEtag() { - return etag; - } - - /** - * Sets the ETag parameter for the delete entity batch operation. - * - * @param etag - * A {@link String} containing the ETag value of the entity to delete. - * @return - * A reference to this {@link DeleteEntityOperation} instance. - */ - public DeleteEntityOperation setEtag(String etag) { - this.etag = etag; - return this; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BatchResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BatchResult.java deleted file mode 100644 index 288ced7d29875..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BatchResult.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import java.util.ArrayList; -import java.util.List; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the response to a request for a batch transaction returned from a Table Service REST API Entity Group - * Transaction operation. This is returned by calls to implementations of {@link TableContract#batch(BatchOperations)} - * and {@link TableContract#batch(BatchOperations, TableServiceOptions)}. - *

- * See the Performing Entity Group - * Transactions documentation on MSDN for details of the underlying Table Service REST API operation. - */ -public class BatchResult { - private List entries = new ArrayList(); - - /** - * Gets the collection of {@link Entry} results from each MIME change set response corresponding to each request in - * the batch transaction. - * - * @return - * A {@link java.util.List} of {@link Entry} instances corresponding to the responses to each request in - * the batch transaction. - */ - public List getEntries() { - return entries; - } - - /** - * Reserved for internal use. Sets the collection of {@link Entry} results from each MIME change set response - * corresponding to each request in the batch transaction. - * - * @param entries - * The {@link java.util.List} of {@link Entry} instances corresponding to the responses to each request - * in the batch transaction. - * @return - * A reference to this {@link BatchResult} instance. - */ - public BatchResult setEntries(List entries) { - this.entries = entries; - return this; - } - - /** - * The abstract base class for entries in the batch transaction response. - */ - public static abstract class Entry { - } - - /** - * Represents the result of an insert entity operation within a batch transaction. - */ - public static class InsertEntity extends Entry { - private Entity entity; - - /** - * Gets the table entity inserted by the operation as returned in the server response. - * - * @return - * The {@link Entity} returned in the server response. - */ - public Entity getEntity() { - return entity; - } - - /** - * Reserved for internal use. Sets the table entity inserted by the operation from the matching - * entry element in the MIME change set response corresponding to the insert request in the - * batch transaction. - * - * @param entity - * The {@link Entity} returned in the server response. - * @return - * A reference to this {@link InsertEntity} instance. - */ - public InsertEntity setEntity(Entity entity) { - this.entity = entity; - return this; - } - } - - /** - * Represents the result of an update entity operation within a batch transaction. - */ - public static class UpdateEntity extends Entry { - private String etag; - - /** - * Gets the updated ETag value for the entity updated by the operation as returned in the server response. - * - * @return - * A {@link String} containing the updated ETag value for the entity. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag for the entity updated by the operation from the matching - * ETag header within the MIME change set response corresponding to the update request in the - * batch transaction. - * - * @param etag - * A {@link String} containing the updated ETag value for the entity. - * @return - * A reference to this {@link UpdateEntity} instance. - */ - public UpdateEntity setEtag(String etag) { - this.etag = etag; - return this; - } - } - - /** - * Represents the result of a delete entity operation within a batch transaction. - */ - public static class DeleteEntity extends Entry { - - } - - /** - * Represents an error result for an insert, update, or delete entity operation within a batch transaction. - */ - public static class Error extends Entry { - private ServiceException error; - - /** - * Gets the {@link ServiceException} instance corresponding to the error returned in the server response. - * - * @return - * A {@link ServiceException} instance corresponding to the error returned in the server response. - */ - public ServiceException getError() { - return error; - } - - /** - * Reserved for internal use. Sets the {@link ServiceException} instance created in response to an error result - * within the MIME change set response corresponding to the request in the batch transaction. - * - * @param error - * A {@link ServiceException} instance corresponding to the error returned in the server response. - * @return - * A reference to this {@link Error} instance. - */ - public Error setError(ServiceException error) { - this.error = error; - return this; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BinaryFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BinaryFilter.java deleted file mode 100644 index b5502542ffc1e..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/BinaryFilter.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * Represents a table query filter expression consisting of a filter, a binary comparison operator, and a filter. Use - * the static factory methods in the {@link Filter} class to create BinaryFilter instances, rather - * than constructing them directly. - */ -public class BinaryFilter extends Filter { - private final String operator; - private final Filter left; - private final Filter right; - - /** - * Creates a BinaryFilter expression from a {@link Filter}, a binary comparison operator, and a - * {@link Filter}. - *

- * Use the static factory methods in the {@link Filter} class to create BinaryFilter instances, rather - * than constructing them directly. - * - * @param left - * The {@link Filter} to use on the left hand side of the expression. - * @param operator - * A {@link String} containing the comparison operator to use in the expression. - * @param right - * The {@link Filter} to use on the right hand side of the expression. - */ - public BinaryFilter(Filter left, String operator, Filter right) { - this.left = left; - this.operator = operator; - this.right = right; - } - - /** - * Gets the comparison operator to use in the BinaryFilter expression. - * - * @return - * A {@link String} containing the comparison operator to use in the expression. - */ - public String getOperator() { - return operator; - } - - /** - * Gets the {@link Filter} to use on the left hand side of the BinaryFilter expression. - * - * @return - * A {@link Filter} to use on the left hand side of the expression. - */ - public Filter getLeft() { - return left; - } - - /** - * Gets the {@link Filter} to use on the right hand side of the BinaryFilter expression. - * - * @return - * A {@link Filter} to use on the right hand side of the expression. - */ - public Filter getRight() { - return right; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/ConstantFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/ConstantFilter.java deleted file mode 100644 index ee90440d312fb..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/ConstantFilter.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * Represents a constant value used as a filter parameter in a table query request. - *

- * Use the static factory method in the {@link Filter} class to create a {@link ConstantFilter}, rather than - * constructing one directly. - *

- * Use this class to pass a constant value as a filter parameter. The value is passed as an Object but must - * be (or have an implicit conversion to) one of the following for successful serialization: - *

    - *
  • null
  • - *
  • byte[]
  • - *
  • Byte[]
  • - *
  • Date
  • - *
  • Long
  • - *
  • String
  • - *
  • UUID
  • - *
- *

- * A {@link PropertyNameFilter} may be combined in a {@link BinaryFilter} with a comparison operator and a - * {@link ConstantFilter} to limit query results to properties with values that match the {@link ConstantFilter} value. - * The table service does not support wildcard queries, but you can perform prefix matching by using comparison - * operators on the desired prefix created as a {@link String} in a {@link ConstantFilter} instance. - *

- * See the Querying Tables and Entities - * topic in MSDN for more information on creating table query filter strings. - */ -public class ConstantFilter extends Filter { - private final Object value; - - /** - * Creates a table query filter constant from the value parameter. - *

- * Use the static factory method in the {@link Filter} class to create a {@link ConstantFilter}, rather than - * constructing one directly. - * - * @param value - * An {@link Object} containing the constant value to use as a filter parameter in a table query request. - */ - public ConstantFilter(Object value) { - this.value = value; - } - - /** - * Gets the constant filter value set in this {@link ConstantFilter} instance. - * - * @return - * The {@link Object} containing the constant value to use as a filter parameter in a table query request. - */ - public Object getValue() { - return value; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/DeleteEntityOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/DeleteEntityOptions.java deleted file mode 100644 index 846407dd9fb74..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/DeleteEntityOptions.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the options that may be set on a - * {@link TableContract#deleteEntity(String, String, String, DeleteEntityOptions)} request. An optional ETag value may - * be set to require that the deleted entity have the same ETag value to be deleted. Set a null ETag value - * to delete the entity unconditionally. - */ -public class DeleteEntityOptions extends TableServiceOptions { - private String etag; - - /** - * Gets the ETag value to match in order to delete the entity set in this {@link DeleteEntityOptions} instance. - * - * @return - * A {@link String} containing the ETag value the entity must match to be deleted. - */ - public String getEtag() { - return etag; - } - - /** - * Sets the ETag value to match in order to delete the entity. Set the etag parameter to null - * to delete the entity unconditionally. - * - * @param etag - * A {@link String} containing the ETag value the entity must match to be deleted, or null. - * @return - * A reference to this {@link DeleteEntityOptions} instance. - */ - public DeleteEntityOptions setEtag(String etag) { - this.etag = etag; - return this; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/EdmType.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/EdmType.java deleted file mode 100644 index 153d0bc035ddb..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/EdmType.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * A class containing string constants used to represent the primitive types of the Entity Data Model (EDM) in the Open - * Data Protocol (OData). The EDM is the underlying abstract data model used by OData services. The subset defined in - * this class is used for data type definitions of the properties of a table entity in the Windows Azure Storage - * service. - *

- * The following table shows the supported property data types in Windows Azure storage and the corresponding Java types - * when deserialized. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Storage TypeEdmType ValueJava TypeDescription
Edm.Binary{@link EdmType#BINARY}byte[], Byte[]An array of bytes up to 64 KB in size.
Edm.Boolean{@link EdmType#BOOLEAN}boolean, BooleanA Boolean value.
Edm.DateTime{@link EdmType#DATETIME}DateA 64-bit value expressed as Coordinated Universal Time (UTC). The supported range begins from 12:00 midnight, - * January 1, 1601 A.D. (C.E.), UTC. The range ends at December 31, 9999.
Edm.Double{@link EdmType#DOUBLE}double, DoubleA 64-bit double-precision floating point value.
Edm.Guid{@link EdmType#GUID}UUIDA 128-bit globally unique identifier.
Edm.Int32{@link EdmType#INT32}int, IntegerA 32-bit integer value.
Edm.Int64{@link EdmType#INT64}long, LongA 64-bit integer value.
Edm.String{@link EdmType#STRING}StringA UTF-16-encoded value. String values may be up to 64 KB in size.
- *

- * For more information about OData, see the Open Data Protocol website. - *

- * For an overview of the available EDM primitive data types and names, see the Primitive Data Types section of the - * OData Protocol Overview. - *

- * The Abstract Type System used to define the primitive types supported by OData is defined in detail in [MC-CSDL] (section 2.2.1). - */ -public class EdmType { - /** - * Edm.DateTime Represents date and time with values ranging from 12:00:00 midnight, January 1, - * 1753 A.D. through 11:59:59 P.M, December 9999 A.D. - */ - public static final String DATETIME = "Edm.DateTime"; - - /** - * Edm.Binary Represents fixed- or variable-length binary data. - */ - public static final String BINARY = "Edm.Binary"; - - /** - * Edm.Boolean Represents the mathematical concept of binary-valued logic. - */ - public static final String BOOLEAN = "Edm.Boolean"; - - /** - * Edm.Double Represents a floating point number with 15 digits precision that can represent values - * with approximate range of +/- 2.23e -308 through +/- 1.79e +308. - */ - public static final String DOUBLE = "Edm.Double"; - - /** - * Edm.Guid Represents a 16-byte (128-bit) unique identifier value. - */ - public static final String GUID = "Edm.Guid"; - - /** - * Edm.Int32 Represents a signed 32-bit integer value. - */ - public static final String INT32 = "Edm.Int32"; - - /** - * Edm.Int64 Represents a signed 64-bit integer value. - */ - public static final String INT64 = "Edm.Int64"; - - /** - * Edm.String Represents fixed- or variable-length character data. - */ - public static final String STRING = "Edm.String"; -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Entity.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Entity.java deleted file mode 100644 index 94fd36448c257..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Entity.java +++ /dev/null @@ -1,323 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * Represents an element of structured storage in a table. Tables store data as a collection of uniquely identifiable - * entities. Entities are similar to rows in a database. An entity has a primary key and a set of properties. A property - * is a name, typed-value pair, similar to a database column. - *

- * The Table service does not enforce any schema for tables, so two entities in the same table may have different sets - * of properties. Developers may choose to enforce a schema on the client side. A table may contain any number of - * entities. - *

- * An entity always has the following system properties: - *

- * These system properties are automatically included for every entity in a table. The names of these properties are - * reserved and cannot be changed. The developer is responsible for inserting and updating the values of - * PartitionKey and RowKey. The server manages the value of - * Timestamp, which cannot be modified. - *

- * An entity can have up to 255 properties, including the three system properties. Therefore, the user may include up to - * 252 custom properties, in addition to the three system properties. The combined size of all data in an entity's - * properties cannot exceed 1 MB. - *

- * The following table shows the supported property data types in Windows Azure storage and the corresponding Java types - * when deserialized. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Storage TypeEdmType ValueJava TypeDescription
Edm.Binary{@link EdmType#BINARY}byte[], Byte[]An array of bytes up to 64 KB in size.
Edm.Boolean{@link EdmType#BOOLEAN}boolean, BooleanA Boolean value.
Edm.DateTime{@link EdmType#DATETIME}DateA 64-bit value expressed as Coordinated Universal Time (UTC). The supported range begins from 12:00 midnight, - * January 1, 1601 A.D. (C.E.), UTC. The range ends at December 31, 9999.
Edm.Double{@link EdmType#DOUBLE}double, DoubleA 64-bit double-precision floating point value.
Edm.Guid{@link EdmType#GUID}UUIDA 128-bit globally unique identifier.
Edm.Int32{@link EdmType#INT32}int, IntegerA 32-bit integer value.
Edm.Int64{@link EdmType#INT64}long, LongA 64-bit integer value.
Edm.String{@link EdmType#STRING}StringA UTF-16-encoded value. String values may be up to 64 KB in size.
- *

- * See the MSDN topic Understanding the - * Table Service Data Model for an overview of tables, entities, and properties as used in the Windows Azure Storage - * service. - *

- * For an overview of the available EDM primitive data types and names, see the Primitive Data Types section of the - * OData Protocol Overview. - *

- */ -public class Entity { - private String etag; - private Map properties = new HashMap(); - - /** - * Gets the ETag value for the entity. This value is used to determine if the table entity has changed since it was - * last read from Windows Azure storage. When modifying an entity, the ETag value may be set to force the operation - * to fail if the ETag does not match the ETag on the server. - * - * @return - * A String containing the ETag for the entity. - */ - public String getEtag() { - return etag; - } - - /** - * Sets the ETag value for the entity. This value is used to determine if the table entity has changed since it was - * last read from Windows Azure storage. When modifying an entity, the ETag value may be set to force the operation - * to fail if the ETag does not match the ETag on the server. Set the etagparameter to null to - * force an unconditional operation. - * - * @param etag - * A String containing the ETag for the entity. - */ - public Entity setEtag(String etag) { - this.etag = etag; - return this; - } - - /** - * Gets the PartitionKey value for the entity. - * - * @return - * A String containing the PartitionKey value for the entity. - */ - public String getPartitionKey() { - Property p = getProperty("PartitionKey"); - return p == null ? null : (String) p.getValue(); - } - - /** - * Sets the PartitionKey value for the entity. - *

- * Tables are partitioned to support load balancing across storage nodes. A table's entities are organized by - * partition. A partition is a consecutive range of entities possessing the same partition key value. The partition - * key is a unique identifier for the partition within a given table, specified by the PartitionKey - * property. The partition key forms the first part of an entity's primary key. The partition key may be a string - * value up to 1 KB in size. - *

- * You must include the PartitionKey property in every insert, update, and delete operation. - * - * @param partitionKey - * A String containing the PartitionKey value for the entity. - * @return - * A reference to this {@link Entity} instance. - */ - public Entity setPartitionKey(String partitionKey) { - setProperty("PartitionKey", null, partitionKey); - return this; - } - - /** - * Gets the RowKey value for the entity. - * - * @return - * A String containing the RowKey value for the entity. - */ - public String getRowKey() { - Property p = getProperty("RowKey"); - return p == null ? null : (String) p.getValue(); - } - - /** - * Sets the RowKey value for the entity. - *

- * The second part of the primary key is the row key, specified by the RowKey property. The row key - * is a unique identifier for an entity within a given partition. Together the PartitionKey and - * RowKey uniquely identify every entity within a table. - *

- * The row key is a string value that may be up to 1 KB in size. - *

- * You must include the RowKey property in every insert, update, and delete operation. - * - * @param rowKey - * A String containing the RowKey value for the entity. - * @return - * A reference to this {@link Entity} instance. - */ - public Entity setRowKey(String rowKey) { - setProperty("RowKey", null, rowKey); - return this; - } - - /** - * Gets the Timestamp value for the entity. - * - * @return - * A {@link Date} containing the Timestamp value for the entity. - */ - public Date getTimestamp() { - Property p = getProperty("Timestamp"); - return p == null ? null : (Date) p.getValue(); - } - - /** - * Sets the Timestamp value for the entity. - *

- * The Timestamp property is a value that is maintained on the server side to record the time an - * entity was last modified. The Table service uses the Timestamp property internally to provide - * optimistic concurrency. You should treat this property as opaque: It should not be read, nor set on insert or - * update operations (the value will be ignored). - * - * @param timestamp - * A {@link Date} containing the Timestamp value for the entity. - * @return - * A reference to this {@link Entity} instance. - */ - public Entity setTimestamp(Date timestamp) { - setProperty("Timestamp", null, timestamp); - return this; - } - - /** - * Gets the properties collection of name and typed-data pairs in the entity. - * - * @return - * The {@link java.util.HashMap} collection of String property names to {@link Property} - * typed-data value pairs in the entity. - */ - public Map getProperties() { - return properties; - } - - /** - * Sets the properties collection of name and typed-data pairs in the entity. - * - * @param properties - * The {@link java.util.HashMap} collection of String property names to {@link Property} - * typed-data value pairs to set in the entity. - * @return - * A reference to this {@link Entity} instance. - */ - public Entity setProperties(Map properties) { - this.properties = properties; - return this; - } - - /** - * Gets the named property value from the properties collection in the entity. - * - * @param name - * A {@link String} containing the name of the entity property to return. - * @return - * The {@link Property} instance associated with the name parameter value in the entity, - * or null if the name is not in the properties collection. - */ - public Property getProperty(String name) { - return properties.get(name); - } - - /** - * Sets the property associated with the specified name in the properties collection in the entity. - * - * @param name - * The {@link String} containing the name to associate with the property value. - * @param property - * The {@link Property} instance to associate with the name parameter value in the entity - * @return - * A reference to this {@link Entity} instance. - */ - public Entity setProperty(String name, Property property) { - this.properties.put(name, property); - return this; - } - - /** - * Sets the property data type and value associated with the specified name in the properties collection in the - * entity. - * - * @param name - * The {@link String} containing the name to associate with the property value. - * @param edmType - * A {@link String} containing the EDM data type to associate with the property value. This must be one - * of the supported EDM types, defined as string constants in the {@link EdmType} class. - * @param value - * An {@link Object} containing the data value of the property, serializable as the associated EDM data - * type of the property. - * @return - * A reference to this {@link Entity} instance. - */ - public Entity setProperty(String name, String edmType, Object value) { - setProperty(name, new Property().setEdmType(edmType).setValue(value)); - return this; - } - - /** - * Gets the named property value from the properties collection in the entity cast an an {@link Object}. - * - * @param name - * A {@link String} containing the name of the entity property to return. - * @return - * The value associated with the name parameter in the properties collection in the entity, - * cast as an {@link Object}, or null if the name is not in the properties collection. - */ - public Object getPropertyValue(String name) { - Property p = getProperty(name); - return p == null ? null : p.getValue(); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Filter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Filter.java deleted file mode 100644 index b8aecc0f87099..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Filter.java +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents a table query filter expression, which can be used as an option in a - * {@link TableContract#queryEntities(String, QueryEntitiesOptions)} request. - *

- * A filter expression is built of operands consisting of property names, constant values, pre-computed query strings, - * or other filter expressions. Filter expressions may be combined with unary and binary operators to create complex - * expressions. - *

- * See the Querying Tables and Entities - * topic in MSDN for more information on creating table query filters. - */ -public class Filter { - /** - * A static factory method that creates a boolean filter expression that is the logical 'not' of the - * operand parameter. - * - * @param operand - * A {@link Filter} instance containing a boolean filter expression. - * @return - * A {@link UnaryFilter} instance containing a filter expression that is the logical 'not' of the - * operand parameter. - */ - public static UnaryFilter not(Filter operand) { - return new UnaryFilter("not", operand); - } - - /** - * A static factory method that creates a boolean filter expression that is the logical 'and' of the left - * and right parameters. - * - * @param left - * A {@link Filter} instance containing a boolean filter expression. - * @param right - * A {@link Filter} instance containing a boolean filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression that is the logical 'and' of the - * left and right parameters. - */ - public static BinaryFilter and(Filter left, Filter right) { - return new BinaryFilter(left, "and", right); - } - - /** - * A static factory method that creates a boolean filter expression that is the logical 'or' of the left - * and right parameters. - * - * @param left - * A {@link Filter} instance containing a boolean filter expression. - * @param right - * A {@link Filter} instance containing a boolean filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression that is the logical 'or' of the - * left and right parameters. - */ - public static BinaryFilter or(Filter left, Filter right) { - return new BinaryFilter(left, "or", right); - } - - /** - * A static factory method that creates a boolean filter expression that expresses whether the left and - * right parameters are equal. - *

- * Use this method to create a filter that compares the content of a property with a constant value. - *

- * The value must be of the same type as the property for the comparison operation to return valid results. Note - * that it is not possible to compare a property to a dynamic value; one side of the expression must be a constant. - * - * @param left - * A {@link Filter} instance containing a filter expression. - * @param right - * A {@link Filter} instance containing a filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression expresses whether the left and - * right parameters are equal. - */ - public static BinaryFilter eq(Filter left, Filter right) { - return new BinaryFilter(left, "eq", right); - } - - /** - * A static factory method that creates a boolean filter expression that expresses whether the left and - * right parameters are not equal. - *

- * Use this method to create a filter that compares the content of a property with a constant value. - *

- * The value must be of the same type as the property for the comparison operation to return valid results. Note - * that it is not possible to compare a property to a dynamic value; one side of the expression must be a constant. - * - * @param left - * A {@link Filter} instance containing a filter expression. - * @param right - * A {@link Filter} instance containing a filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression expresses whether the left and - * right parameters are not equal. - */ - public static BinaryFilter ne(Filter left, Filter right) { - return new BinaryFilter(left, "ne", right); - } - - /** - * A static factory method that creates a boolean filter expression that expresses whether the value of the - * left parameter is greater than or equal to the value of the right parameter. - *

- * Use this method to create a filter that compares the content of a property with a constant value. - *

- * The value must be of the same type as the property for the comparison operation to return valid results. Note - * that it is not possible to compare a property to a dynamic value; one side of the expression must be a constant. - * - * @param left - * A {@link Filter} instance containing a filter expression. - * @param right - * A {@link Filter} instance containing a filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression expresses whether the value of the - * left parameter is greater than or equal to the value of the right parameter. - */ - public static BinaryFilter ge(Filter left, Filter right) { - return new BinaryFilter(left, "ge", right); - } - - /** - * A static factory method that creates a boolean filter expression that expresses whether the value of the - * left parameter is greater than the value of the right parameter. - *

- * Use this method to create a filter that compares the content of a property with a constant value. - *

- * The value must be of the same type as the property for the comparison operation to return valid results. Note - * that it is not possible to compare a property to a dynamic value; one side of the expression must be a constant. - * - * @param left - * A {@link Filter} instance containing a filter expression. - * @param right - * A {@link Filter} instance containing a filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression expresses whether the value of the - * left parameter is greater than the value of the right parameter. - */ - public static BinaryFilter gt(Filter left, Filter right) { - return new BinaryFilter(left, "gt", right); - } - - /** - * A static factory method that creates a boolean filter expression that expresses whether the value of the - * left parameter is less than the value of the right parameter. - *

- * Use this method to create a filter that compares the content of a property with a constant value. - *

- * The value must be of the same type as the property for the comparison operation to return valid results. Note - * that it is not possible to compare a property to a dynamic value; one side of the expression must be a constant. - * - * @param left - * A {@link Filter} instance containing a filter expression. - * @param right - * A {@link Filter} instance containing a filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression expresses whether the value of the - * left parameter is less than the value of the right parameter. - */ - public static BinaryFilter lt(Filter left, Filter right) { - return new BinaryFilter(left, "lt", right); - } - - /** - * A static factory method that creates a boolean filter expression that expresses whether the value of the - * left parameter is less than or equal to the value of the right parameter. - *

- * Use this method to create a filter that compares the content of a property with a constant value. - *

- * The value must be of the same type as the property for the comparison operation to return valid results. Note - * that it is not possible to compare a property to a dynamic value; one side of the expression must be a constant. - * - * @param left - * A {@link Filter} instance containing a filter expression. - * @param right - * A {@link Filter} instance containing a filter expression. - * @return - * A {@link BinaryFilter} instance containing a filter expression expresses whether the value of the - * left parameter is less than or equal to the value of the right parameter. - */ - public static BinaryFilter le(Filter left, Filter right) { - return new BinaryFilter(left, "le", right); - } - - /** - * A static factory method that creates a constant value to use as an operand in a {@link BinaryFilter} expression. - * Case is significant in comparison expressions with constants of type {@link String}. - * - * @param value - * An Object reference to a constant value of a supported type, or null. - * @return - * A {@link ConstantFilter} instance containing the constant value for use in a filter expression. - */ - public static ConstantFilter constant(Object value) { - return new ConstantFilter(value); - } - - /** - * A static factory method that creates a property name value to use as an operand in a {@link BinaryFilter} - * expression. When the filter is evaluated, the content of the named property in the entity is used as the operand. - *

- * Note that case is significant for the PartitionKey and RowKey property names. - * - * @param value - * A {@link String} containing the name of a property. - * @return - * A {@link ConstantFilter} instance containing the constant value for use in a filter expression. - */ - public static PropertyNameFilter propertyName(String value) { - return new PropertyNameFilter(value); - } - - /** - * A static factory method that creates a table query filter string from the contents of the value - * parameter. - * - * @param value - * A {@link String} containing a table query filter string. - * - * @return - * A {@link QueryStringFilter} instance containing the table query filter string. - */ - public static QueryStringFilter queryString(String value) { - return new QueryStringFilter(value); - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetEntityResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetEntityResult.java deleted file mode 100644 index c2326aa379050..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetEntityResult.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the response to a request for a single table entity in the storage account returned - * from a Table Service REST API Query Entities operation. This is returned by calls to implementations of - * {@link TableContract#getEntity(String, String, String)} and - * {@link TableContract#getEntity(String, String, String, TableServiceOptions)}. - *

- * See the Query Entities documentation - * on MSDN for details of the underlying Table Service REST API operation. - */ -public class GetEntityResult { - private Entity entity; - - /** - * Gets the entity returned in the server response to the request. - * - * @return - * The {@link Entity} instance representing the entity returned in the server response to the request. - */ - public Entity getEntity() { - return entity; - } - - /** - * Reserved for internal use. Sets the entity value from the properties of the entry entity - * returned in the body of the server response. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param entity - * An {@link Entity} instance representing the entity returned in the server response to the request. - */ - public void setEntity(Entity entity) { - this.entity = entity; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetServicePropertiesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetServicePropertiesResult.java deleted file mode 100644 index 2f374d787d1ed..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetServicePropertiesResult.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * A wrapper class for the service properties returned in response to Table Service REST API operations. This is - * returned by calls to implementations of {@link TableContract#getServiceProperties()} and - * {@link TableContract#getServiceProperties(TableServiceOptions)}. - *

- * See the Get Table Service Properties - * documentation on MSDN for details of the underlying Table Service REST API operation. - */ -public class GetServicePropertiesResult { - private ServiceProperties value; - - /** - * Gets a {@link ServiceProperties} instance containing the service property values associated with the storage - * account. - *

- * Modifying the values in the {@link ServiceProperties} instance returned does not affect the values associated - * with the storage account. To change the values in the storage account, call the - * {@link TableContract#setServiceProperties(ServiceProperties)} or - * {@link TableContract#setServiceProperties(ServiceProperties, TableServiceOptions)} method and pass the modified - * {@link ServiceProperties} instance as a parameter. - * - * @return - * A {@link ServiceProperties} instance containing the property values associated with the storage account. - */ - public ServiceProperties getValue() { - return value; - } - - /** - * Reserved for internal use. Sets the value of the {@link ServiceProperties} instance associated with a - * storage service call result. This method is invoked by the API to store service properties returned by - * a call to a REST operation and is not intended for public use. - * - * @param value - * A {@link ServiceProperties} instance containing the property values associated with the storage - * account. - */ - public void setValue(ServiceProperties value) { - this.value = value; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetTableResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetTableResult.java deleted file mode 100644 index 59e7eaee303d0..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/GetTableResult.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the response to a request for a single table entry in the list of tables in the storage account returned - * from a Table Service REST API Query Tables operation. This is returned by calls to implementations of - * {@link TableContract#getTable(String)} and {@link TableContract#getTable(String, TableServiceOptions)}. - *

- * See the Query Tables documentation - * on MSDN for details of the underlying Table Service REST API operation. - */ -public class GetTableResult { - private TableEntry tableEntry; - - /** - * Gets the table entry returned in the server response. - * - * @return - * A {@link TableEntry} instance representing the table entry returned in the server response. - */ - public TableEntry getTableEntry() { - return tableEntry; - } - - /** - * Reserved for internal use. Sets the table entry value from the TableName entity in the - * properties of the entry entity returned in the body of the server response. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param tableEntry - * A {@link TableEntry} instance representing the table entry returned in the server response. - */ - public void setTableEntry(TableEntry tableEntry) { - this.tableEntry = tableEntry; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/InsertEntityResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/InsertEntityResult.java deleted file mode 100644 index e6fcf6b0202e7..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/InsertEntityResult.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the response to a request to insert a single table entity in the storage account returned - * from a Table Service REST API Insert Entity operation. This is returned by calls to implementations of - * {@link TableContract#insertEntity(String, Entity)} and - * {@link TableContract#insertEntity(String, Entity, TableServiceOptions)}. - *

- * See the Insert Entity documentation - * on MSDN for details of the underlying Table Service REST API operation. - */ -public class InsertEntityResult { - private Entity entity; - - /** - * Gets the entity returned in the server response to the request. - * - * @return - * The {@link Entity} instance representing the entity returned in the server response to the request. - */ - public Entity getEntity() { - return entity; - } - - /** - * Reserved for internal use. Sets the entity value from the properties of the entry entity - * returned in the body of the server response. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param entity - * An {@link Entity} instance representing the entity returned in the server response to the request. - */ - public void setEntity(Entity entity) { - this.entity = entity; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Property.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Property.java deleted file mode 100644 index 1f54bf907681d..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/Property.java +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * Represents a table entity property value as a data-type and value pair. - *

- * The following table shows the supported property data types in Windows Azure storage and the corresponding Java types - * when deserialized. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Storage TypeEdmType ValueJava TypeDescription
Edm.Binary{@link EdmType#BINARY}byte[], Byte[]An array of bytes up to 64 KB in size.
Edm.Boolean{@link EdmType#BOOLEAN}boolean, BooleanA Boolean value.
Edm.DateTime{@link EdmType#DATETIME}DateA 64-bit value expressed as Coordinated Universal Time (UTC). The supported range begins from 12:00 midnight, - * January 1, 1601 A.D. (C.E.), UTC. The range ends at December 31, 9999.
Edm.Double{@link EdmType#DOUBLE}double, DoubleA 64-bit double-precision floating point value.
Edm.Guid{@link EdmType#GUID}UUIDA 128-bit globally unique identifier.
Edm.Int32{@link EdmType#INT32}int, IntegerA 32-bit integer value.
Edm.Int64{@link EdmType#INT64}long, LongA 64-bit integer value.
Edm.String{@link EdmType#STRING}StringA UTF-16-encoded value. String values may be up to 64 KB in size.
- *

- * See the MSDN topic Understanding the - * Table Service Data Model for an overview of tables, entities, and properties as used in the Windows Azure Storage - * service. - *

- * For an overview of the available EDM primitive data types and names, see the Primitive Data Types section of the - * OData Protocol Overview. - */ -public class Property { - private String edmType; - private Object value; - - /** - * Gets the EDM data type of the property. - * - * @return - * A String containing the EDM data type of the property. - */ - public String getEdmType() { - return edmType; - } - - /** - * Sets the EDM data type of the property. The edmType parameter must be set to one of the string constants - * defined in the {@link EdmType} class. - * - * @param edmType - * A {@link String} containing the EDM data type to associate with the property value. This must be one - * of the supported EDM types, defined as string constants in the {@link EdmType} class. - * @return - * A reference to this {@link Property} instance. - */ - public Property setEdmType(String edmType) { - this.edmType = edmType; - return this; - } - - /** - * Gets the data value of the property. - * - * @return - * An {@link Object} containing the data value of the property. - */ - public Object getValue() { - return value; - } - - /** - * Sets the data value of the property. The value parameter must contain an {@link Object} serializable as - * the associated EDM data type of the property. - * - * @param value - * An {@link Object} containing the data value of the property, serializable as the associated EDM data - * type of the property. - * @return - * A reference to this {@link Property} instance. - */ - public Property setValue(Object value) { - this.value = value; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/PropertyNameFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/PropertyNameFilter.java deleted file mode 100644 index c31b1552a2bbb..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/PropertyNameFilter.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * Represents a property name used as a filter parameter in a table query request. - *

- * Use the static factory method in the {@link Filter} class to create a {@link PropertyNameFilter}, rather than - * constructing one directly. - *

- * Use this class to pass a property name as a filter parameter. When the filter is evaluated, the content of the named - * property in the entity is used in the filter expression. - *

- * Note that case is significant for the PartitionKey and RowKey property names in a - * filter. - *

- * A {@link PropertyNameFilter} may be combined in a {@link BinaryFilter} with a comparison operator and a - * {@link ConstantFilter} to limit query results to properties with values that match the {@link ConstantFilter} value. - * The table service does not support wildcard queries, but you can perform prefix matching by using comparison - * operators on the desired prefix created as a {@link String} in a {@link ConstantFilter} instance. - *

- * See the Querying Tables and Entities - * topic in MSDN for more information on creating table query filter strings. - */ -public class PropertyNameFilter extends Filter { - private final String propertyName; - - /** - * Creates a property name table query filter from the propertyName parameter. - *

- * Use the static factory method in the {@link Filter} class to create a {@link PropertyNameFilter}, rather than - * constructing one directly. - * - * @param propertyName - * A {@link String} containing the property name to use as a filter parameter in a table query request. - */ - public PropertyNameFilter(String propertyName) { - this.propertyName = propertyName; - } - - /** - * Gets the property name set in this {@link PropertyNameFilter} instance. - * - * @return - * The {@link String} containing the property name to use as a filter parameter in a table query request. - */ - public String getPropertyName() { - return propertyName; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryEntitiesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryEntitiesOptions.java deleted file mode 100644 index 71d6442a1a531..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryEntitiesOptions.java +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import java.util.ArrayList; -import java.util.List; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the options that may be set on a {@link TableContract#queryEntities(String, QueryEntitiesOptions) - * queryEntities} request. These options include the next partition key and next row key continuation tokens to use to - * resume the query entities request from, a collection of the property names to include in the entities returned in the - * server response, a filter to limit results to entities with certain property values, and a top count to limit the - * response to that number of the first matching results. - */ -public class QueryEntitiesOptions extends TableServiceOptions { - - private List selectFields = new ArrayList(); - private String from; - private Filter filter; - private List orderByFields = new ArrayList(); - private Integer top; - - public String nextPartitionKey; - public String nextRowKey; - - /** - * Gets the next partition key continuation token set in this {@link QueryEntitiesOptions} instance. - * - * @return - * A {@link String} containing the next partition key continuation token to use to resume a query entities - * request with. - */ - public String getNextPartitionKey() { - return nextPartitionKey; - } - - /** - * Sets the next partition key continuation token to resume a query entities request with. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * Use the {@link QueryEntitiesResult#getNextPartitionKey()} and {@link QueryEntitiesResult#getNextRowKey()} methods - * on the result of a query entities request to determine if there are more results to retrieve. If so, set the - * values returned on a {@link QueryEntitiesOptions} instance with the {@link #setNextPartitionKey(String)} and - * {@link #setNextRowKey(String)} methods, and resume the query with another call to - * {@link TableContract#queryEntities(String, QueryEntitiesOptions)} to get the next set of results. - *

- * It is possible for a query to return no results but to still return a continuation token. - *

- * This value only affects calls made on methods where this {@link QueryEntitiesOptions} instance is passed as a - * parameter. - * - * @param nextPartitionKey - * A {@link String} containing the next partition key continuation token to use to resume a query - * entities request with. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions setNextPartitionKey(String nextPartitionKey) { - this.nextPartitionKey = nextPartitionKey; - return this; - } - - /** - * Gets the next row key continuation token set in this {@link QueryEntitiesOptions} instance. - * - * @return - * A {@link String} containing the next row key continuation token to use to resume a query entities request - * with. - */ - public String getNextRowKey() { - return nextRowKey; - } - - /** - * Sets the next row key continuation token to resume a query entities request with. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * Use the {@link QueryEntitiesResult#getNextPartitionKey()} and {@link QueryEntitiesResult#getNextRowKey()} methods - * on the result of a query entities request to determine if there are more results to retrieve. If so, set the - * values returned on a {@link QueryEntitiesOptions} instance with the {@link #setNextPartitionKey(String)} and - * {@link #setNextRowKey(String)} methods, and resume the query with another call to - * {@link TableContract#queryEntities(String, QueryEntitiesOptions)} to get the next set of results. - *

- * It is possible for a query to return no results but to still return a continuation token. - *

- * This value only affects calls made on methods where this {@link QueryEntitiesOptions} instance is passed as a - * parameter. - * - * @param nextRowKey - * A {@link String} containing the next row key continuation token to use to resume a query - * entities request with. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions setNextRowKey(String nextRowKey) { - this.nextRowKey = nextRowKey; - return this; - } - - /** - * Gets the collection of properties to include in the entities returned in the server response set in this - * {@link QueryEntitiesOptions} instance. - * - * @return - * The {@link java.util.List} of {@link String} property names to include in the entities returned in the - * server response. - */ - public List getSelectFields() { - return selectFields; - } - - /** - * Sets the collection of properties to include in the entities returned in the server response. - * - * @param selectFields - * A {@link java.util.List} of {@link String} property names to include in the entities returned in the - * server response. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions setSelectFields(List selectFields) { - this.selectFields = selectFields; - return this; - } - - /** - * Adds a property name to the collection of properties to include in the entities returned in the server response. - * - * @param selectField - * A {@link String} property name to include in the entities returned in the server response. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions addSelectField(String selectField) { - this.selectFields.add(selectField); - return this; - } - - /** - * Reserved for future use. Gets the from option value set in this {@link QueryEntitiesOptions} instance. - * - * @return - * A {@link String} containing the from option value set. - */ - public String getFrom() { - return from; - } - - /** - * Reserved for future use. Sets the from option value. - * - * @param from - * A {@link String} containing the from option value to set. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions setFrom(String from) { - this.from = from; - return this; - } - - /** - * Gets the table query filter set in this {@link QueryEntitiesOptions} instance. - * - * @return - * A {@link Filter} containing the table query filter to apply on the server to limit the entities returned - * in the response. - */ - public Filter getFilter() { - return filter; - } - - /** - * Sets the table query filter to apply on the server to limit the entities returned in the response. - * - * @param filter - * A {@link Filter} containing the table query filter to apply on the server to limit the entities - * returned in the response. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions setFilter(Filter filter) { - this.filter = filter; - return this; - } - - /** - * Reserved for future use. Gets the list of property names to use to order the results in the server response set - * in this {@link QueryEntitiesOptions} instance. - * - * @return - * The {@link java.util.List} of {@link String} property names to use to order the results in the server - * response. - */ - public List getOrderByFields() { - return orderByFields; - } - - /** - * Reserved for future use. Sets the list of property names to use to order the results in the server response. - * - * @param orderByFields - * A {@link java.util.List} of {@link String} property names to use to order the results in the server - * response. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions setOrderByFields(List orderByFields) { - this.orderByFields = orderByFields; - return this; - } - - /** - * Reserved for future use. Adds a property name to the list of property names to use to order the results in the - * server response. - * - * @param orderByField - * A {@link String} containing a property name to add to the list to use to order the results in the - * server response. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions addOrderByField(String orderByField) { - this.orderByFields.add(orderByField); - return this; - } - - /** - * Gets the number of entities to return in the server response set in this {@link QueryEntitiesOptions} instance. - * - * @return - * The number of entities to return in the server response. - */ - public Integer getTop() { - return top; - } - - /** - * Sets the number of entities to return in the server response. The first results in order by partition key and row - * key will be returned. - * - * @param top - * The number of entities to return in the server response. - * @return - * A reference to this {@link QueryEntitiesOptions} instance. - */ - public QueryEntitiesOptions setTop(Integer top) { - this.top = top; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryEntitiesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryEntitiesResult.java deleted file mode 100644 index b58f2eeccdda6..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryEntitiesResult.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import java.util.ArrayList; -import java.util.List; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the response to a request for a list of entities in the storage account returned from a Table Service REST - * API Query Tables operation. This is returned by calls to implementations of - * {@link TableContract#queryEntities(String)} and {@link TableContract#queryEntities(String, QueryEntitiesOptions)}. - *

- * See the Query Entities documentation - * on MSDN for details of the underlying Table Service REST API operation. - */ -public class QueryEntitiesResult { - private String nextPartitionKey; - private String nextRowKey; - private List entities = new ArrayList(); - - /** - * Gets the list of entities returned in the server response to the query entities request. - * - * @return - * A {@link java.util.List} of {@link Entity} instances representing the entities returned in the server - * response. - */ - public List getEntities() { - return entities; - } - - /** - * Reserved for internal use. Sets the list of entities returned in the server response to the query entities - * request. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param entities - * A {@link java.util.List} of {@link Entity} instances representing the entities returned in the server - * response. - */ - public void setEntities(List entities) { - this.entities = entities; - } - - /** - * Gets the next partition key continuation token to resume the query entities request with, if any is returned. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * Use the {@link QueryEntitiesResult#getNextPartitionKey()} and {@link QueryEntitiesResult#getNextRowKey()} methods - * on the result of a query entities request to determine if there are more results to retrieve. If so, set the - * values returned on a {@link QueryEntitiesOptions} instance with the {@link #setNextPartitionKey(String)} and - * {@link #setNextRowKey(String)} methods, and resume the query with another call to - * {@link TableContract#queryEntities(String, QueryEntitiesOptions)} to get the next set of results. - *

- * It is possible for a query to return no results but to still return a continuation token. - * - * @return - * A {@link String} containing the next partition key continuation token to use to resume the query entities - * request with, or null if no token was returned. - */ - public String getNextPartitionKey() { - return nextPartitionKey; - } - - /** - * Reserved for internal use. Sets the next partition key continuation token to resume a query entities request with - * from the x-ms-continuation-NextPartitionKey header returned in the response from the server. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param nextPartitionKey - * A {@link String} containing the next partition key continuation token to use to resume a query - * entities request with. - */ - public void setNextPartitionKey(String nextPartitionKey) { - this.nextPartitionKey = nextPartitionKey; - } - - /** - * Gets the next row key continuation token to resume the query tables request with, if any is returned. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * Use the {@link QueryEntitiesResult#getNextPartitionKey()} and {@link QueryEntitiesResult#getNextRowKey()} methods - * on the result of a query entities request to determine if there are more results to retrieve. If so, set the - * values returned on a {@link QueryEntitiesOptions} instance with the {@link #setNextPartitionKey(String)} and - * {@link #setNextRowKey(String)} methods, and resume the query with another call to - * {@link TableContract#queryEntities(String, QueryEntitiesOptions)} to get the next set of results. - *

- * It is possible for a query to return no results but to still return a continuation token. - * - * @return - * A {@link String} containing the next row key continuation token to use to resume the query tables - * request with, or null if no token was returned. - */ - public String getNextRowKey() { - return nextRowKey; - } - - /** - * Reserved for internal use. Sets the next row key continuation token to resume a query entities request with from - * the x-ms-continuation-NextRowKey header returned in the response from the server. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param nextRowKey - * A {@link String} containing the next row key continuation token to use to resume a query entities - * request with. - */ - public void setNextRowKey(String nextRowKey) { - this.nextRowKey = nextRowKey; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryStringFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryStringFilter.java deleted file mode 100644 index 0238b57d083f1..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryStringFilter.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * Represents a table query filter string passed directly as a filter parameter in a table query request. - *

- * Use the static factory method in the {@link Filter} class to create a {@link QueryStringFilter}, rather than - * constructing one directly. - *

- * Use this class to pass a literal query filter string without interpretation as a filter parameter. For example, if - * you have a created a query filter expression independently, this class may be used to add it to a filter expression. - *

- * The following characters must be URL-encoded if they are to be used in a query string: - *

    - *
  • Forward slash (/)
  • - *
  • Question mark (?)
  • - *
  • Colon (:)
  • - *
  • 'At' symbol (@)
  • - *
  • Ampersand (&)
  • - *
  • Equals sign (=)
  • - *
  • Plus sign (+)
  • - *
  • Comma (,)
  • - *
  • Dollar sign ($)
  • - *
- *

- * See the Querying Tables and Entities - * topic in MSDN for more information on creating table query filter strings. - */ -public class QueryStringFilter extends Filter { - private final String queryString; - - /** - * Creates a table query filter from the queryString parameter. - *

- * Use the static factory method in the {@link Filter} class to create a {@link QueryStringFilter}, rather than - * constructing one directly. - * - * @param queryString - * A {@link String} containing a table query filter to pass directly as a filter parameter in a table - * query request. - */ - public QueryStringFilter(String queryString) { - this.queryString = queryString; - } - - /** - * Gets the table query filter string set in this {@link QueryStringFilter} instance. - * - * @return - * A {@link String} containing a table query filter to pass directly as a filter parameter in a table - * query request. - */ - public String getQueryString() { - return queryString; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryTablesOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryTablesOptions.java deleted file mode 100644 index e553a15bb8d33..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryTablesOptions.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the options that may be set on a {@link TableContract#queryTables(QueryTablesOptions) queryTables} - * request. These options include a filter to limit results to tables with certain properties, the next table name - * continuation token to use to resume the query tables request from, and a prefix string to match table names with. - */ -public class QueryTablesOptions extends TableServiceOptions { - private Filter filter; - private String nextTableName; - private String prefix; - - /** - * Gets the filter to use to limit table entries returned set in this {@link TableServiceOptions} instance. - * - * @return - * A {@link Filter} instance containing the filter options to use. - */ - public Filter getFilter() { - return filter; - } - - /** - * Sets the filter to use to limit table entries returned by the request to those that match the filter properties. - *

- * This value only affects calls made on methods where this {@link QueryTablesOptions} instance is passed as a - * parameter. - * - * @param filter - * A {@link Filter} instance containing the filter options to use. - * @return - * A reference to this {@link QueryTablesOptions} instance. - */ - public QueryTablesOptions setFilter(Filter filter) { - this.filter = filter; - return this; - } - - /** - * Gets the next table name continuation token set in this {@link TableServiceOptions} instance. - * - * @return - * A {@link String} containing the next table name continuation token to use to resume a query tables - * request with. - */ - public String getNextTableName() { - return nextTableName; - } - - /** - * Sets the next table name continuation token to resume a query tables request with. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * Use the {@link QueryTablesResult#getNextTableName()} method on the result of a query tables request to determine - * if there are more results to retrieve. If so, pass the value returned as the nextTableName parameter to - * this method to set the next table name continuation token option, and resume the query with another call to - * {@link TableContract#queryTables(QueryTablesOptions)} to get the next set of results. - *

- * It is possible for a query to return no results but to still return a continuation token. - *

- * This value only affects calls made on methods where this {@link QueryTablesOptions} instance is passed as a - * parameter. - * - * @param nextTableName - * A {@link String} containing the next table name continuation token to use to resume a query tables - * request with. - * @return - * A reference to this {@link QueryTablesOptions} instance. - */ - public QueryTablesOptions setNextTableName(String nextTableName) { - this.nextTableName = nextTableName; - return this; - } - - /** - * Gets the prefix filter associated with this {@link QueryTablesOptions} instance. This value is used to return - * only tables from the storage account with names that begin with the prefix in the response to a query tables - * request. - * - * @return - * A {@link String} containing the prefix used to filter the table names returned, if any. - */ - public String getPrefix() { - return prefix; - } - - /** - * Sets the optional table name prefix filter value to use in a request. If this value is set, the server will - * return only table entries with names that match the prefix value in the response. - *

- * The prefix value only affects calls made on methods where this {@link QueryTablesOptions} instance is - * passed as a parameter. - * - * @param prefix - * A {@link String} containing a prefix to use to filter the table names returned. - */ - public QueryTablesOptions setPrefix(String prefix) { - this.prefix = prefix; - return this; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryTablesResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryTablesResult.java deleted file mode 100644 index 4937d830a3515..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/QueryTablesResult.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import java.util.List; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the response to a request for a list of tables in the storage account returned - * from a Table Service REST API Query Tables operation. This is returned by calls to implementations of - * {@link TableContract#queryTables()} and {@link TableContract#queryTables(QueryTablesOptions)}. - *

- * See the Query Tables documentation - * on MSDN for details of the underlying Table Service REST API operation. - */ -public class QueryTablesResult { - private String nextTableName; - private List tables; - - /** - * Gets the next table name continuation token to resume the query tables request with, if any is returned. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * Use the {@link QueryTablesResult#getNextTableName()} method on the result of a query tables request to determine - * if there are more results to retrieve. If so, pass the value returned as the nextTableName parameter to - * this method to set the next table name continuation token option, and resume the query with another call to - * {@link TableContract#queryTables(QueryTablesOptions)} to get the next set of results. - *

- * It is possible for a query to return no results but to still return a continuation token. - * - * @return - * A {@link String} containing the next table name continuation token to use to resume the query tables - * request with, or null if no token was returned. - */ - public String getNextTableName() { - return nextTableName; - } - - /** - * Reserved for internal use. Sets the next table name continuation token to resume a query tables request with from - * the x-ms-continuation-NextTableName header returned in the response from the server. - *

- * A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum - * of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five - * seconds, or if the query crosses the partition boundary, the response includes values which provide the client - * with continuation tokens to use in order to resume the query at the next item in the result set. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param nextTableName - * A {@link String} containing the next table name continuation token to use to resume a query tables - * request with. - */ - public void setNextTableName(String nextTableName) { - this.nextTableName = nextTableName; - } - - /** - * Gets the list of table entries returned in the server response. - * - * @return - * A {@link List} of {@link TableEntry} instances containing the table entries returned in the response. - */ - public List getTables() { - return tables; - } - - /** - * Reserved for internal use. Sets the list of table entries from each TableName entity in the - * properties of the entry entities returned in the body of the server response. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param tables - * A {@link List} of {@link TableEntry} instances containing the table entries returned in the response. - */ - public void setTables(List tables) { - this.tables = tables; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/ServiceProperties.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/ServiceProperties.java deleted file mode 100644 index bc09dbce91b1f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/ServiceProperties.java +++ /dev/null @@ -1,342 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the Storage service properties that can be set on a storage account, including Windows Azure Storage - * Analytics. This class is used by the {@link TableContract#getServiceProperties()} method to return the service - * property values set on the storage account, and by the {@link TableContract#setServiceProperties(ServiceProperties)} - * and {@link TableContract#setServiceProperties(ServiceProperties, TableServiceOptions)} methods to set the values of - * the service properties. - */ -@XmlRootElement(name = "StorageServiceProperties") -public class ServiceProperties { - private Logging logging = new Logging(); - private Metrics metrics = new Metrics(); - - /** - * Gets the value of the logging options on the storage account. - * - * @return - * A {@link Logging} instance containing the logging options. - */ - @XmlElement(name = "Logging") - public Logging getLogging() { - return logging; - } - - /** - * Sets the value of the logging options on the storage account. - * - * @param logging - * A {@link Logging} instance containing the logging options. - */ - public void setLogging(Logging logging) { - this.logging = logging; - } - - /** - * Gets the value of the metrics options on the storage account. - * - * @return - * A {@link Metrics} instance containing the metrics options. - */ - @XmlElement(name = "Metrics") - public Metrics getMetrics() { - return metrics; - } - - /** - * Sets the value of the metrics options on the storage account. - * - * @param metrics - * A {@link Metrics} instance containing the metrics options. - */ - public void setMetrics(Metrics metrics) { - this.metrics = metrics; - } - - /** - * Represents the logging options that can be set on a storage account. - */ - public static class Logging { - private String version; - private boolean delete; - private boolean read; - private boolean write; - private RetentionPolicy retentionPolicy; - - /** - * Gets the retention policy for logging data set on the storage account. - * - * @return - * The {@link RetentionPolicy} set on the storage account. - */ - @XmlElement(name = "RetentionPolicy") - public RetentionPolicy getRetentionPolicy() { - return retentionPolicy; - } - - /** - * Sets the retention policy to use for logging data on the storage account. - * - * @param retentionPolicy - * The {@link RetentionPolicy} to set on the storage account. - */ - public void setRetentionPolicy(RetentionPolicy retentionPolicy) { - this.retentionPolicy = retentionPolicy; - } - - /** - * Gets a flag indicating whether all write requests are logged. - * - * @return - * A flag value of true if all write operations are logged; otherwise, false. - */ - @XmlElement(name = "Write") - public boolean isWrite() { - return write; - } - - /** - * Sets a flag indicating whether all write requests should be logged. - * - * @param write - * Set a flag value of true to log all write operations; otherwise, false. - */ - public void setWrite(boolean write) { - this.write = write; - } - - /** - * Gets a flag indicating whether all read requests are logged. - * - * @return - * A flag value of true if all read operations are logged; otherwise, false. - */ - @XmlElement(name = "Read") - public boolean isRead() { - return read; - } - - /** - * Sets a flag indicating whether all read requests should be logged. - * - * @param read - * Set a flag value of true to log all read operations; otherwise, false. - */ - public void setRead(boolean read) { - this.read = read; - } - - /** - * Gets a flag indicating whether all delete requests are logged. - * - * @return - * A flag value of true if all delete operations are logged; otherwise, false. - */ - @XmlElement(name = "Delete") - public boolean isDelete() { - return delete; - } - - /** - * Sets a flag indicating whether all delete requests should be logged. - * - * @param delete - * Set a flag value of true to log all delete operations; otherwise, false. - */ - public void setDelete(boolean delete) { - this.delete = delete; - } - - /** - * Gets the version of logging configured on the storage account. - * - * @return - * A {@link String} containing the version of logging configured on the storage account. - */ - @XmlElement(name = "Version") - public String getVersion() { - return version; - } - - /** - * Sets the version of logging configured on the storage account. - * - * @param version - * A {@link String} containing the version of logging configured on the storage account. - */ - public void setVersion(String version) { - this.version = version; - } - } - - /** - * Represents the metrics options that can be set on a storage account. - */ - public static class Metrics { - private String version; - private boolean enabled; - private Boolean includeAPIs; - private RetentionPolicy retentionPolicy; - - /** - * Gets the retention policy for metrics data set on the storage account. - * - * @return - * The {@link RetentionPolicy} set on the storage account. - */ - @XmlElement(name = "RetentionPolicy") - public RetentionPolicy getRetentionPolicy() { - return retentionPolicy; - } - - /** - * Sets the retention policy to use for metrics data on the storage account. - * - * @param retentionPolicy - * The {@link RetentionPolicy} to set on the storage account. - */ - public void setRetentionPolicy(RetentionPolicy retentionPolicy) { - this.retentionPolicy = retentionPolicy; - } - - /** - * Gets a flag indicating whether metrics generates summary statistics for called API operations. - * - * @return - * A flag value of true if metrics generates summary statistics for called API operations; - * otherwise, false. - */ - @XmlElement(name = "IncludeAPIs") - public Boolean isIncludeAPIs() { - return includeAPIs; - } - - /** - * Sets a flag indicating whether metrics should generate summary statistics for called API operations. This - * flag is optional if metrics is not enabled. - * - * @param includeAPIs - * Set a flag value of true to generate summary statistics for called API operations; - * otherwise, false. - */ - public void setIncludeAPIs(Boolean includeAPIs) { - this.includeAPIs = includeAPIs; - } - - /** - * Gets a flag indicating whether metrics is enabled for the storage account. - * - * @return - * A flag value of true if metrics is enabled for the storage account; otherwise, - * false. - */ - @XmlElement(name = "Enabled") - public boolean isEnabled() { - return enabled; - } - - /** - * Sets a flag indicating whether to enable metrics for the storage account. - * - * @param enabled - * Set a flag value of true to enable metrics for the storage account; otherwise, - * false. - */ - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - /** - * Gets the version of Storage Analytics configured on the storage account. - * - * @return - * A {@link String} containing the version of Storage Analytics configured on the storage account. - */ - @XmlElement(name = "Version") - public String getVersion() { - return version; - } - - /** - * Sets the version of Storage Analytics configured on the storage account. - * - * @param version - * A {@link String} containing the version of Storage Analytics configured on the storage account. - */ - public void setVersion(String version) { - this.version = version; - } - } - - /** - * Represents the optional retention policy that can be applied to logging or metrics on the storage account. - */ - public static class RetentionPolicy { - private boolean enabled; - private Integer days; // nullable, because optional if "enabled" is false - - /** - * Gets the number of days that metrics or logging data should be retained, if logging is enabled. - * - * @return - * The number of days to retain logging or metrics data if logging is enabled, or null. - */ - @XmlElement(name = "Days") - public Integer getDays() { - return days; - } - - /** - * Sets the number of days that metrics or logging data should be retained. The minimum value you can specify is - * 1; the largest value is 365 (one year). This value must be specified even if the enabled flag is set - * to false. - * - * @param days - * The number of days to retain logging or metrics data. - */ - public void setDays(Integer days) { - this.days = days; - } - - /** - * Gets a flag indicating whether a retention policy is enabled. - * - * @return - * A flag value of true if a retention policy is enabled; otherwise, false. - */ - @XmlElement(name = "Enabled") - public boolean isEnabled() { - return enabled; - } - - /** - * Sets a flag indicating whether to enable a retention policy. - * - * @param enabled - * Set a flag value of true to enable a retention policy; otherwise, false. - */ - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/TableEntry.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/TableEntry.java deleted file mode 100644 index f166b04166284..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/TableEntry.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * Represents a single table entry in the list of tables in the storage account. - */ -public class TableEntry { - private String name; - - /** - * Gets the name of the table. - * - * @return - * A {@link String} containing the name of the table. - */ - public String getName() { - return name; - } - - /** - * Sets the name of the table. - * - * @param name - * A {@link String} containing the name of the table. - */ - public void setName(String name) { - this.name = name; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/TableServiceOptions.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/TableServiceOptions.java deleted file mode 100644 index 55d2d818dca1f..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/TableServiceOptions.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * This class is a base class for options that may be set on certain Table service requests. - */ -public class TableServiceOptions { -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/UnaryFilter.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/UnaryFilter.java deleted file mode 100644 index d01cedea3512c..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/UnaryFilter.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -/** - * Represents a table query filter expression consisting of a unary logical operator and a boolean filter expression. - * Use the static factory methods in the {@link Filter} class to create UnaryFilter instances, rather - * than constructing them directly. - */ -public class UnaryFilter extends Filter { - private final String operator; - private final Filter operand; - - /** - * Creates a UnaryFilter expression from a unary logical operator and a boolean {@link Filter}. - *

- * Use the static factory methods in the {@link Filter} class to create UnaryFilter instances, rather - * than constructing them directly. - * - * @param operator - * A {@link String} containing the unary logical operator to use in the expression. - * @param operand - * The boolean {@link Filter} to use as the operand of the expression. - */ - public UnaryFilter(String operator, Filter operand) { - this.operator = operator; - this.operand = operand; - } - - /** - * Gets the unary logical operator to use in the UnaryFilter expression. - * - * @return - * A {@link String} containing the unary logical operator to use in the expression. - */ - public String getOperator() { - return operator; - } - - /** - * Gets the boolean {@link Filter} to use as the operand of the UnaryFilter expression. - * - * @return - * A {@link Filter} to use as the operand of the expression. - */ - public Filter getOperand() { - return operand; - } - -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/UpdateEntityResult.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/UpdateEntityResult.java deleted file mode 100644 index d8496a35f70b2..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/UpdateEntityResult.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.models; - -import com.microsoft.windowsazure.services.table.TableContract; - -/** - * Represents the response to a request to modify a single table entity in the storage account returned - * from a Table Service REST API Update Entity, Merge Entity, Insert or Replace Entity, or Insert or Merge Entity - * operation. This is returned by calls to implementations of {@link TableContract#mergeEntity(String, Entity)}, - * {@link TableContract#mergeEntity(String, Entity, TableServiceOptions)}, - * {@link TableContract#insertOrMergeEntity(String, Entity)}, - * {@link TableContract#insertOrMergeEntity(String, Entity, TableServiceOptions)}, - * {@link TableContract#insertOrReplaceEntity(String, Entity)}, - * {@link TableContract#insertOrReplaceEntity(String, Entity, TableServiceOptions)}, - * {@link TableContract#updateEntity(String, Entity)} and - * {@link TableContract#updateEntity(String, Entity, TableServiceOptions)}. - *

- * See the Update Entity documentation - * on MSDN for details of the underlying Table Service REST API operations. - */ -public class UpdateEntityResult { - private String etag; - - /** - * Gets the ETag value of the modified entity returned in the server response. - * - * @return - * A {@link String} containing the ETag value of the modified entity. - */ - public String getEtag() { - return etag; - } - - /** - * Reserved for internal use. Sets the ETag value of the modified entity from the ETag header value - * in the server response. - *

- * This method is invoked by the API to set the value from the Table Service REST API operation response returned by - * the server. - * - * @param etag - * A {@link String} containing the ETag value of the modified entity. - */ - public void setEtag(String etag) { - this.etag = etag; - } -} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/package.html deleted file mode 100644 index 5d3fb8ac686a3..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/models/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the table data transfer object classes. - - diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/package.html b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/package.html deleted file mode 100644 index 74b2c715f9884..0000000000000 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/table/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -This package contains the table service class, interface, and associated configuration and utility classes. - - diff --git a/microsoft-azure-api/src/main/resources/META-INF/services/com.microsoft.windowsazure.services.core.Builder$Exports b/microsoft-azure-api/src/main/resources/META-INF/services/com.microsoft.windowsazure.services.core.Builder$Exports deleted file mode 100644 index 7ba2c8c10b49e..0000000000000 --- a/microsoft-azure-api/src/main/resources/META-INF/services/com.microsoft.windowsazure.services.core.Builder$Exports +++ /dev/null @@ -1,9 +0,0 @@ -com.microsoft.windowsazure.services.blob.Exports -com.microsoft.windowsazure.services.queue.Exports -com.microsoft.windowsazure.services.table.Exports -com.microsoft.windowsazure.services.serviceBus.Exports -com.microsoft.windowsazure.services.serviceBus.implementation.Exports -com.microsoft.windowsazure.services.core.utils.Exports -com.microsoft.windowsazure.services.core.utils.pipeline.Exports -com.microsoft.windowsazure.services.media.Exports -com.microsoft.windowsazure.services.management.Exports diff --git a/microsoft-azure-api/src/main/resources/management/package-names.xjb b/microsoft-azure-api/src/main/resources/management/package-names.xjb deleted file mode 100644 index 183b2abd31b39..0000000000000 --- a/microsoft-azure-api/src/main/resources/management/package-names.xjb +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - diff --git a/microsoft-azure-api/src/main/resources/management/schemas.microsoft.com.windowsazure.xsd b/microsoft-azure-api/src/main/resources/management/schemas.microsoft.com.windowsazure.xsd deleted file mode 100644 index a09632d1c7725..0000000000000 --- a/microsoft-azure-api/src/main/resources/management/schemas.microsoft.com.windowsazure.xsd +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/microsoft-azure-api/src/main/resources/serviceBus/package-names.xjb b/microsoft-azure-api/src/main/resources/serviceBus/package-names.xjb deleted file mode 100644 index 534b69ac71b36..0000000000000 --- a/microsoft-azure-api/src/main/resources/serviceBus/package-names.xjb +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java deleted file mode 100644 index ddac6c4ac80bb..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.configuration.builder; - -import java.util.Map; - -import com.microsoft.windowsazure.services.core.Builder; - -public class AlterClassWithProperties implements Builder.Alteration { - @Override - public ClassWithProperties alter(String profile, ClassWithProperties instance, Builder builder, - Map properties) { - instance.setFoo(instance.getFoo() + " - changed"); - return instance; - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java deleted file mode 100644 index 5dd190c78b24e..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.configuration.builder; - -import java.util.HashMap; -import java.util.Map; - -import junit.framework.Assert; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import com.microsoft.windowsazure.services.core.DefaultBuilder; - -public class DefaultBuilderTest { - - Map properties; - DefaultBuilder builder; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void init() { - properties = new HashMap(); - builder = new DefaultBuilder(); - } - - @Test - public void namedAnnotationsComeFromBuildProperties() throws Exception { - // Arrange - builder.add(ClassWithNamedParameter.class); - - // Act - Map properties = new HashMap(); - properties.put("Foo", "world"); - ClassWithNamedParameter cwnp = builder.build("", ClassWithNamedParameter.class, ClassWithNamedParameter.class, - properties); - - // Assert - Assert.assertEquals("world", cwnp.getHello()); - } - - @Test - public void namedAnnotationReportsMissingProperty() throws Exception { - // Arrange - thrown.expect(RuntimeException.class); - - builder.add(ClassWithNamedParameter.class); - - // Act - ClassWithNamedParameter cwnp = builder.build("", ClassWithNamedParameter.class, ClassWithNamedParameter.class, - properties); - - // Assert - Assert.assertEquals("world", cwnp.getHello()); - } - - @Test - public void singleCtorWithNoInjectShouldBeUsed() throws Exception { - // Arrange - builder.add(ClassWithSingleCtorNoInject.class); - - // Act - ClassWithSingleCtorNoInject result = builder.build("", ClassWithSingleCtorNoInject.class, - ClassWithSingleCtorNoInject.class, properties); - - // Assert - Assert.assertNotNull(result); - } - - @Test - public void multipleCtorWithNoInjectShouldFail() throws Exception { - // Arrange - thrown.expect(RuntimeException.class); - - builder.add(ClassWithMultipleCtorNoInject.class); - - // Act - ClassWithMultipleCtorNoInject result = builder.build("", ClassWithMultipleCtorNoInject.class, - ClassWithMultipleCtorNoInject.class, properties); - - // Assert - Assert.assertTrue("Exception must occur", false); - Assert.assertNull("Result should be null", result); - } - - @Test - public void multipleCtorWithMultipleInjectShouldFail() throws Exception { - // Arrange - thrown.expect(RuntimeException.class); - - builder.add(ClassWithMultipleCtorMultipleInject.class); - - // Act - ClassWithMultipleCtorMultipleInject result = builder.build("", ClassWithMultipleCtorMultipleInject.class, - ClassWithMultipleCtorMultipleInject.class, properties); - - // Assert - Assert.assertTrue("Exception must occur", false); - Assert.assertNull("Result should be null", result); - } - - @Test - public void alterationExecutesWhenInstanceCreated() throws Exception { - // Arrange - builder.add(ClassWithProperties.class); - builder.alter(ClassWithProperties.class, ClassWithProperties.class, new AlterClassWithProperties()); - - // Act - ClassWithProperties result = builder - .build("", ClassWithProperties.class, ClassWithProperties.class, properties); - - // Assert - Assert.assertEquals("one - changed", result.getFoo()); - } - - @Test - public void namedParametersUseProfileBasedKeysFirst() throws Exception { - // Arrange - builder.add(ClassWithNamedParameter.class); - properties.put("Foo", "fallback"); - properties.put("testing.Foo", "Profile foo value"); - - // Act - ClassWithNamedParameter result = builder.build("testing", ClassWithNamedParameter.class, - ClassWithNamedParameter.class, properties); - - // Assert - Assert.assertEquals("Profile foo value", result.getHello()); - } - - @Test - public void namedParametersFallBackToNonProfileBasedKeys() throws Exception { - // Arrange - builder.add(ClassWithNamedParameter.class); - properties.put("Foo", "fallback"); - properties.put("testing.Foo", "Profile foo value"); - - // Act - ClassWithNamedParameter result1 = builder.build("", ClassWithNamedParameter.class, - ClassWithNamedParameter.class, properties); - ClassWithNamedParameter result2 = builder.build("production", ClassWithNamedParameter.class, - ClassWithNamedParameter.class, properties); - ClassWithNamedParameter result3 = builder.build("testing.custom", ClassWithNamedParameter.class, - ClassWithNamedParameter.class, properties); - - // Assert - Assert.assertEquals("fallback", result1.getHello()); - Assert.assertEquals("fallback", result2.getHello()); - Assert.assertEquals("fallback", result3.getHello()); - } - - @Test - public void namedParamatersFallBackFromLeftToRight() throws Exception { - // Arrange - builder.add(ClassWithNamedParameter.class); - properties.put("Foo", "fallback"); - properties.put("custom.Foo", "custom.Foo value"); - properties.put("testing.custom.Foo", "testing.custom.Foo value"); - - // Act - ClassWithNamedParameter result1 = builder.build("custom", ClassWithNamedParameter.class, - ClassWithNamedParameter.class, properties); - ClassWithNamedParameter result2 = builder.build("production.custom", ClassWithNamedParameter.class, - ClassWithNamedParameter.class, properties); - ClassWithNamedParameter result3 = builder.build("testing.custom", ClassWithNamedParameter.class, - ClassWithNamedParameter.class, properties); - - // Assert - Assert.assertEquals("custom.Foo value", result1.getHello()); - Assert.assertEquals("custom.Foo value", result2.getHello()); - Assert.assertEquals("testing.custom.Foo value", result3.getHello()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java deleted file mode 100644 index 903dc9756fd7b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.io.InputStream; -import java.util.LinkedList; -import java.util.List; - -import org.junit.Test; - -/** - * - */ -public class Protocol1RuntimeGoalStateClientTests { - private final List goalStates = new LinkedList(); - - @Test - public void addGoalStateChangedListenerAddsListener() { - Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); - - GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); - - RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { - @Override - public RoleEnvironmentData deserialize(InputStream stream) { - return null; - } - }; - - InputChannel inputChannel = new MockInputChannel(new String[] { - "" + "" + "1" - + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "", - "" + "" + "2" - + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "" }); - - Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, - goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); - - client.addGoalStateChangedListener(new GoalStateChangedListener() { - @Override - public void goalStateChanged(GoalState newGoalState) { - goalStates.add(newGoalState); - } - }); - - goalStates.clear(); - - try { - client.getCurrentGoalState(); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - try { - Thread.sleep(200); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - assertThat(goalStates.size(), is(1)); - assertThat(goalStates.get(0).getIncarnation().intValue(), is(2)); - } - - @Test - public void goalStateClientRestartsThread() { - Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); - - GoalStateDeserializer goalStateDeserializer = new GoalStateDeserializer() { - private final ChunkedGoalStateDeserializer deserializer = new ChunkedGoalStateDeserializer(); - - @Override - public void initialize(InputStream inputStream) { - deserializer.initialize(inputStream); - } - - @Override - public GoalState deserialize() { - GoalState goalState = deserializer.deserialize(); - - try { - Thread.sleep(200); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - goalStates.add(goalState); - - return goalState; - } - }; - - RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { - @Override - public RoleEnvironmentData deserialize(InputStream stream) { - return null; - } - }; - - InputChannel inputChannel = new MockInputChannel(new String[] { "" - + "" + "1" + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "" }); - - Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, - goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); - - goalStates.clear(); - - try { - client.getCurrentGoalState(); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - try { - Thread.sleep(1000); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - try { - client.getCurrentGoalState(); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - try { - Thread.sleep(2000); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - assertThat(goalStates.size(), is(3)); - } - - @Test - public void getRoleEnvironmentDataReturnsDeserializedData() { - Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); - - GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); - - final RoleEnvironmentData data = new RoleEnvironmentData(null, null, null, null, null, false); - - RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { - @Override - public RoleEnvironmentData deserialize(InputStream stream) { - return data; - } - }; - - InputChannel inputChannel = new MockInputChannel(new String[] { "" - + "" + "1" + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "" }); - - Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, - goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); - - try { - assertThat(client.getRoleEnvironmentData(), is(data)); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @Test - public void removeGoalStateChangedListenerRemovesListener() { - Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(null, null); - - GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); - - RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { - @Override - public RoleEnvironmentData deserialize(InputStream stream) { - return null; - } - }; - - InputChannel inputChannel = new MockInputChannel(new String[] { - "" + "" + "1" - + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "", - "" + "" + "2" - + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "" }); - - Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient(currentStateClient, - goalStateDeserializer, roleEnvironmentDeserializer, inputChannel); - - GoalStateChangedListener listener = new GoalStateChangedListener() { - @Override - public void goalStateChanged(GoalState newGoalState) { - goalStates.add(newGoalState); - } - }; - - client.addGoalStateChangedListener(listener); - client.removeGoalStateChangedListener(listener); - - goalStates.clear(); - - try { - client.getCurrentGoalState(); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - try { - Thread.sleep(200); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - assertThat(goalStates.size(), is(0)); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManagerTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManagerTests.java deleted file mode 100644 index da58a7bd1e25b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManagerTests.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.serviceruntime; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -import org.junit.Test; -import static org.junit.Assert.*; -import static org.hamcrest.Matchers.*; - -/** - * - */ -public class RuntimeVersionManagerTests { - @Test - public void getRuntimeClientForV1CanParseGoalState() { - RuntimeVersionManager manager = createVersionManagerWithGoalState("" - + "" + "1" + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "", "2011-03-08"); - - RuntimeClient runtimeClient = manager.getRuntimeClient(""); - GoalState goalState = null; - - try { - goalState = runtimeClient.getCurrentGoalState(); - } - catch (InterruptedException e) { - e.printStackTrace(); - } - - Calendar expectedDeadline = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT+00:00")); - - expectedDeadline.clear(); - expectedDeadline.set(2011, 2, 8, 3, 27, 44); - - assertThat(goalState.getIncarnation(), equalTo(BigInteger.ONE)); - assertThat(goalState.getExpectedState(), equalTo(ExpectedState.STARTED)); - assertThat(goalState.getEnvironmentPath(), equalTo("envpath")); - assertThat(goalState.getCurrentStateEndpoint(), equalTo("statepath")); - assertThat(goalState.getDeadline().getTimeInMillis(), equalTo(expectedDeadline.getTimeInMillis())); - } - - @Test - public void getRuntimeClientThrowsWhenNoSupportedVersionsFound() { - RuntimeVersionManager manager = createVersionManagerWithGoalState("" - + "" + "1" + "Started" - + "envpath" - + "statepath" - + "2011-03-08T03:27:44.0Z" + "", "notSupported"); - - try { - manager.getRuntimeClient(""); - } - catch (RuntimeException ex) { - return; - } - - fail(); - } - - private RuntimeVersionManager createVersionManagerWithGoalState(String goalStateXml, String version) { - File tempGoalState; - - try { - tempGoalState = File.createTempFile("tempGoalState", null); - FileOutputStream output = new FileOutputStream(tempGoalState); - - InputChannel goalStateChannel = new MockInputChannel(new String[] { goalStateXml }); - BufferedInputStream input = new BufferedInputStream(goalStateChannel.getInputStream("")); - - byte buffer[] = new byte[1024]; - int length = 0; - - while ((length = input.read(buffer)) > 0) { - output.write(buffer, 0, length); - } - - input.close(); - output.close(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - - InputChannel inputChannel = new MockInputChannel("" + "" - + "" + "" + "" + ""); - RuntimeVersionProtocolClient protocolClient = new RuntimeVersionProtocolClient(inputChannel); - return new RuntimeVersionManager(protocolClient); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/BlobServiceIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/BlobServiceIntegrationTest.java deleted file mode 100644 index 49f73558f7609..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/BlobServiceIntegrationTest.java +++ /dev/null @@ -1,1798 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob; - -import static org.junit.Assert.*; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import junit.framework.Assert; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.blob.models.AccessCondition; -import com.microsoft.windowsazure.services.blob.models.BlobProperties; -import com.microsoft.windowsazure.services.blob.models.BlockList; -import com.microsoft.windowsazure.services.blob.models.BreakLeaseResult; -import com.microsoft.windowsazure.services.blob.models.ContainerACL; -import com.microsoft.windowsazure.services.blob.models.ContainerACL.PublicAccessType; -import com.microsoft.windowsazure.services.blob.models.CopyBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobPagesResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobResult; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotOptions; -import com.microsoft.windowsazure.services.blob.models.CreateBlobSnapshotResult; -import com.microsoft.windowsazure.services.blob.models.CreateContainerOptions; -import com.microsoft.windowsazure.services.blob.models.DeleteBlobOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.GetBlobPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.GetBlobResult; -import com.microsoft.windowsazure.services.blob.models.GetContainerPropertiesResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobBlocksResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobRegionsResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobsOptions; -import com.microsoft.windowsazure.services.blob.models.ListBlobsResult; -import com.microsoft.windowsazure.services.blob.models.ListBlobsResult.BlobEntry; -import com.microsoft.windowsazure.services.blob.models.ListContainersOptions; -import com.microsoft.windowsazure.services.blob.models.ListContainersResult; -import com.microsoft.windowsazure.services.blob.models.ListContainersResult.Container; -import com.microsoft.windowsazure.services.blob.models.PageRange; -import com.microsoft.windowsazure.services.blob.models.ServiceProperties; -import com.microsoft.windowsazure.services.blob.models.SetBlobMetadataResult; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesOptions; -import com.microsoft.windowsazure.services.blob.models.SetBlobPropertiesResult; -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.ExponentialRetryPolicy; -import com.microsoft.windowsazure.services.core.RetryPolicyFilter; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; - -public class BlobServiceIntegrationTest extends IntegrationTestBase { - private static final String testContainersPrefix = "sdktest-"; - private static final String createableContainersPrefix = "csdktest-"; - private static final String BLOB_FOR_ROOT_CONTAINER = "sdktestroot"; - private static String CREATEABLE_CONTAINER_1; - private static String CREATEABLE_CONTAINER_2; - private static String CREATEABLE_CONTAINER_3; - private static String CREATEABLE_CONTAINER_4; - private static String TEST_CONTAINER_FOR_BLOBS; - private static String TEST_CONTAINER_FOR_BLOBS_2; - private static String TEST_CONTAINER_FOR_LISTING; - private static String[] creatableContainers; - private static String[] testContainers; - private static boolean createdRoot; - - @BeforeClass - public static void setup() throws Exception { - // Setup container names array (list of container names used by - // integration tests) - testContainers = new String[10]; - for (int i = 0; i < testContainers.length; i++) { - testContainers[i] = String.format("%s%d", testContainersPrefix, i + 1); - } - - creatableContainers = new String[10]; - for (int i = 0; i < creatableContainers.length; i++) { - creatableContainers[i] = String.format("%s%d", createableContainersPrefix, i + 1); - } - - CREATEABLE_CONTAINER_1 = creatableContainers[0]; - CREATEABLE_CONTAINER_2 = creatableContainers[1]; - CREATEABLE_CONTAINER_3 = creatableContainers[2]; - CREATEABLE_CONTAINER_4 = creatableContainers[3]; - - TEST_CONTAINER_FOR_BLOBS = testContainers[0]; - TEST_CONTAINER_FOR_BLOBS_2 = testContainers[1]; - TEST_CONTAINER_FOR_LISTING = testContainers[2]; - - // Create all test containers and their content - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - createContainers(service, testContainersPrefix, testContainers); - - try { - service.createContainer("$root"); - createdRoot = true; - } - catch (ServiceException e) { - e.printStackTrace(); - } - } - - @AfterClass - public static void cleanup() throws Exception { - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - deleteContainers(service, testContainersPrefix, testContainers); - deleteContainers(service, createableContainersPrefix, creatableContainers); - - // If container was created, delete it - if (createdRoot) { - try { - service.deleteContainer("$root"); - createdRoot = false; - } - catch (ServiceException e) { - e.printStackTrace(); - } - } - } - - private static void createContainers(BlobContract service, String prefix, String[] list) throws Exception { - Set containers = listContainers(service, prefix); - for (String item : list) { - if (!containers.contains(item)) { - service.createContainer(item); - } - } - } - - private static void deleteContainers(BlobContract service, String prefix, String[] list) throws Exception { - Set containers = listContainers(service, prefix); - for (String item : list) { - if (containers.contains(item)) { - service.deleteContainer(item); - } - } - } - - private static Set listContainers(BlobContract service, String prefix) throws Exception { - HashSet result = new HashSet(); - ListContainersResult list = service.listContainers(new ListContainersOptions().setPrefix(prefix)); - for (Container item : list.getContainers()) { - result.add(item.getName()); - } - return result; - } - - @Test - public void getServiceProppertiesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Don't run this test with emulator, as v1.6 doesn't support this method - if (isRunningWithEmulator(config)) { - return; - } - - // Act - ServiceProperties props = service.getServiceProperties().getValue(); - - // Assert - assertNotNull(props); - assertNotNull(props.getLogging()); - assertNotNull(props.getLogging().getRetentionPolicy()); - assertNotNull(props.getLogging().getVersion()); - assertNotNull(props.getMetrics().getRetentionPolicy()); - assertNotNull(props.getMetrics().getVersion()); - } - - @Test - public void setServiceProppertiesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Don't run this test with emulator, as v1.6 doesn't support this method - if (isRunningWithEmulator(config)) { - return; - } - - // Act - ServiceProperties props = service.getServiceProperties().getValue(); - - props.setDefaultServiceVersion("2009-09-19"); - props.getLogging().setRead(true); - service.setServiceProperties(props); - - props = service.getServiceProperties().getValue(); - - // Assert - assertNotNull(props); - assertEquals("2009-09-19", props.getDefaultServiceVersion()); - assertNotNull(props.getLogging()); - assertNotNull(props.getLogging().getRetentionPolicy()); - assertNotNull(props.getLogging().getVersion()); - assertTrue(props.getLogging().isRead()); - assertNotNull(props.getMetrics().getRetentionPolicy()); - assertNotNull(props.getMetrics().getVersion()); - } - - @Test - public void createContainerWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createContainer(CREATEABLE_CONTAINER_1); - - // Assert - } - - @Test(expected = IllegalArgumentException.class) - public void createNullContainerFail() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createContainer(null); - - // Assert - assertTrue(false); - } - - @Test - public void createContainerWithMetadataWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createContainer(CREATEABLE_CONTAINER_2, new CreateContainerOptions().setPublicAccess("blob") - .addMetadata("test", "bar").addMetadata("blah", "bleah")); - - GetContainerPropertiesResult prop = service.getContainerMetadata(CREATEABLE_CONTAINER_2); - GetContainerPropertiesResult prop2 = service.getContainerProperties(CREATEABLE_CONTAINER_2); - ContainerACL acl = service.getContainerACL(CREATEABLE_CONTAINER_2).getContainerACL(); - - ListContainersResult results2 = service.listContainers(new ListContainersOptions().setPrefix( - CREATEABLE_CONTAINER_2).setIncludeMetadata(true)); - - service.deleteContainer(CREATEABLE_CONTAINER_2); - - // Assert - assertNotNull(prop); - assertNotNull(prop.getEtag()); - assertNotNull(prop.getLastModified()); - assertNotNull(prop.getMetadata()); - assertEquals(2, prop.getMetadata().size()); - assertTrue(prop.getMetadata().containsKey("test")); - assertTrue(prop.getMetadata().containsValue("bar")); - assertTrue(prop.getMetadata().containsKey("blah")); - assertTrue(prop.getMetadata().containsValue("bleah")); - - assertNotNull(prop2); - assertNotNull(prop2.getEtag()); - assertNotNull(prop2.getLastModified()); - assertNotNull(prop2.getMetadata()); - assertEquals(2, prop2.getMetadata().size()); - assertTrue(prop2.getMetadata().containsKey("test")); - assertTrue(prop2.getMetadata().containsValue("bar")); - assertTrue(prop2.getMetadata().containsKey("blah")); - assertTrue(prop2.getMetadata().containsValue("bleah")); - - assertNotNull(results2); - assertEquals(1, results2.getContainers().size()); - assertTrue(results2.getContainers().get(0).getMetadata().containsKey("test")); - assertTrue(results2.getContainers().get(0).getMetadata().containsValue("bar")); - assertTrue(results2.getContainers().get(0).getMetadata().containsKey("blah")); - assertTrue(results2.getContainers().get(0).getMetadata().containsValue("bleah")); - - assertNotNull(acl); - - } - - @Test - public void deleteContainerWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String containerName = "deletecontainerworks"; - service.createContainer( - containerName, - new CreateContainerOptions().setPublicAccess("blob").addMetadata("test", "bar") - .addMetadata("blah", "bleah")); - - // Act - service.deleteContainer(containerName); - ListContainersResult listContainerResult = service.listContainers(); - - // Assert - for (Container container : listContainerResult.getContainers()) { - assertTrue(!container.getName().equals(containerName)); - } - } - - @Test(expected = IllegalArgumentException.class) - public void deleteNullContainerFail() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.deleteContainer(null); - - // Assert - assertTrue(false); - } - - @Test - public void setContainerMetadataWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createContainer(CREATEABLE_CONTAINER_3); - - HashMap metadata = new HashMap(); - metadata.put("test", "bar"); - metadata.put("blah", "bleah"); - service.setContainerMetadata(CREATEABLE_CONTAINER_3, metadata); - GetContainerPropertiesResult prop = service.getContainerMetadata(CREATEABLE_CONTAINER_3); - - // Assert - assertNotNull(prop); - assertNotNull(prop.getEtag()); - assertNotNull(prop.getLastModified()); - assertNotNull(prop.getMetadata()); - assertEquals(2, prop.getMetadata().size()); - assertTrue(prop.getMetadata().containsKey("test")); - assertTrue(prop.getMetadata().containsValue("bar")); - assertTrue(prop.getMetadata().containsKey("blah")); - assertTrue(prop.getMetadata().containsValue("bleah")); - } - - @Test - public void setContainerACLWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - String container = CREATEABLE_CONTAINER_4; - Date expiryStartDate = new GregorianCalendar(2010, 1, 1).getTime(); - Date expiryEndDate = new GregorianCalendar(2020, 1, 1).getTime(); - - // Act - service.createContainer(container); - - ContainerACL acl = new ContainerACL(); - acl.setPublicAccess(PublicAccessType.BLOBS_ONLY); - acl.addSignedIdentifier("test", expiryStartDate, expiryEndDate, "rwd"); - service.setContainerACL(container, acl); - - ContainerACL acl2 = service.getContainerACL(container).getContainerACL(); - service.deleteContainer(container); - - // Assert - assertNotNull(acl2); - assertNotNull(acl2.getEtag()); - assertNotNull(acl2.getLastModified()); - assertNotNull(acl2.getPublicAccess()); - assertEquals(PublicAccessType.BLOBS_ONLY, acl2.getPublicAccess()); - assertEquals(1, acl2.getSignedIdentifiers().size()); - assertEquals("test", acl2.getSignedIdentifiers().get(0).getId()); - assertEquals(expiryStartDate, acl2.getSignedIdentifiers().get(0).getAccessPolicy().getStart()); - assertEquals(expiryEndDate, acl2.getSignedIdentifiers().get(0).getAccessPolicy().getExpiry()); - assertEquals("rwd", acl2.getSignedIdentifiers().get(0).getAccessPolicy().getPermission()); - } - - @Test - public void listContainersWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - ListContainersResult results = service.listContainers(); - - // Assert - assertNotNull(results); - assertTrue(testContainers.length <= results.getContainers().size()); - assertNotNull(results.getContainers().get(0).getName()); - assertNotNull(results.getContainers().get(0).getMetadata()); - assertNotNull(results.getContainers().get(0).getProperties()); - assertNotNull(results.getContainers().get(0).getProperties().getEtag()); - assertNotNull(results.getContainers().get(0).getProperties().getLastModified()); - assertNotNull(results.getContainers().get(0).getUrl()); - } - - @Test - public void listContainersWithPaginationWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - ListContainersResult results = service.listContainers(new ListContainersOptions().setMaxResults(3)); - ListContainersResult results2 = service.listContainers(new ListContainersOptions().setMarker(results - .getNextMarker())); - - // Assert - assertNotNull(results); - assertEquals(3, results.getContainers().size()); - assertNotNull(results.getNextMarker()); - assertEquals(3, results.getMaxResults()); - - assertNotNull(results2); - assertTrue(testContainers.length - 3 <= results2.getContainers().size()); - assertEquals("", results2.getNextMarker()); - assertEquals(0, results2.getMaxResults()); - } - - @Test - public void listContainersWithPrefixWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - ListContainersResult results = service.listContainers(new ListContainersOptions().setPrefix( - testContainersPrefix).setMaxResults(3)); - // Assert - assertNotNull(results); - assertEquals(3, results.getContainers().size()); - assertNotNull(results.getNextMarker()); - assertEquals(3, results.getMaxResults()); - - // Act - ListContainersResult results2 = service.listContainers(new ListContainersOptions().setPrefix( - testContainersPrefix).setMarker(results.getNextMarker())); - - // Assert - assertNotNull(results2); - assertNotNull(results2.getNextMarker()); - assertEquals(0, results2.getMaxResults()); - - // Act - ListContainersResult results3 = service.listContainers(new ListContainersOptions() - .setPrefix(testContainersPrefix)); - - // Assert - assertEquals(results.getContainers().size() + results2.getContainers().size(), results3.getContainers().size()); - } - - @Test - public void workingWithRootContainersWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // - // Work with root container explicitly ("$root") - // - { - // Act - service.createPageBlob("$root", BLOB_FOR_ROOT_CONTAINER, 512); - ListBlobsResult list = service.listBlobs("$root"); - GetBlobPropertiesResult properties = service.getBlobProperties("$root", BLOB_FOR_ROOT_CONTAINER); - GetBlobMetadataResult metadata = service.getBlobMetadata("$root", BLOB_FOR_ROOT_CONTAINER); - - // Assert - assertNotNull(list); - assertTrue(1 <= list.getBlobs().size()); - assertNotNull(properties); - assertNotNull(metadata); - - // Act - service.deleteBlob("$root", BLOB_FOR_ROOT_CONTAINER); - } - - // - // Work with root container implicitly ("") - // - { - // Act - service.createPageBlob("", BLOB_FOR_ROOT_CONTAINER, 512); - // "$root" must be explicit when listing blobs in the root container - ListBlobsResult list = service.listBlobs("$root"); - GetBlobPropertiesResult properties = service.getBlobProperties("", BLOB_FOR_ROOT_CONTAINER); - GetBlobMetadataResult metadata = service.getBlobMetadata("", BLOB_FOR_ROOT_CONTAINER); - - // Assert - assertNotNull(list); - assertTrue(1 <= list.getBlobs().size()); - assertNotNull(properties); - assertNotNull(metadata); - - // Act - service.deleteBlob("", BLOB_FOR_ROOT_CONTAINER); - } - } - - @Test - public void listBlobsWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String[] blobNames = { "myblob1", "myblob2", "other-blob1", "other-blob2" }; - for (String blob : blobNames) { - service.createPageBlob(TEST_CONTAINER_FOR_LISTING, blob, 512); - } - - // Act - ListBlobsResult results = service.listBlobs(TEST_CONTAINER_FOR_LISTING); - - for (String blob : blobNames) { - service.deleteBlob(TEST_CONTAINER_FOR_LISTING, blob); - } - - // Assert - assertNotNull(results); - assertEquals(4, results.getBlobs().size()); - } - - @Test - public void listBlobsWithPrefixWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String[] blobNames = { "myblob1", "myblob2", "otherblob1", "otherblob2" }; - for (String blob : blobNames) { - service.createPageBlob(TEST_CONTAINER_FOR_LISTING, blob, 512); - } - - // Act - ListBlobsResult results = service.listBlobs(TEST_CONTAINER_FOR_LISTING, - new ListBlobsOptions().setPrefix("myblob")); - ListBlobsResult results2 = service.listBlobs(TEST_CONTAINER_FOR_LISTING, new ListBlobsOptions().setPrefix("o")); - - for (String blob : blobNames) { - service.deleteBlob(TEST_CONTAINER_FOR_LISTING, blob); - } - - // Assert - assertNotNull(results); - assertEquals(2, results.getBlobs().size()); - assertEquals("myblob1", results.getBlobs().get(0).getName()); - assertEquals("myblob2", results.getBlobs().get(1).getName()); - - assertNotNull(results2); - assertEquals(2, results2.getBlobs().size()); - assertEquals("otherblob1", results2.getBlobs().get(0).getName()); - assertEquals("otherblob2", results2.getBlobs().get(1).getName()); - } - - @Test - public void listBlobsWithOptionsWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String[] blobNames = { "myblob1", "myblob2", "otherblob1", "otherblob2" }; - for (String blob : blobNames) { - service.createPageBlob(TEST_CONTAINER_FOR_LISTING, blob, 512); - } - - // Act - ListBlobsResult results = service.listBlobs(TEST_CONTAINER_FOR_LISTING, new ListBlobsOptions() - .setIncludeMetadata(true).setIncludeSnapshots(true)); - - for (String blob : blobNames) { - service.deleteBlob(TEST_CONTAINER_FOR_LISTING, blob); - } - - // Assert - assertNotNull(results); - assertEquals(4, results.getBlobs().size()); - } - - @Test - public void listBlobsWithDelimiterWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String[] blobNames = { "myblob1", "myblob2", "dir1-blob1", "dir1-blob2", "dir2-dir21-blob3", "dir2-dir22-blob3" }; - for (String blob : blobNames) { - service.createPageBlob(TEST_CONTAINER_FOR_LISTING, blob, 512); - } - - // Act - ListBlobsResult results = service.listBlobs(TEST_CONTAINER_FOR_LISTING, - new ListBlobsOptions().setDelimiter("-")); - ListBlobsResult results2 = service.listBlobs(TEST_CONTAINER_FOR_LISTING, - new ListBlobsOptions().setDelimiter("-").setPrefix("dir1-")); - ListBlobsResult results3 = service.listBlobs(TEST_CONTAINER_FOR_LISTING, - new ListBlobsOptions().setDelimiter("-").setPrefix("dir2-")); - ListBlobsResult results4 = service.listBlobs(TEST_CONTAINER_FOR_LISTING, - new ListBlobsOptions().setDelimiter("-").setPrefix("dir2-dir21-")); - ListBlobsResult results5 = service.listBlobs(TEST_CONTAINER_FOR_LISTING, - new ListBlobsOptions().setDelimiter("-").setPrefix("dir2-dir22-")); - ListBlobsResult results6 = service.listBlobs(TEST_CONTAINER_FOR_LISTING, - new ListBlobsOptions().setDelimiter("-").setPrefix("dir2-dir44-")); - - for (String blob : blobNames) { - service.deleteBlob(TEST_CONTAINER_FOR_LISTING, blob); - } - - // Assert - assertNotNull(results); - assertEquals(2, results.getBlobs().size()); - assertEquals(2, results.getBlobPrefixes().size()); - - assertEquals(2, results2.getBlobs().size()); - assertEquals(0, results2.getBlobPrefixes().size()); - - assertEquals(0, results3.getBlobs().size()); - assertEquals(2, results3.getBlobPrefixes().size()); - - assertEquals(1, results4.getBlobs().size()); - assertEquals(0, results4.getBlobPrefixes().size()); - - assertEquals(1, results5.getBlobs().size()); - assertEquals(0, results5.getBlobPrefixes().size()); - - assertEquals(0, results6.getBlobs().size()); - assertEquals(0, results6.getBlobPrefixes().size()); - } - - @Test - public void listBlockBlobWithNoCommittedBlocksWorks() throws Exception { - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "listBlockBlobWithNoCommittedBlocksWorks"; - - service.createBlockBlob(container, blob, null); - service.createBlobBlock(container, blob, "01", new ByteArrayInputStream(new byte[] { 0x00 })); - service.deleteBlob(container, blob); - - try { - // Note: This next two lines should give a 404, because the blob no longer - // exists. However, the service sometimes allow this improper access, so - // the SDK has to handle the situation gracefully. - service.createBlobBlock(container, blob, "01", new ByteArrayInputStream(new byte[] { 0x00 })); - ListBlobBlocksResult result = service.listBlobBlocks(container, blob); - assertEquals(0, result.getCommittedBlocks().size()); - } - catch (ServiceException ex) { - assertEquals(404, ex.getHttpStatusCode()); - } - } - - @Test - public void createPageBlobWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 512); - - // Assert - } - - @Test - public void createPageBlobWithETagSuccess() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - CreateBlobResult createBlobResult = service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 512); - - // Assert - assertNotNull(createBlobResult); - assertNotNull(createBlobResult.getEtag()); - } - - @Test - public void createPageBlobWithOptionsWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 512, - new CreateBlobOptions().setBlobCacheControl("test").setBlobContentEncoding("UTF-8") - .setBlobContentLanguage("en-us") - /* .setBlobContentMD5("1234") */.setBlobContentType("text/plain").setCacheControl("test") - .setContentEncoding("UTF-8") - /* .setContentMD5("1234") */.setContentType("text/plain")); - - GetBlobPropertiesResult result = service.getBlobProperties(TEST_CONTAINER_FOR_BLOBS, "test"); - - // Assert - assertNotNull(result); - - assertNotNull(result.getMetadata()); - assertEquals(0, result.getMetadata().size()); - - BlobProperties props = result.getProperties(); - assertNotNull(props); - assertEquals("test", props.getCacheControl()); - assertEquals("UTF-8", props.getContentEncoding()); - assertEquals("en-us", props.getContentLanguage()); - assertEquals("text/plain", props.getContentType()); - assertEquals(512, props.getContentLength()); - assertNotNull(props.getEtag()); - assertNull(props.getContentMD5()); - assertNotNull(props.getLastModified()); - assertEquals("PageBlob", props.getBlobType()); - assertEquals("unlocked", props.getLeaseStatus()); - assertEquals(0, props.getSequenceNumber()); - } - - @Test - public void clearBlobPagesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - service.createPageBlob(container, blob, 512); - - CreateBlobPagesResult result = service.clearBlobPages(container, blob, new PageRange(0, 511)); - - // Assert - assertNotNull(result); - assertNull(result.getContentMD5()); - assertNotNull(result.getLastModified()); - assertNotNull(result.getEtag()); - assertEquals(0, result.getSequenceNumber()); - } - - @Test - public void createBlobPagesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - String content = new String(new char[512]); - service.createPageBlob(container, blob, 512); - - CreateBlobPagesResult result = service.createBlobPages(container, blob, new PageRange(0, 511), - content.length(), new ByteArrayInputStream(content.getBytes("UTF-8"))); - - // Assert - assertNotNull(result); - assertNotNull(result.getContentMD5()); - assertNotNull(result.getLastModified()); - assertNotNull(result.getEtag()); - assertEquals(0, result.getSequenceNumber()); - } - - @Test - public void listBlobRegionsWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - String content = new String(new char[512]); - service.createPageBlob(container, blob, 16384 + 512); - - service.createBlobPages(container, blob, new PageRange(0, 511), content.length(), new ByteArrayInputStream( - content.getBytes("UTF-8"))); - service.createBlobPages(container, blob, new PageRange(1024, 1024 + 511), content.length(), - new ByteArrayInputStream(content.getBytes("UTF-8"))); - service.createBlobPages(container, blob, new PageRange(8192, 8192 + 511), content.length(), - new ByteArrayInputStream(content.getBytes("UTF-8"))); - service.createBlobPages(container, blob, new PageRange(16384, 16384 + 511), content.length(), - new ByteArrayInputStream(content.getBytes("UTF-8"))); - - ListBlobRegionsResult result = service.listBlobRegions(container, blob); - - // Assert - assertNotNull(result); - assertNotNull(result.getLastModified()); - assertNotNull(result.getEtag()); - assertEquals(16384 + 512, result.getContentLength()); - assertNotNull(result.getPageRanges()); - assertEquals(4, result.getPageRanges().size()); - assertEquals(0, result.getPageRanges().get(0).getStart()); - assertEquals(511, result.getPageRanges().get(0).getEnd()); - assertEquals(1024, result.getPageRanges().get(1).getStart()); - assertEquals(1024 + 511, result.getPageRanges().get(1).getEnd()); - assertEquals(8192, result.getPageRanges().get(2).getStart()); - assertEquals(8192 + 511, result.getPageRanges().get(2).getEnd()); - assertEquals(16384, result.getPageRanges().get(3).getStart()); - assertEquals(16384 + 511, result.getPageRanges().get(3).getEnd()); - } - - @Test - public void listBlobBlocksOnEmptyBlobWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test13"; - String content = new String(new char[512]); - service.createBlockBlob(container, blob, new ByteArrayInputStream(content.getBytes("UTF-8"))); - - ListBlobBlocksResult result = service.listBlobBlocks(container, blob); - - // Assert - assertNotNull(result); - assertNotNull(result.getLastModified()); - assertNotNull(result.getEtag()); - assertEquals(512, result.getContentLength()); - assertNotNull(result.getCommittedBlocks()); - assertEquals(0, result.getCommittedBlocks().size()); - assertNotNull(result.getUncommittedBlocks()); - assertEquals(0, result.getUncommittedBlocks().size()); - } - - @Test - public void listBlobBlocksWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test14"; - service.createBlockBlob(container, blob, null); - service.createBlobBlock(container, blob, "123", new ByteArrayInputStream(new byte[256])); - service.createBlobBlock(container, blob, "124", new ByteArrayInputStream(new byte[512])); - service.createBlobBlock(container, blob, "125", new ByteArrayInputStream(new byte[195])); - - ListBlobBlocksResult result = service.listBlobBlocks(container, blob, new ListBlobBlocksOptions() - .setCommittedList(true).setUncommittedList(true)); - - // Assert - assertNotNull(result); - assertNotNull(result.getLastModified()); - assertNotNull(result.getEtag()); - assertEquals(0, result.getContentLength()); - assertNotNull(result.getCommittedBlocks()); - assertEquals(0, result.getCommittedBlocks().size()); - assertNotNull(result.getUncommittedBlocks()); - assertEquals(3, result.getUncommittedBlocks().size()); - assertEquals("123", result.getUncommittedBlocks().get(0).getBlockId()); - assertEquals(256, result.getUncommittedBlocks().get(0).getBlockLength()); - assertEquals("124", result.getUncommittedBlocks().get(1).getBlockId()); - assertEquals(512, result.getUncommittedBlocks().get(1).getBlockLength()); - assertEquals("125", result.getUncommittedBlocks().get(2).getBlockId()); - assertEquals(195, result.getUncommittedBlocks().get(2).getBlockLength()); - } - - @Test - public void listBlobBlocksWithOptionsWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test14"; - service.createBlockBlob(container, blob, null); - service.createBlobBlock(container, blob, "123", new ByteArrayInputStream(new byte[256])); - - BlockList blockList = new BlockList(); - blockList.addUncommittedEntry("123"); - service.commitBlobBlocks(container, blob, blockList); - - service.createBlobBlock(container, blob, "124", new ByteArrayInputStream(new byte[512])); - service.createBlobBlock(container, blob, "125", new ByteArrayInputStream(new byte[195])); - - ListBlobBlocksResult result1 = service.listBlobBlocks(container, blob, new ListBlobBlocksOptions() - .setCommittedList(true).setUncommittedList(true)); - ListBlobBlocksResult result2 = service.listBlobBlocks(container, blob, - new ListBlobBlocksOptions().setCommittedList(true)); - ListBlobBlocksResult result3 = service.listBlobBlocks(container, blob, - new ListBlobBlocksOptions().setUncommittedList(true)); - - // Assert - assertEquals(1, result1.getCommittedBlocks().size()); - assertEquals(2, result1.getUncommittedBlocks().size()); - - assertEquals(1, result2.getCommittedBlocks().size()); - assertEquals(0, result2.getUncommittedBlocks().size()); - - assertEquals(0, result3.getCommittedBlocks().size()); - assertEquals(2, result3.getUncommittedBlocks().size()); - } - - @Test - public void commitBlobBlocksWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test14"; - String blockId1 = "1fedcba"; - String blockId2 = "2abcdef"; - String blockId3 = "3zzzzzz"; - service.createBlockBlob(container, blob, null); - service.createBlobBlock(container, blob, blockId1, new ByteArrayInputStream(new byte[256])); - service.createBlobBlock(container, blob, blockId2, new ByteArrayInputStream(new byte[512])); - service.createBlobBlock(container, blob, blockId3, new ByteArrayInputStream(new byte[195])); - - BlockList blockList = new BlockList(); - blockList.addUncommittedEntry(blockId1).addLatestEntry(blockId3); - service.commitBlobBlocks(container, blob, blockList); - - ListBlobBlocksResult result = service.listBlobBlocks(container, blob, new ListBlobBlocksOptions() - .setCommittedList(true).setUncommittedList(true)); - - // Assert - assertNotNull(result); - assertNotNull(result.getLastModified()); - assertNotNull(result.getEtag()); - assertEquals(256 + 195, result.getContentLength()); - - assertNotNull(result.getCommittedBlocks()); - assertEquals(2, result.getCommittedBlocks().size()); - assertEquals(blockId1, result.getCommittedBlocks().get(0).getBlockId()); - assertEquals(256, result.getCommittedBlocks().get(0).getBlockLength()); - assertEquals(blockId3, result.getCommittedBlocks().get(1).getBlockId()); - assertEquals(195, result.getCommittedBlocks().get(1).getBlockLength()); - - assertNotNull(result.getUncommittedBlocks()); - assertEquals(0, result.getUncommittedBlocks().size()); - } - - @Test - public void createBlobBlockWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test13"; - String content = new String(new char[512]); - service.createBlockBlob(container, blob, new ByteArrayInputStream(content.getBytes("UTF-8"))); - service.createBlobBlock(container, blob, "123", new ByteArrayInputStream(content.getBytes("UTF-8"))); - service.createBlobBlock(container, blob, "124", new ByteArrayInputStream(content.getBytes("UTF-8"))); - - // Assert - } - - @Test - public void createBlobBlockNullContainerWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = null; - String blob = "createblobblocknullcontainerworks"; - String content = new String(new char[512]); - service.createBlockBlob(container, blob, new ByteArrayInputStream(content.getBytes("UTF-8"))); - GetBlobPropertiesResult result = service.getBlobProperties(null, blob); - GetBlobResult getBlobResult = service.getBlob(null, blob); - - // Assert - assertNotNull(result); - assertNotNull(result.getMetadata()); - assertEquals(0, result.getMetadata().size()); - BlobProperties props = result.getProperties(); - assertNotNull(props); - - assertEquals(content, inputStreamToString(getBlobResult.getContentStream(), "UTF-8")); - } - - @Test - public void createBlockBlobWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test2", new ByteArrayInputStream("some content".getBytes())); - - // Assert - } - - @Test - public void createBlockBlobWithValidEtag() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - CreateBlobResult createBlobResult = service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test2", - new ByteArrayInputStream("some content".getBytes())); - - // Assert - assertNotNull(createBlobResult); - assertNotNull(createBlobResult.getEtag()); - } - - @Test - public void createBlockBlobWithOptionsWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String content = "some content"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test2", new ByteArrayInputStream(content.getBytes("UTF-8")), - new CreateBlobOptions().setBlobCacheControl("test").setBlobContentEncoding("UTF-8") - .setBlobContentLanguage("en-us") - /* .setBlobContentMD5("1234") */.setBlobContentType("text/plain").setCacheControl("test") - .setContentEncoding("UTF-8") - /* .setContentMD5("1234") */.setContentType("text/plain")); - - GetBlobPropertiesResult result = service.getBlobProperties(TEST_CONTAINER_FOR_BLOBS, "test2"); - - // Assert - assertNotNull(result); - - assertNotNull(result.getMetadata()); - assertEquals(0, result.getMetadata().size()); - - BlobProperties props = result.getProperties(); - assertNotNull(props); - assertEquals("test", props.getCacheControl()); - assertEquals("UTF-8", props.getContentEncoding()); - assertEquals("en-us", props.getContentLanguage()); - assertEquals("text/plain", props.getContentType()); - assertEquals(content.length(), props.getContentLength()); - assertNotNull(props.getEtag()); - assertNull(props.getContentMD5()); - assertNotNull(props.getLastModified()); - assertEquals("BlockBlob", props.getBlobType()); - assertEquals("unlocked", props.getLeaseStatus()); - assertEquals(0, props.getSequenceNumber()); - } - - @Test - public void createBlobSnapshotWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test3"; - service.createBlockBlob(container, blob, new ByteArrayInputStream("some content".getBytes())); - CreateBlobSnapshotResult snapshot = service.createBlobSnapshot(container, blob); - - // Assert - assertNotNull(snapshot); - assertNotNull(snapshot.getEtag()); - assertNotNull(snapshot.getLastModified()); - assertNotNull(snapshot.getSnapshot()); - } - - @Test - public void createBlobSnapshotWithOptionsWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test3"; - service.createBlockBlob(container, blob, new ByteArrayInputStream("some content".getBytes())); - CreateBlobSnapshotResult snapshot = service.createBlobSnapshot(container, blob, new CreateBlobSnapshotOptions() - .addMetadata("test", "bar").addMetadata("blah", "bleah")); - - GetBlobPropertiesResult result = service.getBlobProperties(container, blob, - new GetBlobPropertiesOptions().setSnapshot(snapshot.getSnapshot())); - - // Assert - assertNotNull(result); - assertEquals(snapshot.getEtag(), result.getProperties().getEtag()); - assertEquals(snapshot.getLastModified(), result.getProperties().getLastModified()); - assertTrue(result.getMetadata().containsKey("test")); - assertTrue(result.getMetadata().containsValue("bar")); - assertTrue(result.getMetadata().containsKey("blah")); - assertTrue(result.getMetadata().containsValue("bleah")); - } - - @Test - public void getBlockBlobWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String content = "some content"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test2", new ByteArrayInputStream(content.getBytes("UTF-8")), - new CreateBlobOptions().setBlobCacheControl("test").setBlobContentEncoding("UTF-8") - .setBlobContentLanguage("en-us") - /* .setBlobContentMD5("1234") */.setBlobContentType("text/plain").setCacheControl("test") - .setContentEncoding("UTF-8") - /* .setContentMD5("1234") */.setContentType("text/plain")); - - GetBlobResult result = service.getBlob(TEST_CONTAINER_FOR_BLOBS, "test2"); - - // Assert - assertNotNull(result); - - assertNotNull(result.getMetadata()); - assertEquals(0, result.getMetadata().size()); - - BlobProperties props = result.getProperties(); - assertNotNull(props); - assertEquals("test", props.getCacheControl()); - assertEquals("UTF-8", props.getContentEncoding()); - assertEquals("en-us", props.getContentLanguage()); - assertEquals("text/plain", props.getContentType()); - assertEquals(content.length(), props.getContentLength()); - assertNotNull(props.getEtag()); - assertNull(props.getContentMD5()); - assertNotNull(props.getLastModified()); - assertEquals("BlockBlob", props.getBlobType()); - assertEquals("unlocked", props.getLeaseStatus()); - assertEquals(0, props.getSequenceNumber()); - assertEquals(content, inputStreamToString(result.getContentStream(), "UTF-8")); - } - - @Test - public void getPageBlobWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 4096, - new CreateBlobOptions().setBlobCacheControl("test").setBlobContentEncoding("UTF-8") - .setBlobContentLanguage("en-us") - /* .setBlobContentMD5("1234") */.setBlobContentType("text/plain").setCacheControl("test") - .setContentEncoding("UTF-8") - /* .setContentMD5("1234") */.setContentType("text/plain")); - - GetBlobResult result = service.getBlob(TEST_CONTAINER_FOR_BLOBS, "test"); - - // Assert - assertNotNull(result); - - assertNotNull(result.getMetadata()); - assertEquals(0, result.getMetadata().size()); - - BlobProperties props = result.getProperties(); - assertEquals("test", props.getCacheControl()); - assertEquals("UTF-8", props.getContentEncoding()); - assertEquals("en-us", props.getContentLanguage()); - assertEquals("text/plain", props.getContentType()); - assertEquals(4096, props.getContentLength()); - assertNotNull(props.getEtag()); - assertNull(props.getContentMD5()); - assertNotNull(props.getLastModified()); - assertEquals("PageBlob", props.getBlobType()); - assertEquals("unlocked", props.getLeaseStatus()); - assertEquals(0, props.getSequenceNumber()); - assertEquals(4096, inputStreamToByteArray(result.getContentStream()).length); - } - - @Test - public void getBlobWithIfMatchETagAccessConditionWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 4096); - try { - service.getBlob(TEST_CONTAINER_FOR_BLOBS, "test", - new GetBlobOptions().setAccessCondition(AccessCondition.ifMatch("123"))); - Assert.fail("getBlob should throw an exception"); - } - catch (ServiceException e) { - } - - // Assert - } - - @Test - public void getBlobWithIfNoneMatchETagAccessConditionWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 4096); - GetBlobPropertiesResult props = service.getBlobProperties(TEST_CONTAINER_FOR_BLOBS, "test"); - try { - service.getBlob(TEST_CONTAINER_FOR_BLOBS, "test", new GetBlobOptions().setAccessCondition(AccessCondition - .ifNoneMatch(props.getProperties().getEtag()))); - Assert.fail("getBlob should throw an exception"); - } - catch (ServiceException e) { - } - - // Assert - } - - @Test - public void getBlobWithIfModifiedSinceAccessConditionWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 4096); - GetBlobPropertiesResult props = service.getBlobProperties(TEST_CONTAINER_FOR_BLOBS, "test"); - try { - service.getBlob(TEST_CONTAINER_FOR_BLOBS, "test", new GetBlobOptions().setAccessCondition(AccessCondition - .ifModifiedSince(props.getProperties().getLastModified()))); - Assert.fail("getBlob should throw an exception"); - } - catch (ServiceException e) { - } - - // Assert - } - - @Test - public void getBlobWithIfNotModifiedSinceAccessConditionWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - service.createPageBlob(container, blob, 4096); - GetBlobPropertiesResult props = service.getBlobProperties(container, blob); - - // To test for "IfNotModifiedSince", we need to make updates to the blob - // until at least 1 second has passed since the blob creation - Date lastModifiedBase = (Date) props.getProperties().getLastModified().clone(); - - // +1 second - Date lastModifiedNext = new Date(lastModifiedBase.getTime() + 1000); - - while (true) { - HashMap metadata = new HashMap(); - metadata.put("test", "test1"); - SetBlobMetadataResult result = service.setBlobMetadata(container, blob, metadata); - if (result.getLastModified().compareTo(lastModifiedNext) >= 0) - break; - } - try { - service.getBlob(container, blob, - new GetBlobOptions().setAccessCondition(AccessCondition.ifNotModifiedSince(lastModifiedBase))); - Assert.fail("getBlob should throw an exception"); - } - catch (ServiceException e) { - } - - // Assert - } - - @Test - public void getBlobWithMD5Range() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String expectedMd5 = "+zxkkqBt6HehE3r5suhS1w=="; - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - service.createPageBlob(container, blob, 4096); - - GetBlobOptions options = new GetBlobOptions(); - options = options.setRangeStart(50L); - options = options.setRangeEnd(200L); - options = options.setComputeRangeMD5(true); - GetBlobResult getBlobResult = service.getBlob(container, blob, options); - - // Assert - assertNotNull(getBlobResult); - BlobProperties blobProperties = getBlobResult.getProperties(); - String actualMd5 = blobProperties.getContentMD5(); - assertEquals(expectedMd5, actualMd5); - - } - - @Test - public void getBlobPropertiesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - service.createPageBlob(container, blob, 4096); - GetBlobPropertiesResult result = service.getBlobProperties(container, blob); - - // Assert - assertNotNull(result); - - assertNotNull(result.getMetadata()); - assertEquals(0, result.getMetadata().size()); - - BlobProperties props = result.getProperties(); - assertNotNull(props); - assertNull(props.getCacheControl()); - assertNull(props.getContentEncoding()); - assertNull(props.getContentLanguage()); - assertEquals("application/octet-stream", props.getContentType()); - assertEquals(4096, props.getContentLength()); - assertNotNull(props.getEtag()); - assertNull(props.getContentMD5()); - assertNotNull(props.getLastModified()); - assertEquals("PageBlob", props.getBlobType()); - assertEquals("unlocked", props.getLeaseStatus()); - assertEquals(0, props.getSequenceNumber()); - } - - @Test(expected = ServiceException.class) - public void getBlobPropertiesIfNotModified() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - CreateBlobResult result = service.createPageBlob(container, blob, 4096); - Date tenSecondsFromNow = new Date(result.getLastModified().getTime() + 10000); - service.getBlobProperties(container, blob, - new GetBlobPropertiesOptions().setAccessCondition(AccessCondition.ifModifiedSince(tenSecondsFromNow))); - - // Assert - assertTrue(false); - } - - @Test - public void getBlobMetadataWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test"; - service.createPageBlob(container, blob, 4096, - new CreateBlobOptions().addMetadata("test", "bar").addMetadata("blah", "bleah")); - GetBlobMetadataResult props = service.getBlobMetadata(container, blob); - - // Assert - assertNotNull(props); - assertNotNull(props.getEtag()); - assertNotNull(props.getMetadata()); - assertEquals(2, props.getMetadata().size()); - assertTrue(props.getMetadata().containsKey("test")); - assertTrue(props.getMetadata().containsValue("bar")); - assertTrue(props.getMetadata().containsKey("blah")); - assertTrue(props.getMetadata().containsValue("bleah")); - assertNotNull(props.getLastModified()); - } - - @Test - public void setBlobPropertiesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test10"; - service.createPageBlob(container, blob, 4096); - SetBlobPropertiesResult result = service.setBlobProperties(container, blob, new SetBlobPropertiesOptions() - .setCacheControl("test").setContentEncoding("UTF-8").setContentLanguage("en-us").setContentLength(512L) - .setContentMD5(null).setContentType("text/plain").setSequenceNumberAction("increment")); - - GetBlobPropertiesResult getResult = service.getBlobProperties(container, blob); - - // Assert - assertNotNull(result); - assertNotNull(result.getEtag()); - assertNotNull(result.getLastModified()); - assertNotNull(result.getSequenceNumber()); - assertEquals(1, result.getSequenceNumber().longValue()); - - assertNotNull(getResult); - - assertNotNull(getResult.getMetadata()); - assertEquals(0, getResult.getMetadata().size()); - - BlobProperties props = getResult.getProperties(); - assertNotNull(props); - assertEquals("test", props.getCacheControl()); - assertEquals("UTF-8", props.getContentEncoding()); - assertEquals("en-us", props.getContentLanguage()); - assertEquals("text/plain", props.getContentType()); - assertEquals(512, props.getContentLength()); - assertNull(props.getContentMD5()); - assertNotNull(props.getLastModified()); - assertEquals("PageBlob", props.getBlobType()); - assertEquals("unlocked", props.getLeaseStatus()); - assertEquals(1, props.getSequenceNumber()); - } - - @Test - public void setBlobMetadataWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String container = TEST_CONTAINER_FOR_BLOBS; - String blob = "test11"; - HashMap metadata = new HashMap(); - metadata.put("test", "bar"); - metadata.put("blah", "bleah"); - - service.createPageBlob(container, blob, 4096); - SetBlobMetadataResult result = service.setBlobMetadata(container, blob, metadata); - GetBlobPropertiesResult props = service.getBlobProperties(container, blob); - - // Assert - assertNotNull(result); - assertNotNull(result.getEtag()); - assertNotNull(result.getLastModified()); - - assertNotNull(props); - assertNotNull(props.getMetadata()); - assertEquals(2, props.getMetadata().size()); - assertTrue(props.getMetadata().containsKey("test")); - assertTrue(props.getMetadata().containsValue("bar")); - assertTrue(props.getMetadata().containsKey("blah")); - assertTrue(props.getMetadata().containsValue("bleah")); - } - - @Test - public void deleteBlobWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String content = "some content"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test2", new ByteArrayInputStream(content.getBytes("UTF-8"))); - - service.deleteBlob(TEST_CONTAINER_FOR_BLOBS, "test2"); - - // Assert - } - - @Test - public void deleteBlobSnapshotSuccess() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String blobName = "deleteBlobSnapshotSuccess"; - // Act - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, blobName, 512); - CreateBlobSnapshotResult createBlobSnapshotResult = service.createBlobSnapshot(TEST_CONTAINER_FOR_BLOBS, - blobName); - DeleteBlobOptions deleteBlobOptions = new DeleteBlobOptions(); - String snapshot = createBlobSnapshotResult.getSnapshot(); - deleteBlobOptions.setSnapshot(snapshot); - service.deleteBlob(TEST_CONTAINER_FOR_BLOBS, blobName, deleteBlobOptions); - - // Assert - ListBlobsResult listBlobsResult = service.listBlobs(TEST_CONTAINER_FOR_BLOBS); - List blobEntry = listBlobsResult.getBlobs(); - for (BlobEntry blobEntryItem : blobEntry) { - assertTrue(blobEntryItem.getSnapshot() == null || !blobEntryItem.getSnapshot().equals(snapshot)); - } - assertTrue(true); - } - - @Test - public void copyBlobWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String content = "some content2"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test6", new ByteArrayInputStream(content.getBytes("UTF-8"))); - service.copyBlob(TEST_CONTAINER_FOR_BLOBS_2, "test5", TEST_CONTAINER_FOR_BLOBS, "test6"); - - GetBlobResult result = service.getBlob(TEST_CONTAINER_FOR_BLOBS_2, "test5"); - - // Assert - assertNotNull(result); - - assertNotNull(result.getMetadata()); - assertEquals(0, result.getMetadata().size()); - - BlobProperties props = result.getProperties(); - assertNotNull(props); - assertEquals(content.length(), props.getContentLength()); - assertNotNull(props.getEtag()); - assertNull(props.getContentMD5()); - assertNotNull(props.getLastModified()); - assertEquals("BlockBlob", props.getBlobType()); - assertEquals("unlocked", props.getLeaseStatus()); - assertEquals(0, props.getSequenceNumber()); - assertEquals(content, inputStreamToString(result.getContentStream(), "UTF-8")); - } - - @Test - public void copyBlobGetEtagSuccess() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - String sourceBlobName = "copyblobgetetagsuccesssource"; - String targetBlobName = "copyblobgetetagsuccesstarget"; - - //Act - String content = "some content2"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, sourceBlobName, - new ByteArrayInputStream(content.getBytes("UTF-8"))); - CopyBlobResult copyBlobResult = service.copyBlob(TEST_CONTAINER_FOR_BLOBS_2, targetBlobName, - TEST_CONTAINER_FOR_BLOBS, sourceBlobName); - - GetBlobResult result = service.getBlob(TEST_CONTAINER_FOR_BLOBS_2, targetBlobName); - - // Assert - assertNotNull(result); - assertEquals(copyBlobResult.getEtag(), result.getProperties().getEtag()); - - } - - @Test - public void acquireLeaseWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String content = "some content2"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test6", new ByteArrayInputStream(content.getBytes("UTF-8"))); - String leaseId = service.acquireLease(TEST_CONTAINER_FOR_BLOBS, "test6").getLeaseId(); - service.releaseLease(TEST_CONTAINER_FOR_BLOBS, "test6", leaseId); - - // Assert - assertNotNull(leaseId); - } - - @Test - public void renewLeaseWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String content = "some content2"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test6", new ByteArrayInputStream(content.getBytes("UTF-8"))); - String leaseId = service.acquireLease(TEST_CONTAINER_FOR_BLOBS, "test6").getLeaseId(); - String leaseId2 = service.renewLease(TEST_CONTAINER_FOR_BLOBS, "test6", leaseId).getLeaseId(); - service.releaseLease(TEST_CONTAINER_FOR_BLOBS, "test6", leaseId); - - // Assert - assertNotNull(leaseId); - assertNotNull(leaseId2); - } - - @Test - public void breakLeaseWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - String content = "some content2"; - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "test6", new ByteArrayInputStream(content.getBytes("UTF-8"))); - String leaseId = service.acquireLease(TEST_CONTAINER_FOR_BLOBS, "test6").getLeaseId(); - BreakLeaseResult breakResult = service.breakLease(TEST_CONTAINER_FOR_BLOBS, "test6"); - service.releaseLease(TEST_CONTAINER_FOR_BLOBS, "test6", leaseId); - - // Assert - assertNotNull(leaseId); - assertNotNull(breakResult); - assertTrue(breakResult.getRemainingLeaseTimeInSeconds() > 0); - } - - class RetryPolicyObserver implements ServiceFilter { - public int requestCount; - - @Override - public Response handle(Request request, Next next) throws Exception { - requestCount++; - return next.handle(request); - } - } - - @Test - public void retryPolicyWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - RetryPolicyObserver observer = new RetryPolicyObserver(); - service = service.withFilter(observer); - - // Act - service = service.withFilter(new RetryPolicyFilter(new ExponentialRetryPolicy(100/*deltaBackoff*/, - 3/*maximumAttempts*/, new int[] { 400, 500, 503 }))); - - ServiceException Error = null; - try { - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 12); - } - catch (ServiceException e) { - Error = e; - } - - // Assert - assertNotNull(Error); - assertEquals(400, Error.getHttpStatusCode()); - assertEquals(4, observer.requestCount); - } - - @Test - public void retryPolicyCompositionWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - RetryPolicyObserver observer = new RetryPolicyObserver(); - service = service.withFilter(observer); - - // Act - service = service.withFilter(new RetryPolicyFilter(new ExponentialRetryPolicy(100/*deltaBackoff*/, - 3/*maximumAttempts*/, new int[] { 400, 500, 503 }))); - service = service.withFilter(new RetryPolicyFilter(new ExponentialRetryPolicy(100/*deltaBackoff*/, - 2/*maximumAttempts*/, new int[] { 400, 500, 503 }))); - - ServiceException Error = null; - try { - service.createPageBlob(TEST_CONTAINER_FOR_BLOBS, "test", 12); - } - catch (ServiceException e) { - Error = e; - } - - // Assert - assertNotNull(Error); - assertEquals(400, Error.getHttpStatusCode()); - assertEquals(3, observer.requestCount); - } - - private class NonResetableInputStream extends FilterInputStream { - - protected NonResetableInputStream(InputStream in) { - super(in); - } - - @Override - public boolean markSupported() { - return false; - } - } - - @Test - public void retryPolicyThrowsOnInvalidInputStream() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service = service.withFilter(new RetryPolicyFilter(new ExponentialRetryPolicy(100/*deltaBackoff*/, - 3/*maximumAttempts*/, new int[] { 400, 500, 503 }))); - - Exception error = null; - try { - String content = "foo"; - InputStream contentStream = new ByteArrayInputStream(content.getBytes("UTF-8")); - InputStream stream = new NonResetableInputStream(contentStream); - - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "testretry", stream); - } - catch (Exception e) { - error = e; - } - - // Assert - assertNotNull(error); - } - - private class ResetableInputStream extends FilterInputStream { - private boolean resetCalled; - - protected ResetableInputStream(InputStream in) { - super(in); - } - - @Override - public void reset() throws IOException { - super.reset(); - setResetCalled(true); - } - - public boolean isResetCalled() { - return resetCalled; - } - - public void setResetCalled(boolean resetCalled) { - this.resetCalled = resetCalled; - } - } - - @Test - public void retryPolicyCallsResetOnValidInputStream() throws Exception { - // Arrange - Configuration config = createConfiguration(); - BlobContract service = BlobService.create(config); - - // Act - service = service.withFilter(new RetryPolicyFilter(new ExponentialRetryPolicy(100/*deltaBackoff*/, - 3/*maximumAttempts*/, new int[] { 403 }))); - - ServiceException error = null; - ResetableInputStream stream = null; - try { - String content = "foo"; - InputStream contentStream = new ByteArrayInputStream(content.getBytes("UTF-8")); - stream = new ResetableInputStream(contentStream); - - service.createBlockBlob(TEST_CONTAINER_FOR_BLOBS, "invalidblobname @#$#@$@", stream); - } - catch (ServiceException e) { - error = e; - } - - // Assert - assertNotNull(error); - assertEquals(403, error.getHttpStatusCode()); - assertNotNull(stream); - assertTrue(stream.isResetCalled()); - } - - private byte[] inputStreamToByteArray(InputStream inputStream) throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - - byte[] buffer = new byte[1024]; - try { - while (true) { - int n = inputStream.read(buffer); - if (n == -1) - break; - outputStream.write(buffer, 0, n); - } - } - finally { - inputStream.close(); - } - return outputStream.toByteArray(); - } - - private String inputStreamToString(InputStream inputStream, String encoding) throws IOException { - Writer writer = new StringWriter(); - - char[] buffer = new char[1024]; - try { - Reader reader = new BufferedReader(new InputStreamReader(inputStream, encoding)); - while (true) { - int n = reader.read(buffer); - if (n == -1) - break; - writer.write(buffer, 0, n); - } - } - finally { - inputStream.close(); - } - return writer.toString(); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/IntegrationTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/IntegrationTestBase.java deleted file mode 100644 index fc7b2c07ac808..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/IntegrationTestBase.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob; - -import com.microsoft.windowsazure.services.core.Configuration; - -public abstract class IntegrationTestBase { - protected static Configuration createConfiguration() { - Configuration config = Configuration.getInstance(); - overrideWithEnv(config, BlobConfiguration.ACCOUNT_NAME); - overrideWithEnv(config, BlobConfiguration.ACCOUNT_KEY); - overrideWithEnv(config, BlobConfiguration.URI); - return config; - } - - private static void overrideWithEnv(Configuration config, String key) { - String value = System.getenv(key); - if (value == null) - return; - - config.setProperty(key, value); - } - - protected static boolean isRunningWithEmulator(Configuration config) { - String accountName = "devstoreaccount1"; - String accountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; - - return accountName.equals(config.getProperty(BlobConfiguration.ACCOUNT_NAME)) - && accountKey.equals(config.getProperty(BlobConfiguration.ACCOUNT_KEY)); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/client/BlobTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/client/BlobTestBase.java deleted file mode 100644 index 1b69119c1e48b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/client/BlobTestBase.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; - -import com.microsoft.windowsazure.services.core.storage.AuthenticationScheme; -import com.microsoft.windowsazure.services.core.storage.CloudStorageAccount; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Blob Test Base - * Blob test refactoring will be done in future. - */ -public class BlobTestBase { - public static boolean USE_DEV_FABRIC = false; - public static final String CLOUD_ACCOUNT_HTTP = "DefaultEndpointsProtocol=http;AccountName=[ACCOUNT NAME];AccountKey=[ACCOUNT KEY]"; - public static final String CLOUD_ACCOUNT_HTTPS = "DefaultEndpointsProtocol=https;AccountName=[ACCOUNT NAME];AccountKey=[ACCOUNT KEY]"; - - protected static CloudStorageAccount httpAcc; - protected static CloudBlobClient bClient; - protected static String testSuiteContainerName = generateRandomContainerName(); - protected static byte[] testData = new byte[] { 1, 2, 3, 4 }; - - @BeforeClass - public static void setup() throws URISyntaxException, StorageException, InvalidKeyException { - if (USE_DEV_FABRIC) { - httpAcc = CloudStorageAccount.getDevelopmentStorageAccount(); - } - else { - String cloudAccount = CLOUD_ACCOUNT_HTTP; - cloudAccount = cloudAccount.replace("[ACCOUNT NAME]", System.getenv("blob.accountName")); - cloudAccount = cloudAccount.replace("[ACCOUNT KEY]", System.getenv("blob.accountKey")); - - httpAcc = CloudStorageAccount.parse(cloudAccount); - } - - bClient = httpAcc.createCloudBlobClient(); - bClient.setAuthenticationScheme(AuthenticationScheme.SHAREDKEYFULL); - testSuiteContainerName = generateRandomContainerName(); - CloudBlobContainer container = bClient.getContainerReference(testSuiteContainerName); - container.create(); - } - - @AfterClass - public static void teardown() throws StorageException, URISyntaxException { - CloudBlobContainer container = bClient.getContainerReference(testSuiteContainerName); - container.delete(); - } - - protected static String generateRandomContainerName() { - String containerName = "container" + UUID.randomUUID().toString(); - return containerName.replace("-", ""); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/client/CloudBlobContainerTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/client/CloudBlobContainerTests.java deleted file mode 100644 index 227ce6b97c188..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/blob/client/CloudBlobContainerTests.java +++ /dev/null @@ -1,880 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.blob.client; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.EnumSet; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Random; -import java.util.TimeZone; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.AccessCondition; -import com.microsoft.windowsazure.services.core.storage.AuthenticationScheme; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.RetryNoRetry; -import com.microsoft.windowsazure.services.core.storage.SendingRequestEvent; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageEvent; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Table Client Tests - */ -public class CloudBlobContainerTests extends BlobTestBase { - /** - * test SharedAccess of container. - * - * @XSCLCaseName ContainerInfoSharedAccess - */ - @Test - public void testContainerSaS() throws InvalidKeyException, IllegalArgumentException, StorageException, - URISyntaxException, IOException { - - String name = generateRandomContainerName(); - CloudBlobContainer container = bClient.getContainerReference(name); - container.create(); - - CloudBlockBlob blob = container.getBlockBlobReference("test"); - blob.upload(new ByteArrayInputStream(new byte[100]), 100); - - SharedAccessBlobPolicy sp1 = createSharedAccessPolicy( - EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.WRITE, - SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.DELETE), 300); - SharedAccessBlobPolicy sp2 = createSharedAccessPolicy( - EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 300); - BlobContainerPermissions perms = new BlobContainerPermissions(); - - perms.getSharedAccessPolicies().put("full", sp1); - perms.getSharedAccessPolicies().put("readlist", sp2); - container.uploadPermissions(perms); - - String containerReadListSas = container.generateSharedAccessSignature(sp2, null); - CloudBlobContainer readListContainer = bClient.getContainerReference(container.getUri().toString() + "?" - + containerReadListSas); - Assert.assertEquals(StorageCredentialsSharedAccessSignature.class.toString(), readListContainer - .getServiceClient().getCredentials().getClass().toString()); - - CloudBlockBlob blobFromSasContainer = readListContainer.getBlockBlobReference("test"); - blobFromSasContainer.download(new ByteArrayOutputStream()); - container.deleteIfExists(); - } - - @Test - public void testBlobSaS() throws InvalidKeyException, IllegalArgumentException, StorageException, - URISyntaxException, IOException { - - String name = generateRandomContainerName(); - CloudBlobContainer container = bClient.getContainerReference(name); - container.create(); - - CloudBlockBlob blob = container.getBlockBlobReference("test"); - blob.upload(new ByteArrayInputStream(new byte[100]), 100); - - SharedAccessBlobPolicy sp = createSharedAccessPolicy( - EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 300); - BlobContainerPermissions perms = new BlobContainerPermissions(); - - perms.getSharedAccessPolicies().put("readperm", sp); - container.uploadPermissions(perms); - - CloudBlockBlob sasBlob = new CloudBlockBlob(new URI(blob.getUri().toString() + "?" - + blob.generateSharedAccessSignature(null, "readperm"))); - sasBlob.download(new ByteArrayOutputStream()); - container.deleteIfExists(); - } - - public final static SharedAccessBlobPolicy createSharedAccessPolicy(EnumSet sap, - int expireTimeInSeconds) { - - Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); - cal.setTime(new Date()); - cal.add(Calendar.SECOND, expireTimeInSeconds); - SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy(); - policy.setPermissions(sap); - policy.setSharedAccessExpiryTime(cal.getTime()); - return policy; - - } - - @Test - public void testContainerGetSetPermission() throws StorageException, URISyntaxException { - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - - BlobContainerPermissions expectedPermissions; - BlobContainerPermissions testPermissions; - - try { - // Test new permissions. - expectedPermissions = new BlobContainerPermissions(); - testPermissions = newContainer.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - - // Test setting empty permissions. - newContainer.uploadPermissions(expectedPermissions); - testPermissions = newContainer.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - - // Add a policy, check setting and getting. - SharedAccessBlobPolicy policy1 = new SharedAccessBlobPolicy(); - Calendar now = GregorianCalendar.getInstance(); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 10); - policy1.setSharedAccessExpiryTime(now.getTime()); - - policy1.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.DELETE, - SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.DELETE)); - expectedPermissions.getSharedAccessPolicies().put(UUID.randomUUID().toString(), policy1); - - newContainer.uploadPermissions(expectedPermissions); - testPermissions = newContainer.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - static void assertTablePermissionsEqual(BlobContainerPermissions expected, BlobContainerPermissions actual) { - HashMap expectedPolicies = expected.getSharedAccessPolicies(); - HashMap actualPolicies = actual.getSharedAccessPolicies(); - Assert.assertEquals("SharedAccessPolicies.Count", expectedPolicies.size(), actualPolicies.size()); - for (String name : expectedPolicies.keySet()) { - Assert.assertTrue("Key" + name + " doesn't exist", actualPolicies.containsKey(name)); - SharedAccessBlobPolicy expectedPolicy = expectedPolicies.get(name); - SharedAccessBlobPolicy actualPolicy = actualPolicies.get(name); - Assert.assertEquals("Policy: " + name + "\tPermissions\n", expectedPolicy.getPermissions().toString(), - actualPolicy.getPermissions().toString()); - Assert.assertEquals("Policy: " + name + "\tStartDate\n", expectedPolicy.getSharedAccessStartTime() - .toString(), actualPolicy.getSharedAccessStartTime().toString()); - Assert.assertEquals("Policy: " + name + "\tExpireDate\n", expectedPolicy.getSharedAccessExpiryTime() - .toString(), actualPolicy.getSharedAccessExpiryTime().toString()); - - } - - } - - @Test - public void testContainerAcquireLease() throws StorageException, URISyntaxException, InterruptedException { - String name = "leased" + generateRandomContainerName(); - CloudBlobContainer leaseContainer1 = bClient.getContainerReference(name); - leaseContainer1.create(); - String proposedLeaseId1 = UUID.randomUUID().toString(); - - name = "leased" + generateRandomContainerName(); - CloudBlobContainer leaseContainer2 = bClient.getContainerReference(name); - leaseContainer2.create(); - String proposedLeaseId2 = UUID.randomUUID().toString(); - - try { - // 15 sec - - OperationContext operationContext1 = new OperationContext(); - leaseContainer1.acquireLease(15, proposedLeaseId1, null /*access condition*/, - null/* BlobRequestOptions */, operationContext1); - Assert.assertTrue(operationContext1.getLastResult().getStatusCode() == HttpURLConnection.HTTP_CREATED); - - //infinite - String leaseId1; - String leaseId2; - OperationContext operationContext2 = new OperationContext(); - leaseId1 = leaseContainer2.acquireLease(null /* infinite lease */, proposedLeaseId2, - null /*access condition*/, null/* BlobRequestOptions */, operationContext2); - Assert.assertTrue(operationContext2.getLastResult().getStatusCode() == HttpURLConnection.HTTP_CREATED); - - leaseId2 = leaseContainer2.acquireLease(null /* infinite lease */, proposedLeaseId2); - Assert.assertEquals(leaseId1, leaseId2); - - } - finally { - // cleanup - AccessCondition condition = new AccessCondition(); - condition.setLeaseID(proposedLeaseId1); - leaseContainer1.releaseLease(condition); - leaseContainer1.deleteIfExists(); - - condition = new AccessCondition(); - condition.setLeaseID(proposedLeaseId2); - leaseContainer2.releaseLease(condition); - leaseContainer2.deleteIfExists(); - } - } - - @Test - public void testContainerReleaseLease() throws StorageException, URISyntaxException, InterruptedException { - String name = "leased" + generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - - try { - // 15 sec - String proposedLeaseId = UUID.randomUUID().toString(); - String leaseId = newContainer.acquireLease(15, proposedLeaseId); - AccessCondition condition = new AccessCondition(); - condition.setLeaseID(leaseId); - OperationContext operationContext1 = new OperationContext(); - newContainer.releaseLease(condition, null/* BlobRequestOptions */, operationContext1); - Assert.assertTrue(operationContext1.getLastResult().getStatusCode() == HttpURLConnection.HTTP_OK); - - //infinite - proposedLeaseId = UUID.randomUUID().toString(); - leaseId = newContainer.acquireLease(null /* infinite lease */, proposedLeaseId); - condition = new AccessCondition(); - condition.setLeaseID(leaseId); - OperationContext operationContext2 = new OperationContext(); - newContainer.releaseLease(condition, null/* BlobRequestOptions */, operationContext2); - Assert.assertTrue(operationContext2.getLastResult().getStatusCode() == HttpURLConnection.HTTP_OK); - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - @Test - public void testContainerBreakLease() throws StorageException, URISyntaxException, InterruptedException { - String name = "leased" + generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - String proposedLeaseId = UUID.randomUUID().toString(); - - try { - // 5 sec - String leaseId = newContainer.acquireLease(15, proposedLeaseId); - AccessCondition condition = new AccessCondition(); - condition.setLeaseID(leaseId); - OperationContext operationContext1 = new OperationContext(); - newContainer.breakLease(0, condition, null/* BlobRequestOptions */, operationContext1); - Assert.assertTrue(operationContext1.getLastResult().getStatusCode() == HttpURLConnection.HTTP_ACCEPTED); - Thread.sleep(15 * 1000); - - //infinite - proposedLeaseId = UUID.randomUUID().toString(); - leaseId = newContainer.acquireLease(null /* infinite lease */, proposedLeaseId); - condition = new AccessCondition(); - condition.setLeaseID(leaseId); - OperationContext operationContext2 = new OperationContext(); - newContainer.breakLease(0, condition, null/* BlobRequestOptions */, operationContext2); - Assert.assertTrue(operationContext2.getLastResult().getStatusCode() == HttpURLConnection.HTTP_ACCEPTED); - } - finally { - // cleanup - AccessCondition condition = new AccessCondition(); - condition.setLeaseID(proposedLeaseId); - newContainer.releaseLease(condition); - newContainer.deleteIfExists(); - } - } - - @Test - public void testContainerRenewLeaseTest() throws StorageException, URISyntaxException, InterruptedException { - String name = "leased" + generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - String proposedLeaseId = UUID.randomUUID().toString(); - - try { - // 5 sec - String leaseId = newContainer.acquireLease(15, proposedLeaseId); - AccessCondition condition = new AccessCondition(); - condition.setLeaseID(leaseId); - OperationContext operationContext1 = new OperationContext(); - newContainer.renewLease(condition, null/* BlobRequestOptions */, operationContext1); - Assert.assertTrue(operationContext1.getLastResult().getStatusCode() == HttpURLConnection.HTTP_OK); - newContainer.releaseLease(condition); - - //infinite - proposedLeaseId = UUID.randomUUID().toString(); - leaseId = newContainer.acquireLease(null /* infinite lease */, proposedLeaseId); - condition = new AccessCondition(); - condition.setLeaseID(leaseId); - OperationContext operationContext2 = new OperationContext(); - newContainer.renewLease(condition, null/* BlobRequestOptions */, operationContext2); - Assert.assertTrue(operationContext2.getLastResult().getStatusCode() == HttpURLConnection.HTTP_OK); - } - finally { - // cleanup - AccessCondition condition = new AccessCondition(); - condition.setLeaseID(proposedLeaseId); - newContainer.releaseLease(condition); - newContainer.deleteIfExists(); - } - } - - @Test - public void testBlobLeaseAcquireAndRelease() throws URISyntaxException, StorageException, IOException { - final int length = 128; - final Random randGenerator = new Random(); - final byte[] buff = new byte[length]; - randGenerator.nextBytes(buff); - - String blobName = "testBlob" + Integer.toString(randGenerator.nextInt(50000)); - blobName = blobName.replace('-', '_'); - - final CloudBlobContainer leasedContainer = bClient.getContainerReference(testSuiteContainerName); - final CloudBlob blobRef = leasedContainer.getBlockBlobReference(blobName); - final BlobRequestOptions options = new BlobRequestOptions(); - - blobRef.upload(new ByteArrayInputStream(buff), -1, null, options, null); - - // Get Lease - OperationContext operationContext = new OperationContext(); - final String leaseID = blobRef.acquireLease(15, null /*access condition*/, null /*proposed lease id */, - null/* BlobRequestOptions */, operationContext); - final AccessCondition leaseCondition = AccessCondition.generateLeaseCondition(leaseID); - Assert.assertTrue(operationContext.getLastResult().getStatusCode() == HttpURLConnection.HTTP_CREATED); - - // Try to upload without lease - try { - blobRef.upload(new ByteArrayInputStream(buff), -1, null, options, null); - } - catch (final StorageException ex) { - Assert.assertEquals(ex.getHttpStatusCode(), 412); - Assert.assertEquals(ex.getErrorCode(), StorageErrorCodeStrings.LEASE_ID_MISSING); - } - - // Try to upload with lease - blobRef.upload(new ByteArrayInputStream(buff), -1, leaseCondition, options, null); - - // Release lease - blobRef.releaseLease(leaseCondition); - - // now upload with no lease specified. - blobRef.upload(new ByteArrayInputStream(buff), -1, null, options, null); - } - - @Test - public void testBlobLeaseBreak() throws URISyntaxException, StorageException, IOException, InterruptedException { - final int length = 128; - final Random randGenerator = new Random(); - final byte[] buff = new byte[length]; - randGenerator.nextBytes(buff); - - String blobName = "testBlob" + Integer.toString(randGenerator.nextInt(50000)); - blobName = blobName.replace('-', '_'); - - final CloudBlobContainer existingContainer = bClient.getContainerReference(testSuiteContainerName); - final CloudBlob blobRef = existingContainer.getBlockBlobReference(blobName); - final BlobRequestOptions options = new BlobRequestOptions(); - - blobRef.upload(new ByteArrayInputStream(buff), -1, null, options, null); - - // Get Lease - String leaseID = blobRef.acquireLease(null, null); - - OperationContext operationContext = new OperationContext(); - final AccessCondition leaseCondition = AccessCondition.generateLeaseCondition(leaseID); - blobRef.breakLease(0, leaseCondition, null/* BlobRequestOptions */, operationContext); - Assert.assertTrue(operationContext.getLastResult().getStatusCode() == HttpURLConnection.HTTP_ACCEPTED); - } - - @Test - public void testListBlobs() throws URISyntaxException, StorageException, IOException, InterruptedException { - final int length = 128; - final Random randGenerator = new Random(); - final byte[] buff = new byte[length]; - randGenerator.nextBytes(buff); - - String blobName = "testBlob" + Integer.toString(randGenerator.nextInt(50000)); - blobName = blobName.replace('-', '_'); - - final CloudBlobContainer existingContainer = bClient.getContainerReference(testSuiteContainerName); - final CloudBlob blobRef = existingContainer.getBlockBlobReference(blobName); - final BlobRequestOptions options = new BlobRequestOptions(); - OperationContext context = new OperationContext(); - context.setClientRequestID("My-Helpful-TraceId"); - - // Subscribe to sending request event once we move that. Currently, the sendingrequest event is fired - // after the connection is initiated and we don't have access to the request headers at that time. - - blobRef.upload(new ByteArrayInputStream(buff), -1, null, options, context); - - for (ListBlobItem blob : existingContainer.listBlobs()) { - Assert.assertEquals(blobRef.getClass(), blob.getClass()); - } - } - - @Test - public void testBlobLeaseRenew() throws URISyntaxException, StorageException, IOException, InterruptedException { - final int length = 128; - final Random randGenerator = new Random(); - final byte[] buff = new byte[length]; - randGenerator.nextBytes(buff); - - String blobName = "testBlob" + Integer.toString(randGenerator.nextInt(50000)); - blobName = blobName.replace('-', '_'); - - final CloudBlobContainer existingContainer = bClient.getContainerReference(testSuiteContainerName); - final CloudBlob blobRef = existingContainer.getBlockBlobReference(blobName); - final BlobRequestOptions options = new BlobRequestOptions(); - - blobRef.upload(new ByteArrayInputStream(buff), -1, null, options, null); - - // Get Lease - final String leaseID = blobRef.acquireLease(15, null); - Thread.sleep(1000); - - AccessCondition leaseCondition = AccessCondition.generateLeaseCondition(leaseID); - OperationContext operationContext = new OperationContext(); - blobRef.renewLease(leaseCondition, null/* BlobRequestOptions */, operationContext); - Assert.assertTrue(operationContext.getLastResult().getStatusCode() == HttpURLConnection.HTTP_OK); - } - - static String setLeasedState(CloudBlobContainer container, int leaseTime) throws StorageException { - String leaseId = UUID.randomUUID().toString(); - setUnleasedState(container); - return container.acquireLease(leaseTime, leaseId); - } - - static void setUnleasedState(CloudBlobContainer container) throws StorageException { - if (!container.createIfNotExist()) { - try { - container.breakLease(0); - } - catch (StorageException e) { - if (e.getHttpStatusCode() != HttpURLConnection.HTTP_BAD_REQUEST) { - throw e; - } - } - } - } - - @Test - public void testCopyFromBlob() throws StorageException, URISyntaxException, IOException, InterruptedException { - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - CloudBlob originalBlob = newContainer.getBlockBlobReference("newblob"); - originalBlob.upload(new ByteArrayInputStream(testData), testData.length); - - try { - CloudBlob copyBlob = newContainer.getBlockBlobReference(originalBlob.getName() + "copyed"); - copyBlob.copyFromBlob(originalBlob); - Thread.sleep(1000); - copyBlob.downloadAttributes(); - Assert.assertNotNull(copyBlob.copyState); - Assert.assertNotNull(copyBlob.copyState.getCopyId()); - Assert.assertNotNull(copyBlob.copyState.getCompletionTime()); - Assert.assertNotNull(copyBlob.copyState.getSource()); - Assert.assertFalse(copyBlob.copyState.getBytesCopied() == 0); - Assert.assertFalse(copyBlob.copyState.getTotalBytes() == 0); - for (final ListBlobItem blob : newContainer.listBlobs()) { - CloudBlob blobFromList = ((CloudBlob) blob); - blobFromList.downloadAttributes(); - } - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - @Test - public void testCopyFromBlobAbortTest() throws StorageException, URISyntaxException, IOException, - InterruptedException { - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - CloudBlob originalBlob = newContainer.getBlockBlobReference("newblob"); - byte[] data = new byte[16 * 1024 * 1024]; - Random r = new Random(); - r.nextBytes(data); - originalBlob.upload(new ByteArrayInputStream(data), testData.length); - - try { - CloudBlob copyBlob = newContainer.getBlockBlobReference(originalBlob.getName() + "copyed"); - copyBlob.copyFromBlob(originalBlob); - - try { - copyBlob.abortCopy(copyBlob.copyState.getCopyId()); - } - catch (StorageException e) { - if (!e.getErrorCode().contains("NoPendingCopyOperation")) { - throw e; - } - } - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - @Test - public void testBlobSnapshotValidationTest() throws StorageException, URISyntaxException, IOException, - InterruptedException { - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - - try { - final int length = 1 * 1024; - final Random randGenerator = new Random(); - final byte[] buff = new byte[length]; - randGenerator.nextBytes(buff); - - String blockBlobName = "testBlockBlob" + Integer.toString(randGenerator.nextInt(50000)); - blockBlobName = blockBlobName.replace('-', '_'); - - final CloudBlob blockBlobRef = newContainer.getBlockBlobReference(blockBlobName); - blockBlobRef.upload(new ByteArrayInputStream(buff), -1, null, null, null); - - final CloudBlob blobSnapshot = blockBlobRef.createSnapshot(); - - final ByteArrayOutputStream outStream = new ByteArrayOutputStream(length); - - blobSnapshot.download(outStream); - final byte[] retrievedBuff = outStream.toByteArray(); - for (int m = 0; m < length; m++) { - Assert.assertEquals(buff[m], retrievedBuff[m]); - } - - // Read operation should work fine. - blobSnapshot.downloadAttributes(); - - // Expect an IllegalArgumentException from upload. - try { - blobSnapshot.upload(new ByteArrayInputStream(buff), -1); - Assert.fail("Expect an IllegalArgumentException from upload"); - } - catch (IllegalArgumentException e) { - Assert.assertEquals("Cannot perform this operation on a blob representing a snapshot.", e.getMessage()); - } - - // Expect an IllegalArgumentException from uploadMetadata. - try { - blobSnapshot.uploadMetadata(); - Assert.fail("Expect an IllegalArgumentException from uploadMetadata"); - } - catch (IllegalArgumentException e) { - Assert.assertEquals("Cannot perform this operation on a blob representing a snapshot.", e.getMessage()); - } - - // Expect an IllegalArgumentException from uploadProperties. - try { - blobSnapshot.uploadProperties(); - Assert.fail("Expect an IllegalArgumentException from uploadProperties"); - } - catch (IllegalArgumentException e) { - Assert.assertEquals("Cannot perform this operation on a blob representing a snapshot.", e.getMessage()); - } - - // Expect an IllegalArgumentException from createSnapshot. - try { - blobSnapshot.createSnapshot(); - Assert.fail("Expect an IllegalArgumentException from createSnapshot"); - } - catch (IllegalArgumentException e) { - Assert.assertEquals("Cannot perform this operation on a blob representing a snapshot.", e.getMessage()); - } - - blobSnapshot.delete(DeleteSnapshotsOption.NONE, null, null, null); - - blockBlobRef.downloadAttributes(); - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - @Test - public void testBlobDownloadRangeValidationTest() throws StorageException, URISyntaxException, IOException, - InterruptedException { - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - - try { - - final int blockLength = 1024 * 1024; - final int length = 3 * blockLength; - final Random randGenerator = new Random(); - final byte[] buff = new byte[length]; - randGenerator.nextBytes(buff); - - String blockBlobName = "testBlockBlob" + Integer.toString(randGenerator.nextInt(50000)); - blockBlobName = blockBlobName.replace('-', '_'); - - final CloudBlockBlob blockBlobRef = newContainer.getBlockBlobReference(blockBlobName); - blockBlobRef.upload(new ByteArrayInputStream(buff), -1, null, null, null); - ArrayList blockList = new ArrayList(); - for (int i = 1; i <= 3; i++) { - randGenerator.nextBytes(buff); - - String blockID = String.format("%08d", i); - blockBlobRef.uploadBlock(blockID, new ByteArrayInputStream(buff), blockLength, null, null, null); - blockList.add(new BlockEntry(blockID, BlockSearchMode.LATEST)); - } - - blockBlobRef.commitBlockList(blockList); - - //Download full blob - blockBlobRef.download(new ByteArrayOutputStream()); - Assert.assertEquals(length, blockBlobRef.getProperties().getLength()); - - //Download blob range. - byte[] downloadBuffer = new byte[100]; - blockBlobRef.downloadRange(0, 100, downloadBuffer, 0); - Assert.assertEquals(length, blockBlobRef.getProperties().getLength()); - - //Download block list. - blockBlobRef.downloadBlockList(); - Assert.assertEquals(length, blockBlobRef.getProperties().getLength()); - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - @Test - public void testBlobNamePlusEncodingTest() throws StorageException, URISyntaxException, IOException, - InterruptedException { - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - - try { - - final int length = 1 * 1024; - final Random randGenerator = new Random(); - final byte[] buff = new byte[length]; - randGenerator.nextBytes(buff); - - final CloudBlockBlob originalBlob = newContainer.getBlockBlobReference("a+b.txt"); - originalBlob.upload(new ByteArrayInputStream(buff), -1, null, null, null); - - CloudBlob copyBlob = newContainer.getBlockBlobReference(originalBlob.getName() + "copyed"); - copyBlob.copyFromBlob(originalBlob); - Thread.sleep(1000); - copyBlob.downloadAttributes(); - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - @Test - public void testListContainersTest() throws StorageException, URISyntaxException, IOException, InterruptedException { - final ResultSegment segment = bClient.listContainersSegmented(null, - ContainerListingDetails.ALL, 2, null, null, null); - - for (int i = 0; i < 5 && segment.getHasMoreResults(); i++) { - for (final CloudBlobContainer container : segment.getResults()) { - container.downloadAttributes(); - } - - bClient.listContainersSegmented(null, ContainerListingDetails.ALL, 2, segment.getContinuationToken(), null, - null); - } - } - - @Test - public void testSendingRequestEventBlob() throws StorageException, URISyntaxException, IOException, - InterruptedException { - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - - final ArrayList callList = new ArrayList(); - OperationContext sendingRequestEventContext = new OperationContext(); - sendingRequestEventContext.getSendingRequestEventHandler().addListener(new StorageEvent() { - - @Override - public void eventOccurred(SendingRequestEvent eventArg) { - Assert.assertEquals(eventArg.getRequestResult(), eventArg.getOpContext().getLastResult()); - callList.add(true); - } - }); - - try { - Assert.assertEquals(0, callList.size()); - - //Put blob - CloudBlob blob = newContainer.getBlockBlobReference("newblob"); - blob.upload(new ByteArrayInputStream(testData), testData.length, null, null, sendingRequestEventContext); - Assert.assertEquals(1, callList.size()); - - //Get blob - blob.download(new ByteArrayOutputStream(), null, null, sendingRequestEventContext); - Assert.assertEquals(2, callList.size()); - - //uploadMetadata - blob.uploadMetadata(null, null, sendingRequestEventContext); - Assert.assertEquals(3, callList.size()); - - //uploadMetadata - blob.downloadAttributes(null, null, sendingRequestEventContext); - Assert.assertEquals(4, callList.size()); - - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } - - @Test - public void testBlobInputStream() throws URISyntaxException, StorageException, IOException { - final int blobLength = 16 * 1024; - final Random randGenerator = new Random(); - String blobName = "testblob" + Integer.toString(randGenerator.nextInt(50000)); - blobName = blobName.replace('-', '_'); - - final CloudBlobContainer containerRef = bClient.getContainerReference(BlobTestBase.testSuiteContainerName); - - final CloudBlockBlob blobRef = containerRef.getBlockBlobReference(blobName); - - final byte[] buff = new byte[blobLength]; - randGenerator.nextBytes(buff); - buff[0] = -1; - buff[1] = -128; - final ByteArrayInputStream sourceStream = new ByteArrayInputStream(buff); - - final BlobRequestOptions options = new BlobRequestOptions(); - final OperationContext operationContext = new OperationContext(); - options.setStoreBlobContentMD5(true); - options.setTimeoutIntervalInMs(90000); - options.setRetryPolicyFactory(new RetryNoRetry()); - blobRef.uploadFullBlob(sourceStream, blobLength, null, options, operationContext); - - BlobInputStream blobStream = blobRef.openInputStream(); - - for (int i = 0; i < blobLength; i++) { - int data = blobStream.read(); - Assert.assertTrue(data >= 0); - Assert.assertEquals(buff[i], (byte) data); - } - - Assert.assertEquals(-1, blobStream.read()); - - blobRef.delete(); - } - - @Test - public void testCurrentOperationByteCount() throws URISyntaxException, StorageException, IOException { - final int blockLength = 4 * 1024 * 1024; - final Random randGenerator = new Random(); - String blobName = "testblob" + Integer.toString(randGenerator.nextInt(50000)); - blobName = blobName.replace('-', '_'); - - final CloudBlobContainer containerRef = bClient.getContainerReference(BlobTestBase.testSuiteContainerName); - - final CloudBlockBlob blobRef = containerRef.getBlockBlobReference(blobName); - - final ArrayList byteList = new ArrayList(); - final ArrayList blockList = new ArrayList(); - - int numberOfBlocks = 4; - - for (int m = 0; m < numberOfBlocks; m++) { - final byte[] buff = new byte[blockLength]; - randGenerator.nextBytes(buff); - byteList.add(buff); - blobRef.uploadBlock("ABC" + m, new ByteArrayInputStream(buff), blockLength); - - blockList.add(new BlockEntry("ABC" + m, BlockSearchMode.LATEST)); - } - - blobRef.commitBlockList(blockList); - - OperationContext operationContext = new OperationContext(); - BlobRequestOptions options = new BlobRequestOptions(); - options.setTimeoutIntervalInMs(2000); - options.setRetryPolicyFactory(new RetryNoRetry()); - - ByteArrayOutputStream downloadedDataStream = new ByteArrayOutputStream(); - try { - blobRef.download(downloadedDataStream, null, options, operationContext); - } - catch (Exception e) { - Assert.assertEquals(downloadedDataStream.size(), operationContext.getCurrentOperationByteCount()); - } - - operationContext = new OperationContext(); - options = new BlobRequestOptions(); - options.setTimeoutIntervalInMs(90000); - - downloadedDataStream = new ByteArrayOutputStream(); - blobRef.download(downloadedDataStream, null, options, operationContext); - - Assert.assertEquals(blockLength * numberOfBlocks, operationContext.getCurrentOperationByteCount()); - - blobRef.delete(); - } - - @Test - public void testContainerSharedKeyLite() throws StorageException, URISyntaxException { - bClient.setAuthenticationScheme(AuthenticationScheme.SHAREDKEYLITE); - String name = generateRandomContainerName(); - CloudBlobContainer newContainer = bClient.getContainerReference(name); - newContainer.create(); - - BlobContainerPermissions expectedPermissions; - BlobContainerPermissions testPermissions; - - try { - // Test new permissions. - expectedPermissions = new BlobContainerPermissions(); - testPermissions = newContainer.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - - // Test setting empty permissions. - newContainer.uploadPermissions(expectedPermissions); - testPermissions = newContainer.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - - // Add a policy, check setting and getting. - SharedAccessBlobPolicy policy1 = new SharedAccessBlobPolicy(); - Calendar now = GregorianCalendar.getInstance(); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 10); - policy1.setSharedAccessExpiryTime(now.getTime()); - - policy1.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.DELETE, - SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.DELETE)); - expectedPermissions.getSharedAccessPolicies().put(UUID.randomUUID().toString(), policy1); - - newContainer.uploadPermissions(expectedPermissions); - testPermissions = newContainer.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - } - finally { - // cleanup - newContainer.deleteIfExists(); - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/IdempotentClientFilterTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/IdempotentClientFilterTest.java deleted file mode 100644 index 82963a885e9cc..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/IdempotentClientFilterTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.core; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientRequest; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.filter.ClientFilter; - -/** - * Test fixture for IdempotentClientFilter class - * - */ -public class IdempotentClientFilterTest { - Client client; - RetryFilter retry; - CountingFilter filter1; - CountingFilter filter2; - - @Before - public void setup() { - client = Client.create(); - client.addFilter(new MockSinkFilter()); - - retry = new RetryFilter(); - filter1 = new CountingFilter(); - filter2 = new CountingFilter(); - filter2.key = "secondfilter"; - } - - @Test - public void filterRunsFirstTime() throws Exception { - client.addFilter(filter1); - - WebResource r = client.resource("http://test.example"); - ClientResponse response = r.get(ClientResponse.class); - - assertEquals(ClientResponse.Status.ACCEPTED, response.getClientResponseStatus()); - - assertEquals(1, filter1.count); - } - - @Test - public void filterRunsOnlyOnceWhenRequestIsRetried() throws Exception { - retry.triesLeft = 3; - client.addFilter(filter1); - client.addFilter(retry); - - WebResource r = client.resource("http://test.example"); - ClientResponse response = r.get(ClientResponse.class); - - assertEquals(ClientResponse.Status.ACCEPTED, response.getClientResponseStatus()); - assertEquals(1, filter1.count); - } - - @Test - public void multipleIdempotentFiltersRunFirstTime() throws Exception { - client.addFilter(filter1); - client.addFilter(filter2); - - WebResource r = client.resource("http://test.example"); - ClientResponse response = r.get(ClientResponse.class); - - assertEquals(ClientResponse.Status.ACCEPTED, response.getClientResponseStatus()); - - assertEquals(1, filter1.count); - assertEquals(1, filter2.count); - } - - @Test - public void multipleIdempotentFiltersRunOnceWhenRetried() throws Exception { - retry.triesLeft = 4; - - client.addFilter(filter1); - client.addFilter(filter2); - client.addFilter(retry); - - WebResource r = client.resource("http://test.example"); - ClientResponse response = r.get(ClientResponse.class); - - assertEquals(ClientResponse.Status.ACCEPTED, response.getClientResponseStatus()); - - assertEquals(1, filter1.count); - assertEquals(1, filter2.count); - } - - @Test - public void idempotentFilterRunsAgainOnSecondRequest() throws Exception { - client.addFilter(filter1); - - WebResource r = client.resource("http://test.example"); - r.get(ClientResponse.class); - - r = client.resource("http://test.example"); - r.get(ClientResponse.class); - - assertEquals(2, filter1.count); - } - - private class RetryFilter extends ClientFilter { - int triesLeft = 1; - - /* (non-Javadoc) - * @see com.sun.jersey.api.client.filter.ClientFilter#handle(com.sun.jersey.api.client.ClientRequest) - */ - @Override - public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { - ClientResponse response = null; - while (triesLeft > 0) { - --triesLeft; - response = getNext().handle(cr); - } - return response; - } - } - - private class CountingFilter extends IdempotentClientFilter { - public int count; - private String key = null; - - @Override - protected ClientResponse doHandle(ClientRequest cr) throws ClientHandlerException { - ++count; - return getNext().handle(cr); - } - - /* (non-Javadoc) - * @see com.microsoft.windowsazure.services.core.IdempotentClientFilter#getKey() - */ - @Override - protected String getKey() { - if (key != null) { - return key; - } - return super.getKey(); - } - } - - private class MockSinkFilter extends ClientFilter { - - @Override - public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { - ClientResponse response = Mockito.mock(ClientResponse.class); - Mockito.when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.ACCEPTED); - return response; - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/utils/pipeline/PipelineHelpersTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/utils/pipeline/PipelineHelpersTest.java deleted file mode 100644 index 39ecf8029822b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/core/utils/pipeline/PipelineHelpersTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.core.utils.pipeline; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.blob.models.AccessCondition; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; - -public class PipelineHelpersTest { - @Test - public void addOptionalSourceAccessConditionHeaderSuccess() throws Exception { - // Arrange - Client client = Client.create(); - WebResource webResource = client.resource("http://www.microsoft.com"); - Builder builder = webResource.header("ms-version", "1.0"); - AccessCondition accessCondition = AccessCondition.ifMatch("thisIsAETag"); - - // Act - Builder resultBuilder = PipelineHelpers.addOptionalSourceAccessConditionHeader(builder, accessCondition); - - // Assert - assertNotNull(resultBuilder); - - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/management/IntegrationTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/management/IntegrationTestBase.java deleted file mode 100644 index c9e6c5787e3b1..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/management/IntegrationTestBase.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management; - -import java.util.Map; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.Builder.Alteration; -import com.microsoft.windowsazure.services.core.Builder.Registry; -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.management.models.AffinityGroupInfo; -import com.microsoft.windowsazure.services.management.models.ListResult; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.filter.LoggingFilter; - -public abstract class IntegrationTestBase { - - protected ManagementContract service; - - @BeforeClass - public static void initializeSystem() { - System.setProperty("http.keepAlive", "false"); - } - - @Before - public void initialize() throws Exception { - createService(); - removeEntities(); - } - - private void createService() throws Exception { - // reinitialize configuration from known state - Configuration config = createConfiguration(); - - // add LoggingFilter to any pipeline that is created - Registry builder = (Registry) config.getBuilder(); - builder.alter(ManagementContract.class, Client.class, new Alteration() { - @Override - public Client alter(String profile, Client client, Builder builder, Map properties) { - client.addFilter(new LoggingFilter()); - return client; - } - }); - - // applied as default configuration - Configuration.setInstance(config); - service = ManagementService.create(config); - } - - private void removeEntities() { - ListResult listAffinityGroupResult = null; - try { - listAffinityGroupResult = service.listAffinityGroups(); - } - catch (ServiceException e) { - } - - for (AffinityGroupInfo affinityGroupInfo : listAffinityGroupResult) { - try { - String affinityGroupName = affinityGroupInfo.getName(); - if ((affinityGroupName != null) && (affinityGroupName.startsWith("test"))) { - service.deleteAffinityGroup(affinityGroupInfo.getName()); - } - } - catch (ServiceException e) { - } - } - - } - - @AfterClass - public static void cleanUpTestArtifacts() throws Exception { - // Configuration config = createConfiguration(); - } - - protected static Configuration createConfiguration() throws Exception { - Configuration config = Configuration.load(); - - overrideWithEnv(config, ManagementConfiguration.URI); - overrideWithEnv(config, ManagementConfiguration.SUBSCRIPTION_ID); - overrideWithEnv(config, ManagementConfiguration.KEYSTORE_PASSWORD); - overrideWithEnv(config, ManagementConfiguration.KEYSTORE_PATH); - overrideWithEnv(config, ManagementConfiguration.KEYSTORE_TYPE); - - return config; - } - - private static void overrideWithEnv(Configuration config, String key) { - String value = System.getenv(key); - if (value == null) - return; - - config.setProperty(key, value); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/management/ManagementIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/management/ManagementIntegrationTest.java deleted file mode 100644 index 0900786b8cd48..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/management/ManagementIntegrationTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.management; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.management.models.AffinityGroupInfo; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.CreateAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.GetAffinityGroupResult; -import com.microsoft.windowsazure.services.management.models.ListResult; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupOptions; -import com.microsoft.windowsazure.services.management.models.UpdateAffinityGroupResult; - -public class ManagementIntegrationTest extends IntegrationTestBase { - - @Test - public void createAffinityGroupSuccess() throws Exception { - // Arrange - String expectedAffinityGroupName = "testCreateAffinityGroupSuccess"; - String expectedLabel = Base64.encode("testCreateAffinityGroupSuccess".getBytes("UTF-8")); - String expectedLocation = "West US"; - CreateAffinityGroupOptions createAffinityGroupOptions = new CreateAffinityGroupOptions( - expectedAffinityGroupName, expectedLabel, expectedLocation); - - // Act - CreateAffinityGroupResult createAffinityGroupResult = service.createAffinityGroup(createAffinityGroupOptions); - - AffinityGroupInfo affinityGroupInfo = service.getAffinityGroup(expectedAffinityGroupName).getValue(); - - // Assert - assertNotNull(createAffinityGroupResult.getLocation()); - assertNotNull(createAffinityGroupResult.getRegion()); - assertNotNull(createAffinityGroupResult.getServer()); - assertNotNull(createAffinityGroupResult.getDate()); - assertEquals(expectedAffinityGroupName, affinityGroupInfo.getName()); - assertEquals(expectedLabel, affinityGroupInfo.getLabel()); - assertEquals(expectedLocation, affinityGroupInfo.getLocation()); - - } - - @Test - public void createAffinityGroupWithOptionalParametersSuccess() throws Exception { - // Arrange - String expectedAffinityGroupName = "testCreateAffinityGroupWithOptionalParametersSuccess"; - String expectedLabel = Base64.encode("testCreateAffinityGroupWithOptionalParameterSuccess".getBytes("UTF-8")); - String expectedLocation = "West US"; - String expectedDescription = "testCreateAffinityGroupWithOptionalParameterSuccessDescription"; - CreateAffinityGroupOptions createAffinityGroupOptions = new CreateAffinityGroupOptions( - expectedAffinityGroupName, expectedLabel, expectedLocation).setDescription(expectedDescription); - - // Act - CreateAffinityGroupResult createAffinityGroupResult = service.createAffinityGroup(createAffinityGroupOptions); - - // Assert - AffinityGroupInfo actualAffinityGroupInfo = service.getAffinityGroup(expectedAffinityGroupName).getValue(); - assertNotNull(createAffinityGroupResult.getLocation()); - assertNotNull(createAffinityGroupResult.getRegion()); - assertNotNull(createAffinityGroupResult.getServer()); - assertNotNull(createAffinityGroupResult.getDate()); - assertEquals(expectedDescription, actualAffinityGroupInfo.getDescription()); - - } - - @Test - public void listAffinityGroupsSuccess() throws ServiceException { - // Arrange - - // Act - ListResult listAffinityGroupsResult = service.listAffinityGroups(); - - // Assert - assertNotNull(listAffinityGroupsResult); - - } - - @Test - public void deleteAffinityGroupSuccess() throws ServiceException, Exception { - // Arrange - String affinityGroupName = "testDeleteAffinityGroupSuccess"; - String label = Base64.encode("testDeleteAffinityGroupSuccesslabel".getBytes("UTF-8")); - String location = "West US"; - CreateAffinityGroupOptions createAffinityGroupOptions = new CreateAffinityGroupOptions(affinityGroupName, - label, location); - service.createAffinityGroup(createAffinityGroupOptions); - - // Act - service.deleteAffinityGroup(affinityGroupName); - - // Assert - - } - - @Test - public void updateAffinityGroupSuccess() throws Exception { - // Arrange - String expectedAffinityGroupName = "testUpdateAffinityGroupSuccess"; - String expectedAffinityGroupLabel = Base64.encode("testUpdateAffinityGroupSuccess".getBytes("UTF-8")); - String expectedLocation = "West US"; - String expectedDescription = "updateAffinityGroupSuccess"; - CreateAffinityGroupOptions createAffinityGroupOptions = new CreateAffinityGroupOptions( - expectedAffinityGroupName, expectedAffinityGroupLabel, expectedLocation); - service.createAffinityGroup(createAffinityGroupOptions); - UpdateAffinityGroupOptions updateAffinityGroupOptions = new UpdateAffinityGroupOptions( - expectedAffinityGroupName, expectedAffinityGroupLabel).setDescription(expectedDescription); - - // Act - UpdateAffinityGroupResult updateAffinityGroupResult = service.updateAffinityGroup(updateAffinityGroupOptions); - - // Assert - assertNotNull(updateAffinityGroupResult.getRegion()); - assertNotNull(updateAffinityGroupResult.getDate()); - assertNotNull(updateAffinityGroupResult.getRequestId()); - - } - - @Test - public void getAffinityGroupPropertiesSuccess() throws Exception { - // Arrange - String expectedAffinityGroupName = "testGetAffinityGroupPropertiesSuccess"; - String expectedAffinityGroupLabel = Base64.encode("testGetAffinityGroupPropertiesSuccess".getBytes("UTF-8")); - String expectedLocation = "West US"; - CreateAffinityGroupOptions createAffinityGroupOptions = new CreateAffinityGroupOptions( - expectedAffinityGroupName, expectedAffinityGroupLabel, expectedLocation); - service.createAffinityGroup(createAffinityGroupOptions); - - // Act - GetAffinityGroupResult getAffinityGroupResult = service.getAffinityGroup(expectedAffinityGroupName); - AffinityGroupInfo affinityGroupInfo = getAffinityGroupResult.getValue(); - - // Assert - assertEquals(expectedAffinityGroupName, affinityGroupInfo.getName()); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AccessPolicyIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AccessPolicyIntegrationTest.java deleted file mode 100644 index 32bfdbe2dfb9a..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AccessPolicyIntegrationTest.java +++ /dev/null @@ -1,207 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ExponentialRetryPolicy; -import com.microsoft.windowsazure.services.core.RetryPolicyFilter; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.AccessPolicy; -import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; -import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; - -public class AccessPolicyIntegrationTest extends IntegrationTestBase { - private void verifyInfosEqual(String message, AccessPolicyInfo expected, AccessPolicyInfo actual) { - verifyPolicyProperties(message, expected.getName(), expected.getDurationInMinutes(), expected.getPermissions(), - actual); - } - - private void verifyPolicyProperties(String message, String testName, double duration, - AccessPolicyPermission permission, AccessPolicyInfo policy) { - verifyPolicyProperties(message, testName, duration, EnumSet.of(permission), policy); - } - - private void verifyPolicyProperties(String message, String testName, double duration, - EnumSet permissions, AccessPolicyInfo policy) { - assertNotNull(message, policy); - assertEquals(message + " Name", testName, policy.getName()); - assertEquals(message + " DurationInMinutes", duration, policy.getDurationInMinutes(), 0.00001); - for (AccessPolicyPermission permission : permissions) { - if (permission != AccessPolicyPermission.NONE) { - assertTrue(message + "permissions should contain " + permission, - policy.getPermissions().contains(permission)); - } - } - assertEquals(message + " Permissions", permissions, policy.getPermissions()); - - assertNotNull(message + " Id", policy.getId()); - assertNotNull(message + " Created", policy.getCreated()); - assertNotNull(message + " LastModified", policy.getLastModified()); - assertEquals(message + " Created & LastModified", policy.getCreated(), policy.getLastModified()); - } - - @Test - public void canCreateAccessPolicy() throws Exception { - String testName = testPolicyPrefix + "CanCreate"; - double duration = 5; - - AccessPolicyInfo policy = service.create(AccessPolicy.create(testName, duration, - EnumSet.of(AccessPolicyPermission.WRITE))); - - verifyPolicyProperties("policy", testName, duration, AccessPolicyPermission.WRITE, policy); - } - - @Test - public void canCreateAccessPolicyWithReadPermissions() throws Exception { - String testName = testPolicyPrefix + "CanCreateRead"; - double duration = 5; - - AccessPolicyInfo policy = service.create(AccessPolicy.create(testName, duration, - EnumSet.of(AccessPolicyPermission.READ))); - - verifyPolicyProperties("policy", testName, duration, AccessPolicyPermission.READ, policy); - } - - @Test - public void canGetSinglePolicyById() throws Exception { - String expectedName = testPolicyPrefix + "GetOne"; - double duration = 1; - AccessPolicyInfo policyToGet = service.create(AccessPolicy.create(expectedName, duration, - EnumSet.of(AccessPolicyPermission.WRITE))); - - AccessPolicyInfo retrievedPolicy = service.get(AccessPolicy.get(policyToGet.getId())); - - assertEquals(policyToGet.getId(), retrievedPolicy.getId()); - verifyPolicyProperties("retrievedPolicy", expectedName, duration, AccessPolicyPermission.WRITE, retrievedPolicy); - } - - @Test - public void canGetSinglePolicyByInvalidId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.get(AccessPolicy.get(invalidId)); - } - - @Test - public void canGetSinglePolicyByNonexistId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(AccessPolicy.get(validButNonexistAccessPolicyId)); - } - - @Test - public void canRetrieveListOfAccessPolicies() throws Exception { - String[] policyNames = new String[] { testPolicyPrefix + "ListOne", testPolicyPrefix + "ListTwo" }; - double duration = 3; - EnumSet permissions = EnumSet.of(AccessPolicyPermission.WRITE, - AccessPolicyPermission.LIST); - - List expectedAccessPolicies = new ArrayList(); - for (int i = 0; i < policyNames.length; i++) { - AccessPolicyInfo policy = service.create(AccessPolicy.create(policyNames[i], duration, permissions)); - expectedAccessPolicies.add(policy); - } - - List actualAccessPolicies = service.list(AccessPolicy.list()); - - verifyListResultContains("listAccessPolicies", expectedAccessPolicies, actualAccessPolicies, - new ComponentDelegate() { - @Override - public void verifyEquals(String message, Object expected, Object actual) { - verifyInfosEqual(message, (AccessPolicyInfo) expected, (AccessPolicyInfo) actual); - } - }); - } - - @Test - public void canUseQueryParametersWhenListingAccessPolicies() throws Exception { - String[] policyNames = new String[] { testPolicyPrefix + "ListThree", testPolicyPrefix + "ListFour", - testPolicyPrefix + "ListFive", testPolicyPrefix + "ListSix", testPolicyPrefix + "ListSeven" }; - - double duration = 3; - EnumSet permissions = EnumSet.of(AccessPolicyPermission.WRITE, - AccessPolicyPermission.LIST); - - List expectedAccessPolicies = new ArrayList(); - for (int i = 0; i < policyNames.length; i++) { - AccessPolicyInfo policy = service.create(AccessPolicy.create(policyNames[i], duration, permissions)); - expectedAccessPolicies.add(policy); - } - - List actualAccessPolicies = service.list(AccessPolicy.list().setTop(2)); - - assertEquals(2, actualAccessPolicies.size()); - } - - // Note: Access Policy cannot be updated. - - @Test - public void canDeleteAccessPolicyById() throws Exception { - String policyName = testPolicyPrefix + "ToDelete"; - double duration = 1; - AccessPolicyInfo policyToDelete = service.create(AccessPolicy.create(policyName, duration, - EnumSet.of(AccessPolicyPermission.WRITE))); - List listPoliciesResult = service.list(AccessPolicy.list()); - int policyCountBaseline = listPoliciesResult.size(); - - service.delete(AccessPolicy.delete(policyToDelete.getId())); - - listPoliciesResult = service.list(AccessPolicy.list()); - assertEquals("listPoliciesResult.size", policyCountBaseline - 1, listPoliciesResult.size()); - - for (AccessPolicyInfo policy : service.list(AccessPolicy.list())) { - assertFalse(policyToDelete.getId().equals(policy.getId())); - } - - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(AccessPolicy.get(policyToDelete.getId())); - } - - @Test - public void canDeleteAccessPolicyByInvalidId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.delete(AccessPolicy.delete(invalidId)); - } - - @Test - public void canDeleteAccessPolicyByNonexistId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.delete(AccessPolicy.delete(validButNonexistAccessPolicyId)); - } - - @Test - public void canRetryAccessPolicyCreation() throws Exception { - String name = testPolicyPrefix + "canRetryAccessPolicyCreationPolicy"; - double duration = 1; - EnumSet write = EnumSet.of(AccessPolicyPermission.WRITE); - service.create(AccessPolicy.create(name + "1", duration, write)); - - ExponentialRetryPolicy forceRetryPolicy = new ExponentialRetryPolicy(1, 1, new int[] { 201 }); - MediaContract forceRetryService = service.withFilter(new RetryPolicyFilter(forceRetryPolicy)); - - forceRetryService.create(AccessPolicy.create(name + "2", duration, write)); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AssetFileIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AssetFileIntegrationTest.java deleted file mode 100644 index 8a9bc1d7b76bd..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AssetFileIntegrationTest.java +++ /dev/null @@ -1,236 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.EnumSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.AccessPolicy; -import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; -import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetFile; -import com.microsoft.windowsazure.services.media.models.AssetFileInfo; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; - -public class AssetFileIntegrationTest extends IntegrationTestBase { - - // Some dummy binary data for uploading - private static byte[] firstPrimes = new byte[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; - private static byte[] onesAndZeros = new byte[] { 1, 0, 1, 0, 1, 0, 1, 0 }; - private static byte[] countingUp = new byte[] { 3, 4, 5, 6, 7, 8, 9, 10, 11 }; - - private static final String BLOB_NAME = "primes.bin"; - private static final String BLOB_NAME_2 = "primes2.bin"; - - private static AccessPolicyInfo writePolicy; - - @BeforeClass - public static void setup() throws Exception { - IntegrationTestBase.setup(); - - writePolicy = createWritePolicy("uploadWritePolicy", 30); - } - - @Test - public void canCreateFileForUploadedBlob() throws Exception { - AssetInfo asset = createTestAsset("createFileForUploadedBlob"); - LocatorInfo locator = createLocator(writePolicy, asset, 5); - WritableBlobContainerContract blobWriter = service.createBlobWriter(locator); - - createAndUploadBlob(blobWriter, BLOB_NAME, firstPrimes); - - service.action(AssetFile.createFileInfos(asset.getId())); - - ListResult files = service.list(AssetFile.list(asset.getAssetFilesLink())); - - assertEquals(1, files.size()); - AssetFileInfo file = files.get(0); - assertEquals(BLOB_NAME, file.getName()); - } - - @Test - public void canCreateFileEntityDirectly() throws Exception { - AssetInfo asset = createTestAsset("createFileEntityDirectly"); - LocatorInfo locator = createLocator(writePolicy, asset, 5); - WritableBlobContainerContract blobWriter = service.createBlobWriter(locator); - - createAndUploadBlob(blobWriter, BLOB_NAME_2, firstPrimes); - - service.create(AssetFile.create(asset.getId(), BLOB_NAME_2)); - - ListResult files = service.list(AssetFile.list(asset.getAssetFilesLink())); - - boolean found = false; - for (AssetFileInfo file : files) { - if (file.getName().equals(BLOB_NAME_2)) { - found = true; - break; - } - } - - assertTrue(found); - } - - @Test - public void canCreateAssetWithMultipleFiles() throws Exception { - AssetInfo asset = createTestAsset("createWithMultipleFiles"); - AccessPolicyInfo policy = createWritePolicy("createWithMultipleFiles", 10); - LocatorInfo locator = createLocator(policy, asset, 5); - - WritableBlobContainerContract blobWriter = service.createBlobWriter(locator); - - createAndUploadBlob(blobWriter, "blob1.bin", firstPrimes); - createAndUploadBlob(blobWriter, "blob2.bin", onesAndZeros); - createAndUploadBlob(blobWriter, "blob3.bin", countingUp); - - AssetFileInfo file1 = service.create(AssetFile.create(asset.getId(), "blob1.bin").setIsPrimary(true) - .setIsEncrypted(false).setContentFileSize(new Long(firstPrimes.length))); - - AssetFileInfo file2 = service.create(AssetFile.create(asset.getId(), "blob2.bin").setIsPrimary(false) - .setIsEncrypted(false).setContentFileSize(new Long(onesAndZeros.length))); - - AssetFileInfo file3 = service.create(AssetFile.create(asset.getId(), "blob3.bin").setIsPrimary(false) - .setIsEncrypted(false).setContentFileSize(new Long(countingUp.length)).setContentChecksum("1234")); - - ListResult files = service.list(AssetFile.list(asset.getAssetFilesLink())); - - assertEquals(3, files.size()); - - ArrayList results = new ArrayList(files); - Collections.sort(results, new Comparator() { - @Override - public int compare(AssetFileInfo o1, AssetFileInfo o2) { - return o1.getName().compareTo(o2.getName()); - } - }); - - assertAssetFileInfoEquals("results.get(0)", file1, results.get(0)); - assertAssetFileInfoEquals("results.get(1)", file2, results.get(1)); - assertAssetFileInfoEquals("results.get(2)", file3, results.get(2)); - } - - @Test - public void canCreateFileAndThenUpdateIt() throws Exception { - AssetInfo asset = createTestAsset("createAndUpdate"); - AccessPolicyInfo policy = createWritePolicy("createAndUpdate", 10); - LocatorInfo locator = createLocator(policy, asset, 5); - WritableBlobContainerContract blobWriter = service.createBlobWriter(locator); - - createAndUploadBlob(blobWriter, "toUpdate.bin", firstPrimes); - - AssetFileInfo file = service.create(AssetFile.create(asset.getId(), "toUpdate.bin")); - - service.update(AssetFile.update(file.getId()).setMimeType("application/octet-stream")); - - AssetFileInfo fromServer = service.get(AssetFile.get(file.getId())); - - assertEquals("application/octet-stream", fromServer.getMimeType()); - } - - @Test - public void canDeleteFileFromAsset() throws Exception { - AssetInfo asset = createTestAsset("deleteFile"); - AccessPolicyInfo policy = createWritePolicy("deleteFile", 10); - LocatorInfo locator = createLocator(policy, asset, 5); - WritableBlobContainerContract blobWriter = service.createBlobWriter(locator); - - createAndUploadBlob(blobWriter, "todelete.bin", firstPrimes); - createAndUploadBlob(blobWriter, "tokeep.bin", onesAndZeros); - - service.action(AssetFile.createFileInfos(asset.getId())); - - ListResult originalFiles = service.list(AssetFile.list(asset.getAssetFilesLink())); - assertEquals(2, originalFiles.size()); - - for (AssetFileInfo file : originalFiles) { - if (file.getName().equals("todelete.bin")) { - service.delete(AssetFile.delete(file.getId())); - break; - } - } - - ListResult newFiles = service.list(AssetFile.list(asset.getAssetFilesLink())); - assertEquals(1, newFiles.size()); - assertEquals("tokeep.bin", newFiles.get(0).getName()); - } - - // - // Helper functions to create various media services entities - // - private static AssetInfo createTestAsset(String name) throws ServiceException { - return service.create(Asset.create().setName(testAssetPrefix + name)); - } - - private static AccessPolicyInfo createWritePolicy(String name, int durationInMinutes) throws ServiceException { - return service.create(AccessPolicy.create(testPolicyPrefix + name, durationInMinutes, - EnumSet.of(AccessPolicyPermission.WRITE))); - } - - private static void createAndUploadBlob(WritableBlobContainerContract blobWriter, String blobName, byte[] data) - throws ServiceException { - InputStream blobContent = new ByteArrayInputStream(data); - blobWriter.createBlockBlob(blobName, blobContent); - } - - // - // Assertion helpers - // - - private void assertAssetFileInfoEquals(String message, AssetFileInfo expected, AssetFileInfo actual) { - verifyAssetInfoProperties(message, expected.getId(), expected.getName(), expected.getParentAssetId(), - expected.getIsPrimary(), expected.getIsEncrypted(), expected.getEncryptionKeyId(), - expected.getEncryptionScheme(), expected.getEncryptionVersion(), expected.getInitializationVector(), - expected.getCreated(), expected.getLastModified(), expected.getContentChecksum(), - expected.getMimeType(), actual); - } - - private void verifyAssetInfoProperties(String message, String id, String name, String parentAssetId, - boolean isPrimary, boolean isEncrypted, String encryptionKeyId, String encryptionScheme, - String encryptionVersion, String initializationVector, Date created, Date lastModified, - String contentChecksum, String mimeType, AssetFileInfo assetFile) { - assertNotNull(message, assetFile); - - assertEquals(message + ".getId", id, assetFile.getId()); - assertEquals(message + ".getName", name, assetFile.getName()); - assertEquals(message + ".getParentAssetId", parentAssetId, assetFile.getParentAssetId()); - assertEquals(message + ".getIsPrimary", isPrimary, assetFile.getIsPrimary()); - - assertEquals(message + ".getIsEncrypted", isEncrypted, assetFile.getIsEncrypted()); - assertEquals(message + ".getEncryptionKeyId", encryptionKeyId, assetFile.getEncryptionKeyId()); - assertEquals(message + ".getEncryptionScheme", encryptionScheme, assetFile.getEncryptionScheme()); - assertEquals(message + ".getEncryptionVersion", encryptionVersion, assetFile.getEncryptionVersion()); - assertEquals(message + ".getInitializationVector", initializationVector, assetFile.getInitializationVector()); - - assertDateApproxEquals(message + ".getCreated", created, assetFile.getCreated()); - assertDateApproxEquals(message + ".getLastModified", lastModified, assetFile.getLastModified()); - assertEquals(message + ".getContentChecksum", contentChecksum, assetFile.getContentChecksum()); - assertEquals(message + ".getMimeType", mimeType, assetFile.getMimeType()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AssetIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AssetIntegrationTest.java deleted file mode 100644 index b9bcbb3bfeef8..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/AssetIntegrationTest.java +++ /dev/null @@ -1,362 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.io.InputStream; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.EnumSet; -import java.util.List; -import java.util.UUID; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.AccessPolicy; -import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; -import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetFile; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.AssetOption; -import com.microsoft.windowsazure.services.media.models.AssetState; -import com.microsoft.windowsazure.services.media.models.ContentKey; -import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; -import com.microsoft.windowsazure.services.media.models.ContentKeyType; -import com.microsoft.windowsazure.services.media.models.Job; -import com.microsoft.windowsazure.services.media.models.JobInfo; -import com.microsoft.windowsazure.services.media.models.LinkInfo; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.Locator; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; -import com.microsoft.windowsazure.services.media.models.LocatorType; -import com.microsoft.windowsazure.services.media.models.ProtectionKey; -import com.microsoft.windowsazure.services.media.models.Task; -import com.microsoft.windowsazure.services.media.models.Task.CreateBatchOperation; - -public class AssetIntegrationTest extends IntegrationTestBase { - - private void verifyInfosEqual(String message, AssetInfo expected, AssetInfo actual) { - verifyAssetProperties(message, expected.getName(), expected.getAlternateId(), expected.getOptions(), - expected.getState(), actual); - } - - private void verifyAssetProperties(String message, String testName, String altId, AssetOption encryptionOption, - AssetState assetState, AssetInfo actualAsset) { - verifyAssetProperties(message, testName, altId, encryptionOption, assetState, null, null, null, actualAsset); - } - - private void verifyAssetProperties(String message, String testName, String altId, AssetOption encryptionOption, - AssetState assetState, String id, Date created, Date lastModified, AssetInfo actualAsset) { - assertNotNull(message, actualAsset); - assertEquals(message + " Name", testName, actualAsset.getName()); - assertEquals(message + " AlternateId", altId, actualAsset.getAlternateId()); - assertEquals(message + " Options", encryptionOption, actualAsset.getOptions()); - assertEquals(message + " State", assetState, actualAsset.getState()); - if (id != null) { - assertEquals(message + " Id", id, actualAsset.getId()); - } - if (created != null) { - assertEquals(message + " Created", created, actualAsset.getCreated()); - } - if (lastModified != null) { - assertEquals(message + " LastModified", lastModified, actualAsset.getLastModified()); - } - } - - @Test - public void createAssetOptionsSuccess() throws Exception { - // Arrange - String testName = testAssetPrefix + "createAssetOptionsSuccess"; - String altId = "altId"; - AssetOption encryptionOption = AssetOption.StorageEncrypted; - AssetState assetState = AssetState.Published; - - // Act - AssetInfo actualAsset = service.create(Asset.create().setAlternateId(altId).setOptions(encryptionOption) - .setState(assetState).setName(testName)); - - // Assert - verifyAssetProperties("actualAsset", testName, altId, encryptionOption, assetState, actualAsset); - } - - @Test - public void createAssetMeanString() throws Exception { - // Arrange - String meanString = "'\"(?++\\+&==/&?''$@:// +ne " - + "{\"jsonLike\":\"Created\":\"\\/Date(1336368841597)\\/\",\"Name\":null,cksum value\"}}" - + "Some unicode: \uB2E4\uB974\uB2E4\uB294\u0625 \u064A\u062F\u064A\u0648\u0009\r\n"; - - String testName = testAssetPrefix + "createAssetMeanString" + meanString; - - // Act - AssetInfo actualAsset = service.create(Asset.create().setName(testName)); - - // Assert - assertEquals("actualAsset Name", testName, actualAsset.getName()); - } - - @Test - public void createAssetNullNameSuccess() throws Exception { - // Arrange - - // Act - AssetInfo actualAsset = null; - try { - actualAsset = service.create(Asset.create()); - // Assert - verifyAssetProperties("actualAsset", "", "", AssetOption.None, AssetState.Initialized, actualAsset); - } - finally { - // Clean up the anonymous asset now while we have the id, because we - // do not want to delete all anonymous assets in the bulk-cleanup code. - try { - if (actualAsset != null) { - service.delete(Asset.delete(actualAsset.getId())); - } - } - catch (ServiceException ex) { - ex.printStackTrace(); - } - } - } - - @Test - public void getAssetSuccess() throws Exception { - // Arrange - String testName = testAssetPrefix + "GetAssetSuccess"; - String altId = "altId"; - AssetOption encryptionOption = AssetOption.StorageEncrypted; - AssetState assetState = AssetState.Published; - - AssetInfo assetInfo = service.create(Asset.create().setName(testName).setAlternateId(altId) - .setOptions(encryptionOption).setState(assetState)); - - // Act - AssetInfo actualAsset = service.get(Asset.get(assetInfo.getId())); - - // Assert - verifyInfosEqual("actualAsset", assetInfo, actualAsset); - } - - @Test - public void getAssetInvalidId() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.get(Asset.get(invalidId)); - } - - @Test - public void getAssetNonexistId() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(Asset.get(validButNonexistAssetId)); - } - - @Test - public void listAssetSuccess() throws ServiceException { - // Arrange - String altId = "altId"; - AssetOption encryptionOption = AssetOption.StorageEncrypted; - AssetState assetState = AssetState.Published; - - String[] assetNames = new String[] { testAssetPrefix + "assetA", testAssetPrefix + "assetB" }; - List expectedAssets = new ArrayList(); - for (int i = 0; i < assetNames.length; i++) { - String name = assetNames[i]; - expectedAssets.add(service.create(Asset.create().setName(name).setAlternateId(altId) - .setOptions(encryptionOption).setState(assetState))); - } - - // Act - Collection listAssetResult = service.list(Asset.list()); - - // Assert - - verifyListResultContains("listAssets", expectedAssets, listAssetResult, new ComponentDelegate() { - @Override - public void verifyEquals(String message, Object expected, Object actual) { - verifyInfosEqual(message, (AssetInfo) expected, (AssetInfo) actual); - } - }); - } - - @Test - public void canListAssetsWithOptions() throws ServiceException { - String[] assetNames = new String[] { testAssetPrefix + "assetListOptionsA", - testAssetPrefix + "assetListOptionsB", testAssetPrefix + "assetListOptionsC", - testAssetPrefix + "assetListOptionsD" }; - List expectedAssets = new ArrayList(); - for (int i = 0; i < assetNames.length; i++) { - String name = assetNames[i]; - expectedAssets.add(service.create(Asset.create().setName(name))); - } - - Collection listAssetResult = service.list(Asset.list().setTop(2)); - - // Assert - - assertEquals(2, listAssetResult.size()); - } - - @Test - public void updateAssetSuccess() throws Exception { - // Arrange - String originalTestName = testAssetPrefix + "updateAssetSuccessOriginal"; - AssetOption originalEncryptionOption = AssetOption.StorageEncrypted; - AssetState originalAssetState = AssetState.Initialized; - AssetInfo originalAsset = service.create(Asset.create().setName(originalTestName).setAlternateId("altId") - .setOptions(originalEncryptionOption)); - - String updatedTestName = testAssetPrefix + "updateAssetSuccessUpdated"; - String altId = "otherAltId"; - - // Act - service.update(Asset.update(originalAsset.getId()).setName(updatedTestName).setAlternateId(altId)); - AssetInfo updatedAsset = service.get(Asset.get(originalAsset.getId())); - - // Assert - verifyAssetProperties("updatedAsset", updatedTestName, altId, originalEncryptionOption, originalAssetState, - updatedAsset); - } - - @Test - public void updateAssetNoChangesSuccess() throws Exception { - // Arrange - String originalTestName = testAssetPrefix + "updateAssetNoChangesSuccess"; - String altId = "altId"; - AssetInfo originalAsset = service.create(Asset.create().setName(originalTestName).setAlternateId(altId)); - - // Act - service.update(Asset.update(originalAsset.getId())); - AssetInfo updatedAsset = service.get(Asset.get(originalAsset.getId())); - - // Assert - verifyInfosEqual("updatedAsset", originalAsset, updatedAsset); - } - - @Test - public void updateAssetFailedWithInvalidId() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.update(Asset.update(validButNonexistAssetId)); - } - - @Test - public void deleteAssetSuccess() throws Exception { - // Arrange - String assetName = testAssetPrefix + "deleteAssetSuccess"; - AssetInfo assetInfo = service.create(Asset.create().setName(assetName)); - List listAssetsResult = service.list(Asset.list()); - int assetCountBaseline = listAssetsResult.size(); - - // Act - service.delete(Asset.delete(assetInfo.getId())); - - // Assert - listAssetsResult = service.list(Asset.list()); - assertEquals("listAssetsResult.size", assetCountBaseline - 1, listAssetsResult.size()); - - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(Asset.get(assetInfo.getId())); - } - - @Test - public void deleteAssetFailedWithInvalidId() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.delete(Asset.delete(validButNonexistAssetId)); - } - - @Test - public void linkAssetContentKeySuccess() throws ServiceException, URISyntaxException { - // Arrange - String originalTestName = testAssetPrefix + "linkAssetContentKeySuccess"; - AssetInfo assetInfo = service.create(Asset.create().setName(originalTestName) - .setOptions(AssetOption.StorageEncrypted)); - - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(ContentKeyType.StorageEncryption)); - String contentKeyId = String.format("nb:kid:UUID:%s", UUID.randomUUID()); - String encryptedContentKey = "dummyEncryptedContentKey"; - service.create(ContentKey.create(contentKeyId, ContentKeyType.StorageEncryption, encryptedContentKey) - .setProtectionKeyId(protectionKeyId)); - - // Act - service.action(Asset.linkContentKey(assetInfo.getId(), contentKeyId)); - - // Assert - - List contentKeys = service.list(ContentKey.list(assetInfo.getContentKeysLink())); - assertEquals(1, contentKeys.size()); - assertEquals(contentKeyId, contentKeys.get(0).getId()); - } - - @Test - public void linkAssetContentKeyInvalidIdFailed() throws ServiceException, URISyntaxException { - // Arrange - - // Act - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.action(Asset.linkContentKey(validButNonexistAssetId, "nb:kid:UUID:invalidContentKeyId")); - - // Assert - } - - @Test - public void canGetParentBackFromAsset() throws ServiceException, InterruptedException { - // Arrange - String originalAssetName = testAssetPrefix + "canGetParentBackFromAsset"; - AssetInfo originalAsset = service.create(Asset.create().setName(originalAssetName)); - - int durationInMinutes = 10; - AccessPolicyInfo accessPolicyInfo = service.create(AccessPolicy.create(testPolicyPrefix - + "uploadAesPortectedAssetSuccess", durationInMinutes, EnumSet.of(AccessPolicyPermission.WRITE))); - - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfo.getId(), originalAsset.getId(), - LocatorType.SAS)); - WritableBlobContainerContract blobWriter = service.createBlobWriter(locatorInfo); - - InputStream mpeg4H264InputStream = getClass().getResourceAsStream("/media/MPEG4-H264.mp4"); - blobWriter.createBlockBlob("MPEG4-H264.mp4", mpeg4H264InputStream); - service.action(AssetFile.createFileInfos(originalAsset.getId())); - - String jobName = testJobPrefix + "createJobSuccess"; - CreateBatchOperation taskCreator = Task - .create(MEDIA_ENCODER_MEDIA_PROCESSOR_2_2_0_0_ID, - "" + "JobInputAsset(0)" - + "JobOutputAsset(0)" + "") - .setConfiguration("H.264 256k DSL CBR").setName("My encoding Task"); - JobInfo jobInfo = service.create(Job.create().setName(jobName).addInputMediaAsset(originalAsset.getId()) - .addTaskCreator(taskCreator)); - - // Act - ListResult outputAssets = service.list(Asset.list(jobInfo.getOutputAssetsLink())); - assertEquals(1, outputAssets.size()); - AssetInfo childAsset = outputAssets.get(0); - - LinkInfo parentAssetLink = childAsset.getParentAssetsLink(); - AssetInfo parentAsset = service.get(Asset.get(parentAssetLink)); - - // Assert - assertEquals(originalAsset.getId(), parentAsset.getId()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ContentKeyIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ContentKeyIntegrationTest.java deleted file mode 100644 index eca527f932ed5..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ContentKeyIntegrationTest.java +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.net.URL; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.security.PrivateKey; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.media.models.ContentKey; -import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; -import com.microsoft.windowsazure.services.media.models.ContentKeyType; -import com.microsoft.windowsazure.services.media.models.ProtectionKey; -import com.microsoft.windowsazure.services.media.models.ProtectionKeyType; - -public class ContentKeyIntegrationTest extends IntegrationTestBase { - - private final String validButNonexistContentKeyId = "nb:kid:UUID:80dfe751-e5a1-4b29-a992-4a75276473af"; - private final ContentKeyType testContentKeyType = ContentKeyType.CommonEncryption; - private final String testEncryptedContentKey = "bFE4M/kZrKi00AoLOVpbQ4R9xja5P/pfBv9SC9I1Gw8yx+OIWdazGNpT7MgpeOLSebkxO5iDAIUKX5Es6oRUiH6pTNAMEtiHFBrKywODKnTQ09pCAMmdIA4q1gLeEUpsXPY/YXaLsTrBGbmRtlUYyaZEjestsngV8JpkJemCGjmMF0bHCoQRKt0LCVl/cqyWawzBuyaJniUCDdU8jem7sjrw8BbgCDmTAUmaj9TYxEP98d3wEJcL4pzDzOloYWXqzNB9assXgcQ0eouT7onSHa1d76X2E5q16AIIoOndLyIuAxlwFqpzF6LFy3X9mNGEY1iLXeFA89DE0PPx8EHtyg=="; - - private void assertByteArrayEquals(byte[] source, byte[] target) { - assertEquals(source.length, target.length); - for (int i = 0; i < source.length; i++) { - assertEquals(source[i], target[i]); - } - } - - private ContentKeyInfo createTestContentKey(String contentKeyNameSuffix) throws ServiceException { - String testContentKeyId = createRandomContentKeyId(); - String testContentKeyName = testContentKeyPrefix + contentKeyNameSuffix; - - ContentKeyInfo contentKeyInfo = service.create(ContentKey.create(testContentKeyId, testContentKeyType, - testEncryptedContentKey).setName(testContentKeyName)); - return contentKeyInfo; - } - - private ContentKeyInfo createValidTestContentKeyWithAesKey(String contentKeyNameSuffix, byte[] aesKey) - throws Exception { - String testContnetKeyName = testContentKeyPrefix + contentKeyNameSuffix; - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(ContentKeyType.StorageEncryption)); - String protectionKey = service.action(ProtectionKey.getProtectionKey(protectionKeyId)); - - String testContentKeyIdUuid = UUID.randomUUID().toString(); - String testContentKeyId = String.format("nb:kid:UUID:%s", testContentKeyIdUuid); - - byte[] encryptedContentKey = EncryptionHelper.encryptSymmetricKey(protectionKey, aesKey); - String encryptedContentKeyString = Base64.encode(encryptedContentKey); - String checksum = EncryptionHelper.calculateContentKeyChecksum(testContentKeyIdUuid, aesKey); - - ContentKeyInfo contentKeyInfo = service.create(ContentKey - .create(testContentKeyId, ContentKeyType.StorageEncryption, encryptedContentKeyString) - .setChecksum(checksum).setProtectionKeyId(protectionKeyId).setName(testContnetKeyName)); - - return contentKeyInfo; - } - - private ContentKeyInfo createValidTestContentKey(String contentKeyNameSuffix) throws Exception { - byte[] aesKey = createTestAesKey(); - return createValidTestContentKeyWithAesKey(contentKeyNameSuffix, aesKey); - } - - private byte[] createTestAesKey() { - byte[] aesKey = new byte[32]; - int i; - for (i = 0; i < 32; i++) { - aesKey[i] = 1; - } - - return aesKey; - } - - private String createRandomContentKeyId() { - UUID uuid = UUID.randomUUID(); - String randomContentKey = String.format("nb:kid:UUID:%s", uuid); - return randomContentKey; - } - - private void verifyInfosEqual(String message, ContentKeyInfo expected, ContentKeyInfo actual) { - verifyContentKeyProperties(message, expected.getId(), expected.getContentKeyType(), - expected.getEncryptedContentKey(), expected.getName(), expected.getProtectionKeyId(), - expected.getProtectionKeyType(), expected.getChecksum(), actual); - } - - private void verifyContentKeyProperties(String message, String id, ContentKeyType contentKeyType, - String encryptedContentKey, String name, String protectionKeyId, ProtectionKeyType protectionKeyType, - String checksum, ContentKeyInfo actual) { - assertNotNull(message, actual); - assertEquals(message + " Id", id, actual.getId()); - assertEquals(message + " ContentKeyType", contentKeyType, actual.getContentKeyType()); - assertEquals(message + " EncryptedContentKey", encryptedContentKey, actual.getEncryptedContentKey()); - assertEquals(message + " Name", name, actual.getName()); - assertEquals(message + " ProtectionKeyId", protectionKeyId, actual.getProtectionKeyId()); - assertEquals(message + " ProtectionKeyType", protectionKeyType, actual.getProtectionKeyType()); - assertEquals(message + " Checksum", checksum, actual.getChecksum()); - } - - @BeforeClass - public static void Setup() { - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - } - - @Test - public void canCreateContentKey() throws Exception { - // Arrange - String testCanCreateContentKeyId = createRandomContentKeyId(); - String testCanCreateContentKeyName = testContentKeyPrefix + "testCanCreateContentKey"; - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(testContentKeyType)); - - // Act - ContentKeyInfo contentKeyInfo = service.create(ContentKey - .create(testCanCreateContentKeyId, testContentKeyType, testEncryptedContentKey) - .setName(testCanCreateContentKeyName).setProtectionKeyId(protectionKeyId)); - - // Assert - verifyContentKeyProperties("ContentKey", testCanCreateContentKeyId, testContentKeyType, - testEncryptedContentKey, testCanCreateContentKeyName, protectionKeyId, ProtectionKeyType.fromCode(0), - "", contentKeyInfo); - } - - @Test - public void canGetSingleContentKeyById() throws Exception { - // Arrange - String expectedName = testContentKeyPrefix + "GetOne"; - String testGetSingleContentKeyByIdId = createRandomContentKeyId(); - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(testContentKeyType)); - ContentKeyInfo ContentKeyToGet = service.create(ContentKey - .create(testGetSingleContentKeyByIdId, testContentKeyType, testEncryptedContentKey) - .setName(expectedName).setProtectionKeyId(protectionKeyId)); - - // Act - ContentKeyInfo retrievedContentKeyInfo = service.get(ContentKey.get(ContentKeyToGet.getId())); - - // Assert - assertEquals(ContentKeyToGet.getId(), retrievedContentKeyInfo.getId()); - verifyContentKeyProperties("ContentKey", testGetSingleContentKeyByIdId, testContentKeyType, - testEncryptedContentKey, expectedName, protectionKeyId, ProtectionKeyType.fromCode(0), "", - retrievedContentKeyInfo); - } - - @Test - public void cannotGetSingleContentKeyByInvalidId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.get(ContentKey.get(invalidId)); - } - - @Test - public void canRetrieveListOfContentKeys() throws Exception { - // Arrange - String[] ContentKeyNames = new String[] { testContentKeyPrefix + "ListOne", testContentKeyPrefix + "ListTwo" }; - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(testContentKeyType)); - - List expectedContentKeys = new ArrayList(); - for (int i = 0; i < ContentKeyNames.length; i++) { - String testCanRetrieveListOfContentKeysId = createRandomContentKeyId(); - ContentKeyInfo contentKey = service.create(ContentKey.create(testCanRetrieveListOfContentKeysId, - testContentKeyType, testEncryptedContentKey).setProtectionKeyId(protectionKeyId)); - expectedContentKeys.add(contentKey); - } - - // Act - List actualContentKeys = service.list(ContentKey.list()); - - // Assert - verifyListResultContains("listContentKeyss", expectedContentKeys, actualContentKeys, new ComponentDelegate() { - @Override - public void verifyEquals(String message, Object expected, Object actual) { - verifyInfosEqual(message, (ContentKeyInfo) expected, (ContentKeyInfo) actual); - } - }); - } - - @Test - public void canUseQueryParametersWhenListingContentKeys() throws Exception { - // Arrange - String[] ContentKeyNames = new String[] { testContentKeyPrefix + "ListThree", - testContentKeyPrefix + "ListFour", testContentKeyPrefix + "ListFive", testContentKeyPrefix + "ListSix", - testContentKeyPrefix + "ListSeven" }; - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(testContentKeyType)); - - List expectedContentKeys = new ArrayList(); - for (int i = 0; i < ContentKeyNames.length; i++) { - ContentKeyInfo contentKeyInfo = service.create(ContentKey.create(createRandomContentKeyId(), - testContentKeyType, testEncryptedContentKey).setProtectionKeyId(protectionKeyId)); - expectedContentKeys.add(contentKeyInfo); - } - - // Act - List actualContentKeys = service.list(ContentKey.list().setTop(2)); - - // Assert - assertEquals(2, actualContentKeys.size()); - } - - @Test - public void canDeleteContentKeyById() throws Exception { - // Arrange - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(testContentKeyType)); - String contentKeyName = testContentKeyPrefix + "ToDelete"; - ContentKeyInfo contentKeyToDelete = service.create(ContentKey - .create(createRandomContentKeyId(), testContentKeyType, testEncryptedContentKey) - .setName(contentKeyName).setProtectionKeyId(protectionKeyId)); - List listContentKeysResult = service.list(ContentKey.list()); - int ContentKeyCountBaseline = listContentKeysResult.size(); - - // Act - service.delete(ContentKey.delete(contentKeyToDelete.getId())); - - // Assert - listContentKeysResult = service.list(ContentKey.list()); - assertEquals("listPoliciesResult.size", ContentKeyCountBaseline - 1, listContentKeysResult.size()); - - for (ContentKeyInfo contentKey : service.list(ContentKey.list())) { - assertFalse(contentKeyToDelete.getId().equals(contentKey.getId())); - } - - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(ContentKey.get(contentKeyToDelete.getId())); - } - - @Test - public void cannotDeleteContentKeyByInvalidId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.delete(ContentKey.delete(invalidId)); - } - - @Test - public void cannotDeleteContentKeyByNonexistId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.delete(ContentKey.delete(validButNonexistContentKeyId)); - } - - @Test - public void rebindContentKeyNoX509CertificateSuccess() throws Exception { - - ContentKeyInfo contentKeyInfo = createValidTestContentKey("rebindContentKeyNoX509Success"); - - String contentKey = service.action(ContentKey.rebind(contentKeyInfo.getId())); - assertNotNull(contentKey); - - } - - @Test - public void rebindInvalidContentKeyNoX509CertificateFail() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - ContentKeyInfo contentKeyInfo = createTestContentKey("rebindInvalidContentKeyNoX509Fail"); - - service.action(ContentKey.rebind(contentKeyInfo.getId())); - - } - - @Test - public void rebindContentKeyWithX509CertficateSuccess() throws Exception { - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - byte[] aesKey = createTestAesKey(); - ContentKeyInfo contentKeyInfo = createValidTestContentKeyWithAesKey("rebindContentKeyWithX509Success", aesKey); - URL serverCertificateUri = getClass().getResource("/certificate/server.crt"); - X509Certificate x509Certificate = EncryptionHelper.loadX509Certificate(URLDecoder.decode( - serverCertificateUri.getFile(), "UTF-8")); - URL serverPrivateKey = getClass().getResource("/certificate/server.der"); - PrivateKey privateKey = EncryptionHelper.getPrivateKey(URLDecoder.decode(serverPrivateKey.getFile(), "UTF-8")); - - String rebindedContentKey = service.action(ContentKey.rebind(contentKeyInfo.getId(), - URLEncoder.encode(Base64.encode(x509Certificate.getEncoded()), "UTF-8"))); - byte[] decryptedAesKey = EncryptionHelper.decryptSymmetricKey(rebindedContentKey, privateKey); - assertByteArrayEquals(aesKey, decryptedAesKey); - } - - @Test - public void rebindContentKeyWithIncorrectContentKeyIdFailed() throws ServiceException { - expectedException.expect(ServiceException.class); - service.action(ContentKey.rebind("invalidContentKeyId")); - } - - @Test - public void rebindContentKeyWithIncorrectX509CertificateFailed() throws ServiceException { - expectedException.expect(ServiceException.class); - ContentKeyInfo contentKeyInfo = createTestContentKey("rebindContentKeyWithIncorrectX509CertficateFailed"); - - service.action(ContentKey.rebind(contentKeyInfo.getId(), "InvalidX509Certificate")); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EncryptionIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EncryptionIntegrationTest.java deleted file mode 100644 index 176f40f00514b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/EncryptionIntegrationTest.java +++ /dev/null @@ -1,327 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.net.URL; -import java.net.URLDecoder; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; -import java.util.UUID; - -import javax.crypto.Cipher; - -import junit.framework.Assert; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.media.models.AccessPolicy; -import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; -import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetFile; -import com.microsoft.windowsazure.services.media.models.AssetFileInfo; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.AssetOption; -import com.microsoft.windowsazure.services.media.models.ContentKey; -import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; -import com.microsoft.windowsazure.services.media.models.ContentKeyType; -import com.microsoft.windowsazure.services.media.models.Job; -import com.microsoft.windowsazure.services.media.models.JobInfo; -import com.microsoft.windowsazure.services.media.models.JobState; -import com.microsoft.windowsazure.services.media.models.LinkInfo; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.Locator; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; -import com.microsoft.windowsazure.services.media.models.LocatorType; -import com.microsoft.windowsazure.services.media.models.MediaProcessor; -import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo; -import com.microsoft.windowsazure.services.media.models.ProtectionKey; -import com.microsoft.windowsazure.services.media.models.Task; -import com.microsoft.windowsazure.services.media.models.TaskInfo; -import com.microsoft.windowsazure.services.media.models.TaskState; - -public class EncryptionIntegrationTest extends IntegrationTestBase { - private final String storageDecryptionProcessor = "Storage Decryption"; - - private void assertByteArrayEquals(byte[] source, byte[] target) { - assertEquals(source.length, target.length); - for (int i = 0; i < source.length; i++) { - assertEquals(source[i], target[i]); - } - } - - @BeforeClass - public static void Setup() { - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - } - - @Test - public void uploadAesProtectedAssetAndDownloadSuccess() throws Exception { - // Arrange - if (!EncryptionHelper.canUseStrongCrypto()) { - Assert.fail("JVM does not support the required encryption"); - } - - // Media Services requires 256-bit (32-byte) keys and - // 128-bit (16-byte) initialization vectors (IV) for AES encryption, - // and also requires that only the first 8 bytes of the IV is filled. - Random random = new Random(); - byte[] aesKey = new byte[32]; - random.nextBytes(aesKey); - byte[] effectiveIv = new byte[8]; - random.nextBytes(effectiveIv); - byte[] iv = new byte[16]; - System.arraycopy(effectiveIv, 0, iv, 0, effectiveIv.length); - - InputStream mpeg4H264InputStream = getClass().getResourceAsStream("/media/MPEG4-H264.mp4"); - InputStream encryptedContent = EncryptionHelper.encryptFile(mpeg4H264InputStream, aesKey, iv); - int durationInMinutes = 10; - - // Act - AssetInfo assetInfo = service.create(Asset.create().setName(testAssetPrefix + "uploadAesProtectedAssetSuccess") - .setOptions(AssetOption.StorageEncrypted)); - WritableBlobContainerContract blobWriter = getBlobWriter(assetInfo.getId(), durationInMinutes); - - // gets the public key for storage encryption. - String contentKeyId = createContentKey(aesKey); - - // link the content key with the asset. - service.action(Asset.linkContentKey(assetInfo.getId(), contentKeyId)); - - // upload the encrypted file to the server. - uploadEncryptedAssetFile(assetInfo, blobWriter, "MPEG4-H264.mp4", encryptedContent, contentKeyId, iv); - - // submit and execute the decoding job. - JobInfo jobInfo = decodeAsset(testJobPrefix + "uploadAesProtectedAssetSuccess", assetInfo.getId()); - - // assert - LinkInfo taskLinkInfo = jobInfo.getTasksLink(); - List taskInfos = service.list(Task.list(taskLinkInfo)); - for (TaskInfo taskInfo : taskInfos) { - assertEquals(TaskState.Completed, taskInfo.getState()); - ListResult outputs = service.list(Asset.list(taskInfo.getOutputAssetsLink())); - assertEquals(1, outputs.size()); - } - assertEquals(JobState.Finished, jobInfo.getState()); - - // Verify that the contents match - InputStream expected = getClass().getResourceAsStream("/media/MPEG4-H264.mp4"); - - ListResult outputAssets = service.list(Asset.list(jobInfo.getOutputAssetsLink())); - assertEquals(1, outputAssets.size()); - AssetInfo outputAsset = outputAssets.get(0); - ListResult assetFiles = service.list(AssetFile.list(assetInfo.getAssetFilesLink())); - assertEquals(1, assetFiles.size()); - AssetFileInfo outputFile = assetFiles.get(0); - - InputStream actual = getFileContents(outputAsset.getId(), outputFile.getName(), durationInMinutes); - assertStreamsEqual(expected, actual); - } - - @Test - public void testEncryptedContentCanBeDecrypted() throws Exception { - byte[] aesKey = new byte[32]; - for (int i = 0; i < 32; i++) { - aesKey[i] = 1; - } - URL serverCertificateUri = getClass().getResource("/certificate/server.crt"); - X509Certificate x509Certificate = EncryptionHelper.loadX509Certificate(URLDecoder.decode( - serverCertificateUri.getFile(), "UTF-8")); - URL serverPrivateKey = getClass().getResource("/certificate/server.der"); - PrivateKey privateKey = EncryptionHelper.getPrivateKey(URLDecoder.decode(serverPrivateKey.getFile(), "UTF-8")); - byte[] encryptedAesKey = EncryptionHelper.encryptSymmetricKey(x509Certificate, aesKey); - byte[] decryptedAesKey = EncryptionHelper.decryptSymmetricKey(encryptedAesKey, privateKey); - - assertByteArrayEquals(aesKey, decryptedAesKey); - } - - @Test - public void testEncryptedContentCanBeDecryptedUsingPreGeneratedKeyPair() throws Exception { - byte[] input = "abc".getBytes(); - Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC"); - SecureRandom random = new SecureRandom(); - URL serverCertificateUri = getClass().getResource("/certificate/server.crt"); - X509Certificate x509Certificate = EncryptionHelper.loadX509Certificate(URLDecoder.decode( - serverCertificateUri.getFile(), "UTF-8")); - URL serverPrivateKey = getClass().getResource("/certificate/server.der"); - PrivateKey privateKey = EncryptionHelper.getPrivateKey(URLDecoder.decode(serverPrivateKey.getFile(), "UTF-8")); - Key pubKey = x509Certificate.getPublicKey(); - cipher.init(Cipher.ENCRYPT_MODE, pubKey, random); - byte[] cipherText = cipher.doFinal(input); - cipher.init(Cipher.DECRYPT_MODE, privateKey); - - //Act - byte[] plainText = cipher.doFinal(cipherText); - - // Assert - assertByteArrayEquals(input, plainText); - } - - @Test - public void testEncryptionDecryptionFunctionUsingGeneratedKeyPair() throws Exception { - // Arrange - byte[] input = "abc".getBytes(); - Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC"); - SecureRandom random = new SecureRandom(); - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC"); - generator.initialize(386, random); - KeyPair pair = generator.generateKeyPair(); - Key pubKey = pair.getPublic(); - Key privKey = pair.getPrivate(); - cipher.init(Cipher.ENCRYPT_MODE, pubKey, random); - byte[] cipherText = cipher.doFinal(input); - cipher.init(Cipher.DECRYPT_MODE, privKey); - - //Act - byte[] plainText = cipher.doFinal(cipherText); - - // Assert - assertByteArrayEquals(input, plainText); - } - - private JobInfo decodeAsset(String name, String inputAssetId) throws ServiceException, InterruptedException { - MediaProcessorInfo mediaProcessorInfo = service.list( - MediaProcessor.list().set("$filter", "Name eq '" + storageDecryptionProcessor + "'")).get(0); - - String taskBody = "" - + "JobInputAsset(0)JobOutputAsset(0)"; - JobInfo jobInfo = service.create(Job.create().addInputMediaAsset(inputAssetId) - .addTaskCreator(Task.create(mediaProcessorInfo.getId(), taskBody).setName(name))); - - JobInfo currentJobInfo = jobInfo; - int retryCounter = 0; - while (currentJobInfo.getState().getCode() < 3 && retryCounter < 30) { - Thread.sleep(10000); - currentJobInfo = service.get(Job.get(jobInfo.getId())); - retryCounter++; - } - return currentJobInfo; - } - - private String createContentKey(byte[] aesKey) throws ServiceException, Exception { - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(ContentKeyType.StorageEncryption)); - String protectionKey = service.action(ProtectionKey.getProtectionKey(protectionKeyId)); - - String contentKeyIdUuid = UUID.randomUUID().toString(); - String contentKeyId = String.format("nb:kid:UUID:%s", contentKeyIdUuid); - - byte[] encryptedContentKey = EncryptionHelper.encryptSymmetricKey(protectionKey, aesKey); - String encryptedContentKeyString = Base64.encode(encryptedContentKey); - String checksum = EncryptionHelper.calculateContentKeyChecksum(contentKeyIdUuid, aesKey); - - ContentKeyInfo contentKeyInfo = service.create(ContentKey - .create(contentKeyId, ContentKeyType.StorageEncryption, encryptedContentKeyString) - .setChecksum(checksum).setProtectionKeyId(protectionKeyId)); - return contentKeyInfo.getId(); - } - - private void uploadEncryptedAssetFile(AssetInfo asset, WritableBlobContainerContract blobWriter, String blobName, - InputStream blobContent, String encryptionKeyId, byte[] iv) throws ServiceException { - blobWriter.createBlockBlob(blobName, blobContent); - service.action(AssetFile.createFileInfos(asset.getId())); - ListResult files = service.list(AssetFile.list(asset.getAssetFilesLink()).set("$filter", - "Name eq '" + blobName + "'")); - assertEquals(1, files.size()); - AssetFileInfo file = files.get(0); - byte[] sub = new byte[9]; - // Offset bytes to ensure that the sign-bit is not set. - // Media Services expects unsigned Int64 values. - System.arraycopy(iv, 0, sub, 1, 8); - BigInteger longIv = new BigInteger(sub); - String initializationVector = longIv.toString(); - - service.update(AssetFile.update(file.getId()).setIsEncrypted(true).setEncryptionKeyId(encryptionKeyId) - .setEncryptionScheme("StorageEncryption").setEncryptionVersion("1.0") - .setInitializationVector(initializationVector)); - } - - private WritableBlobContainerContract getBlobWriter(String assetId, int durationInMinutes) throws ServiceException { - AccessPolicyInfo accessPolicyInfo = service.create(AccessPolicy.create(testPolicyPrefix - + "uploadAesPortectedAssetSuccess", durationInMinutes, EnumSet.of(AccessPolicyPermission.WRITE))); - - // creates locator for the input media asset - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfo.getId(), assetId, LocatorType.SAS)); - WritableBlobContainerContract blobWriter = service.createBlobWriter(locatorInfo); - return blobWriter; - } - - private InputStream getFileContents(String assetId, String fileName, int availabilityWindowInMinutes) - throws ServiceException, InterruptedException, IOException { - AccessPolicyInfo readAP = service.create(AccessPolicy.create(testPolicyPrefix + "tempAccessPolicy", - availabilityWindowInMinutes, EnumSet.of(AccessPolicyPermission.READ))); - LocatorInfo readLocator = service.create(Locator.create(readAP.getId(), assetId, LocatorType.SAS)); - URL file = new URL(readLocator.getBaseUri() + "/" + fileName + readLocator.getContentAccessToken()); - - // There can be a delay before a new read locator is applied for the asset files. - InputStream reader = null; - for (int counter = 0; true; counter++) { - try { - reader = file.openConnection().getInputStream(); - break; - } - catch (IOException e) { - System.out.println("Got error, wait a bit and try again"); - if (counter < 6) { - Thread.sleep(10000); - } - else { - // No more retries. - throw e; - } - } - } - - return reader; - } - - private void assertStreamsEqual(InputStream inputStream1, InputStream inputStream2) throws IOException { - byte[] buffer1 = new byte[1024]; - byte[] buffer2 = new byte[1024]; - try { - while (true) { - int n1 = inputStream1.read(buffer1); - int n2 = inputStream2.read(buffer2); - assertEquals("number of bytes read from streams", n1, n2); - if (n1 == -1) { - break; - } - for (int i = 0; i < n1; i++) { - assertEquals("byte " + i + " read from streams", buffer1[i], buffer2[i]); - } - } - } - finally { - inputStream1.close(); - inputStream2.close(); - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/IntegrationTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/IntegrationTestBase.java deleted file mode 100644 index c64c90dd6fe8e..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/IntegrationTestBase.java +++ /dev/null @@ -1,360 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.EnumSet; -import java.util.List; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.rules.ExpectedException; - -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.AccessPolicy; -import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; -import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetFile; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.ContentKey; -import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; -import com.microsoft.windowsazure.services.media.models.Job; -import com.microsoft.windowsazure.services.media.models.JobInfo; -import com.microsoft.windowsazure.services.media.models.JobState; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.Locator; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; -import com.microsoft.windowsazure.services.media.models.LocatorType; -import com.microsoft.windowsazure.services.queue.QueueConfiguration; -import com.microsoft.windowsazure.services.queue.QueueContract; -import com.microsoft.windowsazure.services.queue.QueueService; -import com.microsoft.windowsazure.services.queue.models.ListQueuesResult; -import com.microsoft.windowsazure.services.queue.models.ListQueuesResult.Queue; - -public abstract class IntegrationTestBase { - protected static MediaContract service; - protected static QueueContract queueService; - protected static Configuration config; - - protected static final String testAssetPrefix = "testAsset"; - protected static final String testPolicyPrefix = "testPolicy"; - protected static final String testContentKeyPrefix = "testContentKey"; - protected static final String testJobPrefix = "testJobPrefix"; - protected static final String testQueuePrefix = "testqueueprefix"; - - protected static final String validButNonexistAssetId = "nb:cid:UUID:0239f11f-2d36-4e5f-aa35-44d58ccc0973"; - protected static final String validButNonexistAccessPolicyId = "nb:pid:UUID:38dcb3a0-ef64-4ad0-bbb5-67a14c6df2f7"; - protected static final String validButNonexistLocatorId = "nb:lid:UUID:92a70402-fca9-4aa3-80d7-d4de3792a27a"; - - protected static final String MEDIA_ENCODER_MEDIA_PROCESSOR_2_2_0_0_ID = "nb:mpid:UUID:70bdc2c3-ebf4-42a9-8542-5afc1e55d217"; - - protected static final String invalidId = "notAValidId"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @BeforeClass - public static void setup() throws Exception { - config = Configuration.getInstance(); - overrideWithEnv(config, MediaConfiguration.URI); - overrideWithEnv(config, MediaConfiguration.OAUTH_URI); - overrideWithEnv(config, MediaConfiguration.OAUTH_CLIENT_ID); - overrideWithEnv(config, MediaConfiguration.OAUTH_CLIENT_SECRET); - overrideWithEnv(config, MediaConfiguration.OAUTH_SCOPE); - - overrideWithEnv(config, QueueConfiguration.ACCOUNT_KEY, "media.queue.account.key"); - overrideWithEnv(config, QueueConfiguration.ACCOUNT_NAME, "media.queue.account.name"); - overrideWithEnv(config, QueueConfiguration.URI, "media.queue.uri"); - - service = MediaService.create(config); - queueService = QueueService.create(config); - - cleanupEnvironment(); - } - - protected static void overrideWithEnv(Configuration config, String key) { - String value = System.getenv(key); - if (value == null) - return; - - config.setProperty(key, value); - } - - protected static void overrideWithEnv(Configuration config, String key, String enviromentKey) { - String value = System.getenv(enviromentKey); - if (value == null) - return; - - config.setProperty(key, value); - } - - @AfterClass - public static void cleanup() throws Exception { - cleanupEnvironment(); - } - - protected static void cleanupEnvironment() { - removeAllTestLocators(); - removeAllTestAssets(); - removeAllTestAccessPolicies(); - removeAllTestJobs(); - removeAllTestContentKeys(); - removeAllTestQueues(); - } - - private static void removeAllTestQueues() { - try { - ListQueuesResult listQueueResult = queueService.listQueues(); - for (Queue queue : listQueueResult.getQueues()) { - try { - queueService.deleteQueue(queue.getName()); - } - catch (Exception e) { - e.printStackTrace(); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private static void removeAllTestContentKeys() { - try { - List contentKeyInfos = service.list(ContentKey.list()); - - for (ContentKeyInfo contentKeyInfo : contentKeyInfos) { - try { - service.delete(ContentKey.delete(contentKeyInfo.getId())); - } - catch (Exception e) { - e.printStackTrace(); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private static void removeAllTestAccessPolicies() { - try { - List policies = service.list(AccessPolicy.list()); - - for (AccessPolicyInfo policy : policies) { - if (policy.getName().startsWith(testPolicyPrefix)) { - service.delete(AccessPolicy.delete(policy.getId())); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private static void removeAllTestAssets() { - try { - List listAssetsResult = service.list(Asset.list()); - for (AssetInfo assetInfo : listAssetsResult) { - try { - if (assetInfo.getName().startsWith(testAssetPrefix)) { - service.delete(Asset.delete(assetInfo.getId())); - } - else if (assetInfo.getName().startsWith("JobOutputAsset(") - && assetInfo.getName().contains(testJobPrefix)) { - // Delete the temp assets associated with Job results. - service.delete(Asset.delete(assetInfo.getId())); - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private static void removeAllTestLocators() { - try { - ListResult listLocatorsResult = service.list(Locator.list()); - for (LocatorInfo locatorInfo : listLocatorsResult) { - AssetInfo ai = service.get(Asset.get(locatorInfo.getAssetId())); - if (ai.getName().startsWith(testAssetPrefix)) { - service.delete(Locator.delete(locatorInfo.getId())); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private static void removeAllTestJobs() { - try { - ListResult jobs = service.list(Job.list()); - for (JobInfo job : jobs) { - if (job.getName().startsWith(testJobPrefix)) { - // Job can't be deleted when it's state is - // canceling, scheduled,queued or processing - try { - if (isJobBusy(job.getState())) { - service.action(Job.cancel(job.getId())); - job = service.get(Job.get(job.getId())); - } - - int retryCounter = 0; - while (isJobBusy(job.getState()) && retryCounter < 10) { - Thread.sleep(2000); - job = service.get(Job.get(job.getId())); - retryCounter++; - } - - if (!isJobBusy(job.getState())) { - service.delete(Job.delete(job.getId())); - } - else { - // Not much to do so except wait. - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private static boolean isJobBusy(JobState state) { - return state == JobState.Canceling || state == JobState.Scheduled || state == JobState.Queued - || state == JobState.Processing; - } - - interface ComponentDelegate { - void verifyEquals(String message, Object expected, Object actual); - } - - protected static AssetInfo setupAssetWithFile() throws ServiceException { - String name = UUID.randomUUID().toString(); - String testBlobName = "test" + name + ".bin"; - AssetInfo assetInfo = service.create(Asset.create().setName(testAssetPrefix + name)); - - AccessPolicyInfo accessPolicyInfo = service.create(AccessPolicy.create(testPolicyPrefix + name, 10, - EnumSet.of(AccessPolicyPermission.WRITE))); - LocatorInfo locator = createLocator(accessPolicyInfo, assetInfo, 5); - WritableBlobContainerContract blobWriter = service.createBlobWriter(locator); - InputStream blobContent = new ByteArrayInputStream(new byte[] { 4, 8, 15, 16, 23, 42 }); - blobWriter.createBlockBlob(testBlobName, blobContent); - - service.action(AssetFile.createFileInfos(assetInfo.getId())); - - return assetInfo; - } - - protected static LocatorInfo createLocator(AccessPolicyInfo accessPolicy, AssetInfo asset, int startDeltaMinutes) - throws ServiceException { - - Date now = new Date(); - Date start = new Date(now.getTime() - (startDeltaMinutes * 60 * 1000)); - - return service.create(Locator.create(accessPolicy.getId(), asset.getId(), LocatorType.SAS).setStartDateTime( - start)); - } - - protected void verifyListResultContains(List expectedInfos, Collection actualInfos, - ComponentDelegate delegate) { - verifyListResultContains("", expectedInfos, actualInfos, delegate); - } - - protected void verifyListResultContains(String message, List expectedInfos, Collection actualInfos, - ComponentDelegate delegate) { - assertNotNull(message + ": actualInfos", actualInfos); - assertTrue(message + ": actual size should be same size or larger than expected size", - actualInfos.size() >= expectedInfos.size()); - - List orderedAndFilteredActualInfo = new ArrayList(); - try { - for (T expectedInfo : expectedInfos) { - Method getId = expectedInfo.getClass().getMethod("getId"); - String expectedId = (String) getId.invoke(expectedInfo); - for (T actualInfo : actualInfos) { - if (((String) getId.invoke(actualInfo)).equals(expectedId)) { - orderedAndFilteredActualInfo.add(actualInfo); - break; - } - } - } - } - catch (Exception e) { - // Don't worry about problems here. - e.printStackTrace(); - } - - assertEquals(message + ": actual filtered size should be same as expected size", expectedInfos.size(), - orderedAndFilteredActualInfo.size()); - - if (delegate != null) { - for (int i = 0; i < expectedInfos.size(); i++) { - delegate.verifyEquals(message + ": orderedAndFilteredActualInfo " + i, expectedInfos.get(i), - orderedAndFilteredActualInfo.get(i)); - } - } - } - - protected void assertEqualsNullEmpty(String message, String expected, String actual) { - if ((expected == null || expected.length() == 0) && (actual == null || actual.length() == 0)) { - // both nullOrEmpty, so match. - } - else { - assertEquals(message, expected, actual); - } - } - - protected void assertDateApproxEquals(Date expected, Date actual) { - assertDateApproxEquals("", expected, actual); - } - - protected void assertDateApproxEquals(String message, Date expected, Date actual) { - // Default allows for a 30 seconds difference in dates, for clock skew, network delays, etc. - long deltaInMilliseconds = 30000; - - if (expected == null || actual == null) { - assertEquals(message, expected, actual); - } - else { - long diffInMilliseconds = Math.abs(expected.getTime() - actual.getTime()); - - if (diffInMilliseconds > deltaInMilliseconds) { - assertEquals(message, expected, actual); - } - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java deleted file mode 100644 index c835af0634cf6..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/JobIntegrationTest.java +++ /dev/null @@ -1,431 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.EndPointType; -import com.microsoft.windowsazure.services.media.models.ErrorDetail; -import com.microsoft.windowsazure.services.media.models.Job; -import com.microsoft.windowsazure.services.media.models.Job.Creator; -import com.microsoft.windowsazure.services.media.models.JobInfo; -import com.microsoft.windowsazure.services.media.models.JobNotificationSubscription; -import com.microsoft.windowsazure.services.media.models.JobState; -import com.microsoft.windowsazure.services.media.models.LinkInfo; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.NotificationEndPoint; -import com.microsoft.windowsazure.services.media.models.NotificationEndPointInfo; -import com.microsoft.windowsazure.services.media.models.TargetJobState; -import com.microsoft.windowsazure.services.media.models.Task; -import com.microsoft.windowsazure.services.media.models.Task.CreateBatchOperation; -import com.microsoft.windowsazure.services.media.models.TaskHistoricalEvent; -import com.microsoft.windowsazure.services.media.models.TaskInfo; -import com.microsoft.windowsazure.services.queue.models.PeekMessagesResult.QueueMessage; - -public class JobIntegrationTest extends IntegrationTestBase { - - private static AssetInfo assetInfo; - - private void verifyJobInfoEqual(String message, JobInfo expected, JobInfo actual) throws ServiceException { - verifyJobProperties(message, expected.getName(), expected.getPriority(), expected.getRunningDuration(), - expected.getState(), expected.getTemplateId(), expected.getCreated(), expected.getLastModified(), - expected.getStartTime(), expected.getEndTime(), null, actual); - } - - private void verifyJobProperties(String message, String testName, Integer priority, double runningDuration, - JobState state, String templateId, Date created, Date lastModified, Date startTime, Date endTime, - Integer expectedTaskCount, JobInfo actualJob) throws ServiceException { - assertNotNull(message, actualJob); - - assertNotNull(message + "Id", actualJob.getId()); - - assertEquals(message + " Name", testName, actualJob.getName()); - // comment out due to issue 464 - // assertEquals(message + " Priority", priority, actualJob.getPriority()); - assertEquals(message + " RunningDuration", runningDuration, actualJob.getRunningDuration(), 0.001); - assertEquals(message + " State", state, actualJob.getState()); - assertEqualsNullEmpty(message + " TemplateId", templateId, actualJob.getTemplateId()); - - assertDateApproxEquals(message + " Created", created, actualJob.getCreated()); - assertDateApproxEquals(message + " LastModified", lastModified, actualJob.getLastModified()); - assertDateApproxEquals(message + " StartTime", startTime, actualJob.getStartTime()); - assertDateApproxEquals(message + " EndTime", endTime, actualJob.getEndTime()); - - if (expectedTaskCount != null) { - LinkInfo tasksLink = actualJob.getTasksLink(); - ListResult actualTasks = service.list(Task.list(tasksLink)); - assertEquals(message + " tasks size", expectedTaskCount.intValue(), actualTasks.size()); - } - } - - private JobNotificationSubscription getJobNotificationSubscription(String jobNotificationSubscriptionId, - TargetJobState targetJobState) { - return new JobNotificationSubscription(jobNotificationSubscriptionId, targetJobState); - } - - private JobInfo createJob(String name) throws ServiceException { - return service.create(Job.create().setName(name).setPriority(3).addInputMediaAsset(assetInfo.getId()) - .addTaskCreator(getTaskCreator(0))); - } - - private CreateBatchOperation getTaskCreator(int outputAssetPosition) { - return Task - .create(MEDIA_ENCODER_MEDIA_PROCESSOR_2_2_0_0_ID, - "" + "JobInputAsset(0)" + "JobOutputAsset(" - + outputAssetPosition + ")" + "") - .setConfiguration("H.264 256k DSL CBR").setName("My encoding Task"); - } - - @BeforeClass - public static void setup() throws Exception { - IntegrationTestBase.setup(); - assetInfo = setupAssetWithFile(); - } - - @Test - public void createJobSuccess() throws ServiceException { - // Arrange - String name = testJobPrefix + "createJobSuccess"; - int priority = 3; - double duration = 0.0; - JobState state = JobState.Queued; - String templateId = null; - Date created = new Date(); - Date lastModified = new Date(); - Date stateTime = null; - Date endTime = null; - - // Act - JobInfo actualJob = service.create(Job.create().setName(name).setPriority(priority) - .addInputMediaAsset(assetInfo.getId()).addTaskCreator(getTaskCreator(0))); - - // Assert - verifyJobProperties("actualJob", name, priority, duration, state, templateId, created, lastModified, stateTime, - endTime, 1, actualJob); - } - - @Test - public void createJobWithNotificationSuccess() throws ServiceException { - // Arrange - String name = testJobPrefix + "createJobWithNotificationSuccess"; - String queueName = testQueuePrefix + "createjobwithnotificationsuccess"; - int priority = 3; - double duration = 0.0; - JobState state = JobState.Queued; - String templateId = null; - Date created = new Date(); - Date lastModified = new Date(); - Date stateTime = null; - Date endTime = null; - - queueService.createQueue(queueName); - String notificationEndPointName = UUID.randomUUID().toString(); - - service.create(NotificationEndPoint.create(notificationEndPointName, EndPointType.AzureQueue, queueName)); - ListResult listNotificationEndPointInfos = service.list(NotificationEndPoint.list()); - String notificationEndPointId = null; - - for (NotificationEndPointInfo notificationEndPointInfo : listNotificationEndPointInfos) { - if (notificationEndPointInfo.getName().equals(notificationEndPointName)) { - notificationEndPointId = notificationEndPointInfo.getId(); - } - } - - JobNotificationSubscription jobNotificationSubcription = getJobNotificationSubscription(notificationEndPointId, - TargetJobState.All); - - Creator creator = Job.create().setName(name).setPriority(priority).addInputMediaAsset(assetInfo.getId()) - .addTaskCreator(getTaskCreator(0)).addJobNotificationSubscription(jobNotificationSubcription); - - // Act - JobInfo actualJob = service.create(creator); - - // Assert - verifyJobProperties("actualJob", name, priority, duration, state, templateId, created, lastModified, stateTime, - endTime, 1, actualJob); - List queueMessages = queueService.peekMessages(queueName).getQueueMessages(); - assertEquals(1, queueMessages.size()); - } - - @Test - public void createJobTwoTasksSuccess() throws ServiceException { - // Arrange - String name = testJobPrefix + "createJobSuccess"; - int priority = 3; - double duration = 0.0; - JobState state = JobState.Queued; - String templateId = null; - Date created = new Date(); - Date lastModified = new Date(); - Date stateTime = null; - Date endTime = null; - List tasks = new ArrayList(); - tasks.add(getTaskCreator(0)); - tasks.add(getTaskCreator(1)); - - // Act - JobInfo actualJob = service.create(Job.create().setName(name).setPriority(priority) - .addInputMediaAsset(assetInfo.getId()).addTaskCreator(tasks.get(0)).addTaskCreator(tasks.get(1))); - - // Assert - verifyJobProperties("actualJob", name, priority, duration, state, templateId, created, lastModified, stateTime, - endTime, 2, actualJob); - } - - @Test - public void getJobSuccess() throws ServiceException { - // Arrange - String name = testJobPrefix + "getJobSuccess"; - int priority = 3; - double duration = 0.0; - JobState state = JobState.Queued; - String templateId = null; - String jobId = createJob(name).getId(); - Date created = new Date(); - Date lastModified = new Date(); - Date stateTime = null; - Date endTime = null; - - // Act - JobInfo actualJob = service.get(Job.get(jobId)); - - // Assert - verifyJobProperties("actualJob", name, priority, duration, state, templateId, created, lastModified, stateTime, - endTime, 1, actualJob); - } - - @Test - public void getJobInvalidIdFailed() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.get(Job.get(invalidId)); - } - - @Test - public void listJobSuccess() throws ServiceException { - // Arrange - JobInfo jobInfo = createJob(testJobPrefix + "listJobSuccess"); - List jobInfos = new ArrayList(); - jobInfos.add(jobInfo); - ListResult expectedListJobsResult = new ListResult(jobInfos); - - // Act - ListResult actualListJobResult = service.list(Job.list()); - - // Assert - verifyListResultContains("listJobs", expectedListJobsResult, actualListJobResult, new ComponentDelegate() { - @Override - public void verifyEquals(String message, Object expected, Object actual) { - try { - verifyJobInfoEqual(message, (JobInfo) expected, (JobInfo) actual); - } - catch (ServiceException e) { - fail(e.getMessage()); - } - } - }); - } - - @Test - public void canListJobsWithOptions() throws ServiceException { - String[] assetNameSuffixes = new String[] { "A", "B", "C", "D" }; - List expectedJobs = new ArrayList(); - for (String suffix : assetNameSuffixes) { - JobInfo jobInfo = createJob(testJobPrefix + "assetListOptions" + suffix); - expectedJobs.add(jobInfo); - } - - ListResult listJobsResult = service.list(Job.list().setTop(2)); - - // Assert - assertEquals(2, listJobsResult.size()); - } - - @Test - public void cancelJobSuccess() throws ServiceException { - // Arrange - JobInfo jobInfo = createJob(testJobPrefix + "cancelJobSuccess"); - - // Act - service.action(Job.cancel(jobInfo.getId())); - - // Assert - JobInfo canceledJob = service.get(Job.get(jobInfo.getId())); - assertEquals(JobState.Canceling, canceledJob.getState()); - - } - - @Test - public void cancelJobFailedWithInvalidId() throws ServiceException { - // Arrange - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - - // Act - service.action(Job.cancel(invalidId)); - - // Assert - } - - @Test - public void deleteJobSuccess() throws ServiceException, InterruptedException { - // Arrange - JobInfo jobInfo = createJob(testJobPrefix + "deleteJobSuccess"); - service.action(Job.cancel(jobInfo.getId())); - JobInfo cancellingJobInfo = service.get(Job.get(jobInfo.getId())); - int retryCounter = 0; - while (cancellingJobInfo.getState() == JobState.Canceling && retryCounter < 10) { - Thread.sleep(2000); - cancellingJobInfo = service.get(Job.get(jobInfo.getId())); - retryCounter++; - } - - // Act - service.delete(Job.delete(jobInfo.getId())); - - // Assert - expectedException.expect(ServiceException.class); - service.get(Job.get(jobInfo.getId())); - - } - - @Test - public void deleteJobInvalidIdFail() throws ServiceException { - // Arrange - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - - // Act - service.delete(Job.delete(invalidId)); - - // Assert - } - - @Test - public void canGetInputOutputAssetsFromJob() throws Exception { - String name = testJobPrefix + "canGetInputOutputAssetsFromJob"; - int priority = 3; - - JobInfo actualJob = service.create(Job.create().setName(name).setPriority(priority) - .addInputMediaAsset(assetInfo.getId()).addTaskCreator(getTaskCreator(0))); - - ListResult inputs = service.list(Asset.list(actualJob.getInputAssetsLink())); - ListResult outputs = service.list(Asset.list(actualJob.getOutputAssetsLink())); - - assertEquals(1, inputs.size()); - assertEquals(assetInfo.getId(), inputs.get(0).getId()); - - assertEquals(1, outputs.size()); - assertTrue(outputs.get(0).getName().contains(name)); - } - - @Test - public void canGetTasksFromJob() throws Exception { - String name = testJobPrefix + "canGetTaskAssetsFromJob"; - int priority = 3; - - JobInfo actualJob = service.create(Job.create().setName(name).setPriority(priority) - .addInputMediaAsset(assetInfo.getId()).addTaskCreator(getTaskCreator(0))); - - ListResult tasks = service.list(Task.list(actualJob.getTasksLink())); - - assertEquals(1, tasks.size()); - } - - @Test - public void canGetErrorDetailsFromTask() throws Exception { - String name = testJobPrefix + "canGetErrorDetailsFromTask"; - - JobInfo actualJob = service.create(Job.create().setName(name).addInputMediaAsset(assetInfo.getId()) - .addTaskCreator(getTaskCreator(0))); - - JobInfo currentJobInfo = actualJob; - int retryCounter = 0; - while (currentJobInfo.getState().getCode() < 3 && retryCounter < 30) { - Thread.sleep(10000); - currentJobInfo = service.get(Job.get(actualJob.getId())); - retryCounter++; - } - - ListResult tasks = service.list(Task.list(actualJob.getTasksLink())); - TaskInfo taskInfo = tasks.get(0); - List errorDetails = taskInfo.getErrorDetails(); - - assertEquals(1, errorDetails.size()); - ErrorDetail errorDetail = errorDetails.get(0); - assertNotNull(errorDetail.getCode()); - assertNotNull(errorDetail.getMessage()); - } - - @Test - public void canGetInputOutputAssetsFromTask() throws Exception { - String name = testJobPrefix + "canGetInputOutputAssetsFromTask"; - int priority = 3; - - JobInfo actualJob = service.create(Job.create().setName(name).setPriority(priority) - .addInputMediaAsset(assetInfo.getId()).addTaskCreator(getTaskCreator(0))); - - ListResult tasks = service.list(Task.list(actualJob.getTasksLink())); - ListResult inputs = service.list(Asset.list(tasks.get(0).getInputAssetsLink())); - ListResult outputs = service.list(Asset.list(tasks.get(0).getOutputAssetsLink())); - - assertEquals(1, inputs.size()); - assertEquals(assetInfo.getId(), inputs.get(0).getId()); - - assertEquals(1, outputs.size()); - assertTrue(outputs.get(0).getName().contains(name)); - } - - @Test - public void canGetTaskHistoricalEventsFromTask() throws Exception { - // Arrange - String jobName = testJobPrefix + "canGetTaskHistoricalEventsFromTask"; - int priority = 3; - int retryCounter = 0; - - // Act - JobInfo actualJobInfo = service.create(Job.create().setName(jobName).setPriority(priority) - .addInputMediaAsset(assetInfo.getId()).addTaskCreator(getTaskCreator(0))); - - while (actualJobInfo.getState().getCode() < 3 && retryCounter < 30) { - Thread.sleep(10000); - actualJobInfo = service.get(Job.get(actualJobInfo.getId())); - retryCounter++; - } - ListResult tasks = service.list(Task.list(actualJobInfo.getTasksLink())); - TaskInfo taskInfo = tasks.get(0); - List historicalEvents = taskInfo.getHistoricalEvents(); - TaskHistoricalEvent historicalEvent = historicalEvents.get(0); - - // Assert - assertTrue(historicalEvents.size() >= 5); - assertNotNull(historicalEvent.getCode()); - assertNotNull(historicalEvent.getTimeStamp()); - assertNull(historicalEvent.getMessage()); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/LocatorIntegrationTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/LocatorIntegrationTests.java deleted file mode 100644 index e66162eef69f3..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/LocatorIntegrationTests.java +++ /dev/null @@ -1,315 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Date; -import java.util.EnumSet; -import java.util.List; -import java.util.UUID; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.AccessPolicy; -import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; -import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.Locator; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; -import com.microsoft.windowsazure.services.media.models.LocatorType; - -public class LocatorIntegrationTests extends IntegrationTestBase { - - private static AssetInfo assetInfo; - private static AccessPolicyInfo accessPolicyInfo; - private static AccessPolicyInfo accessPolicyInfoRead; - private static int minuteInMS = 60 * 1000; - private static int tenMinutesInMS = 10 * 60 * 1000; - - private void verifyLocatorInfosEqual(String message, LocatorInfo expected, LocatorInfo actual) { - verifyLocatorProperties(message, expected.getAccessPolicyId(), expected.getAssetId(), - expected.getLocatorType(), expected.getStartTime(), expected.getId(), expected.getPath(), actual); - } - - private void verifyLocatorProperties(String message, String accessPolicyId, String assetId, - LocatorType locatorType, Date startTime, LocatorInfo actualLocator) { - verifyLocatorProperties(message, accessPolicyId, assetId, locatorType, startTime, null, null, actualLocator); - } - - private void verifyLocatorProperties(String message, String accessPolicyId, String assetId, - LocatorType locatorType, Date startTime, String id, String path, LocatorInfo actualLocator) { - assertNotNull(message, actualLocator); - assertEquals(message + " accessPolicyId", accessPolicyId, actualLocator.getAccessPolicyId()); - assertEquals(message + " assetId", assetId, actualLocator.getAssetId()); - assertEquals(message + " locatorType", locatorType, actualLocator.getLocatorType()); - - assertDateApproxEquals(message + " startTime", startTime, actualLocator.getStartTime()); - - if (id == null) { - assertNotNull(message + " Id", actualLocator.getId()); - } - else { - assertEquals(message + " Id", id, actualLocator.getId()); - } - if (path == null) { - assertNotNull(message + " path", actualLocator.getPath()); - } - else { - assertEquals(message + " path", path, actualLocator.getPath()); - } - } - - @BeforeClass - public static void setup() throws Exception { - IntegrationTestBase.setup(); - accessPolicyInfo = service.create(AccessPolicy.create(testPolicyPrefix + "ForLocatorTest", 5, - EnumSet.of(AccessPolicyPermission.WRITE))); - accessPolicyInfoRead = service.create(AccessPolicy.create(testPolicyPrefix + "ForLocatorTestRead", 15, - EnumSet.of(AccessPolicyPermission.READ))); - } - - @Before - public void instanceSetup() throws Exception { - assetInfo = service.create(Asset.create().setName(testAssetPrefix + "ForLocatorTest")); - } - - @Test - public void createLocatorSuccess() throws ServiceException { - // Arrange - LocatorType locatorType = LocatorType.SAS; - - // Act - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfoRead.getId(), assetInfo.getId(), - locatorType)); - - // Assert - verifyLocatorProperties("locatorInfo", accessPolicyInfoRead.getId(), assetInfo.getId(), locatorType, null, - locatorInfo); - } - - @Test - public void createLocatorWithSpecifiedIdSuccess() throws ServiceException { - // Arrange - LocatorType locatorType = LocatorType.SAS; - - // Act - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfoRead.getId(), assetInfo.getId(), - locatorType).setId(String.format("nb:lid:UUID:%s", UUID.randomUUID().toString()))); - - // Assert - verifyLocatorProperties("locatorInfo", accessPolicyInfoRead.getId(), assetInfo.getId(), locatorType, null, - locatorInfo); - } - - @Test - public void createLocatorOptionsSetStartTimeSuccess() throws ServiceException { - // Arrange - Date expectedStartDateTime = new Date(); - expectedStartDateTime.setTime(expectedStartDateTime.getTime() + tenMinutesInMS); - LocatorType locatorType = LocatorType.SAS; - - // Act - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), - locatorType).setStartDateTime(expectedStartDateTime)); - - // Assert - verifyLocatorProperties("locatorInfo", accessPolicyInfo.getId(), assetInfo.getId(), locatorType, - expectedStartDateTime, locatorInfo); - } - - @Test - public void getLocatorSuccess() throws ServiceException { - // Arrange - LocatorType locatorType = LocatorType.SAS; - Date expectedStartDateTime = new Date(); - expectedStartDateTime.setTime(expectedStartDateTime.getTime() + tenMinutesInMS); - - LocatorInfo expectedLocatorInfo = service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), - locatorType).setStartDateTime(expectedStartDateTime)); - - // Act - LocatorInfo actualLocatorInfo = service.get(Locator.get(expectedLocatorInfo.getId())); - - // Assert - verifyLocatorInfosEqual("actualLocatorInfo", expectedLocatorInfo, actualLocatorInfo); - } - - @Test - public void getLocatorInvalidId() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.get(Locator.get(invalidId)); - } - - @Test - public void getLocatorNonexistId() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(Locator.get(validButNonexistLocatorId)); - } - - @Test - public void listLocatorsSuccess() throws ServiceException { - // Arrange - LocatorType locatorType = LocatorType.SAS; - List expectedLocators = new ArrayList(); - for (int i = 0; i < 2; i++) { - expectedLocators - .add(service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), locatorType))); - } - - // Act - ListResult listLocatorsResult = service.list(Locator.list()); - - // Assert - assertNotNull(listLocatorsResult); - verifyListResultContains("listLocatorsResult", expectedLocators, listLocatorsResult, new ComponentDelegate() { - @Override - public void verifyEquals(String message, Object expected, Object actual) { - verifyLocatorInfosEqual(message, (LocatorInfo) expected, (LocatorInfo) actual); - } - }); - } - - @Test - public void listLocatorsWithOptions() throws ServiceException { - List expectedLocators = new ArrayList(); - for (int i = 0; i < 5; i++) { - expectedLocators.add(service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), - LocatorType.SAS))); - } - - ListResult result = service.list(Locator - .list() - .setTop(3) - .set("$filter", - "(Id eq '" + expectedLocators.get(1).getId() + "') or (" + "Id eq '" - + expectedLocators.get(3).getId() + "')")); - - assertEquals(2, result.size()); - } - - @Test - public void updateLocatorSuccess() throws ServiceException { - // Arrange - LocatorType locatorType = LocatorType.OnDemandOrigin; - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfoRead.getId(), assetInfo.getId(), - locatorType)); - - Date startTime = new Date(); - startTime.setTime(startTime.getTime() - tenMinutesInMS); - - // Act - service.update(Locator.update(locatorInfo.getId()).setStartDateTime(startTime)); - LocatorInfo updatedLocatorInfo = service.get(Locator.get(locatorInfo.getId())); - - // Assert - Date expectedExpiration = new Date(); - expectedExpiration.setTime(startTime.getTime() + (long) accessPolicyInfoRead.getDurationInMinutes() - * minuteInMS); - - verifyLocatorProperties("updatedLocatorInfo", locatorInfo.getAccessPolicyId(), locatorInfo.getAssetId(), - locatorInfo.getLocatorType(), startTime, locatorInfo.getId(), locatorInfo.getPath(), updatedLocatorInfo); - } - - @Test - public void updateLocatorNoChangesSuccess() throws ServiceException { - // Arrange - LocatorType locatorType = LocatorType.OnDemandOrigin; - Date expirationDateTime = new Date(); - expirationDateTime.setTime(expirationDateTime.getTime() + tenMinutesInMS); - Date startTime = new Date(); - startTime.setTime(startTime.getTime() - tenMinutesInMS); - - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfoRead.getId(), assetInfo.getId(), - locatorType).setStartDateTime(startTime)); - - // Act - service.update(Locator.update(locatorInfo.getId())); - LocatorInfo updatedLocatorInfo = service.get(Locator.get(locatorInfo.getId())); - - // Assert - verifyLocatorInfosEqual("updatedLocatorInfo", locatorInfo, updatedLocatorInfo); - } - - @Test - public void deleteLocatorSuccess() throws ServiceException { - // Arrange - LocatorType locatorType = LocatorType.SAS; - LocatorInfo locatorInfo = service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), - locatorType)); - ListResult listLocatorsResult = service.list(Locator.list()); - int assetCountBaseline = listLocatorsResult.size(); - - // Act - service.delete(Locator.delete(locatorInfo.getId())); - - // Assert - listLocatorsResult = service.list(Locator.list()); - assertEquals("listLocatorsResult.size", assetCountBaseline - 1, listLocatorsResult.size()); - - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(Locator.get(locatorInfo.getId())); - } - - @Test - public void deleteLocatorInvalidIdFailed() throws ServiceException { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.delete(Locator.delete(invalidId)); - } - - @Test - public void canGetLocatorBackFromAsset() throws Exception { - LocatorInfo locator = service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), - LocatorType.SAS)); - - ListResult locators = service.list(Locator.list(assetInfo.getLocatorsLink())); - - assertEquals(1, locators.size()); - assertEquals(locator.getId(), locators.get(0).getId()); - - } - - @Test - public void canGetAssetFromLocator() throws Exception { - LocatorInfo locator = service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), - LocatorType.SAS)); - - AssetInfo asset = service.get(Asset.get(locator.getAssetLink())); - - assertEquals(assetInfo.getId(), asset.getId()); - } - - @Test - public void canGetAccessPolicyFromLocator() throws Exception { - LocatorInfo locator = service.create(Locator.create(accessPolicyInfo.getId(), assetInfo.getId(), - LocatorType.SAS)); - - AccessPolicyInfo accessPolicy = service.get(AccessPolicy.get(locator.getAccessPolicyLink())); - - assertEquals(accessPolicyInfo.getId(), accessPolicy.getId()); - - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaConfigurationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaConfigurationTest.java deleted file mode 100644 index ea1f80c485bca..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaConfigurationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Configuration; - -public class MediaConfigurationTest { - - @Test - public void createMediaConfigurationTestSuccess() { - // Arrange - - // Act - Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication( - "https://testMediaServiceBaseUri", "testOAuthUri", "testClientId", "testClientSecret", "testScope"); - - // Assert - assertEquals("https://testMediaServiceBaseUri", configuration.getProperty("media.uri")); - assertEquals("testOAuthUri", configuration.getProperty("media.oauth.uri")); - assertEquals("testClientId", configuration.getProperty("media.oauth.client.id")); - assertEquals("testClientSecret", configuration.getProperty("media.oauth.client.secret")); - assertEquals("testScope", configuration.getProperty("media.oauth.scope")); - } - - @Test - public void createMediaConfigurationPassingExistingConfigurationSuccess() { - // Arrange - Configuration preConfiguration = new Configuration(); - preConfiguration.setProperty("preexistingName", "preexistingValue"); - - // Act - Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication(preConfiguration, - "https://testMediaServiceBaseUri", "testOAuthUri", "testClientId", "testClientSecret", "testScope"); - - // Assert - assertEquals("preexistingValue", configuration.getProperty("preexistingName")); - assertEquals("https://testMediaServiceBaseUri", configuration.getProperty("media.uri")); - assertEquals("testOAuthUri", configuration.getProperty("media.oauth.uri")); - assertEquals("testClientId", configuration.getProperty("media.oauth.client.id")); - assertEquals("testClientSecret", configuration.getProperty("media.oauth.client.secret")); - - } - - @Test - public void createMediaConfigurationWithProfileConfigurationSuccess() { - // Arrange - Configuration preConfiguration = new Configuration(); - preConfiguration.setProperty("preexistingName", "preexistingValue"); - - // Act - Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication("testProfile", - preConfiguration, "https://testMediaServiceBaseUri", "testOAuthUri", "testClientId", - "testClientSecret", "testScope"); - - // Assert - assertEquals("preexistingValue", configuration.getProperty("preexistingName")); - assertEquals("https://testMediaServiceBaseUri", configuration.getProperty("testProfile.media.uri")); - assertEquals("testOAuthUri", configuration.getProperty("testProfile.media.oauth.uri")); - assertEquals("testClientId", configuration.getProperty("testProfile.media.oauth.client.id")); - assertEquals("testClientSecret", configuration.getProperty("testProfile.media.oauth.client.secret")); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaProcessorIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaProcessorIntegrationTest.java deleted file mode 100644 index 8132e3d52e67f..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaProcessorIntegrationTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.util.List; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.MediaProcessor; -import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo; - -public class MediaProcessorIntegrationTest extends IntegrationTestBase { - - private void verifyMediaProcessorInfo(String message, MediaProcessorInfo mediaProcessorInfo) { - assertEquals(message + " id length", 49, mediaProcessorInfo.getId().length()); - assertTrue(message + " name length > 0", mediaProcessorInfo.getName().length() > 0); - assertNotNull(message + " description", mediaProcessorInfo.getDescription()); - assertNotNull(message + " sku", mediaProcessorInfo.getSku()); - assertTrue(message + " vendor length > 0", mediaProcessorInfo.getVendor().length() > 0); - assertTrue(message + " version length > 0", mediaProcessorInfo.getVersion().length() > 0); - } - - private void verifyMediaProcessorInfo(String message, String id, String name, String description, String sku, - String vendor, MediaProcessorInfo mediaProcessorInfo) { - assertEquals(message + " id", id, mediaProcessorInfo.getId()); - assertEquals(message + " name", name, mediaProcessorInfo.getName()); - assertEquals(message + " description", description, mediaProcessorInfo.getDescription()); - assertEquals(message + " sku", sku, mediaProcessorInfo.getSku()); - assertEquals(message + " vendor", vendor, mediaProcessorInfo.getVendor()); - assertTrue(message + "version length > 0", mediaProcessorInfo.getVersion().length() > 0); - } - - @Test - public void listMediaProcessorsSuccess() throws ServiceException { - // Arrange - - // Act - ListResult listMediaProcessorsResult = service.list(MediaProcessor.list()); - - // Assert - assertNotNull("listMediaProcessorsResult", listMediaProcessorsResult); - assertTrue("listMediaProcessorsResult size > 0", listMediaProcessorsResult.size() > 0); - List ps = listMediaProcessorsResult; - for (int i = 0; i < ps.size(); i++) { - MediaProcessorInfo mediaProcessorInfo = ps.get(i); - verifyMediaProcessorInfo("mediaProcessorInfo:" + i, mediaProcessorInfo); - } - } - - @Test - public void listMediaProcessorWithOptionSuccess() throws ServiceException { - ListResult listMediaProcessorsResult = service.list(MediaProcessor.list().setTop(2) - .set("$filter", "Id eq 'nb:mpid:UUID:aec03716-7c5e-4f68-b592-f4850eba9f10'")); - - assertNotNull("listMediaProcessorsResult", listMediaProcessorsResult); - assertEquals("listMediaProcessors size", 1, listMediaProcessorsResult.size()); - MediaProcessorInfo mediaProcessorInfo = listMediaProcessorsResult.get(0); - verifyMediaProcessorInfo("mediaProcessorInfo", "nb:mpid:UUID:aec03716-7c5e-4f68-b592-f4850eba9f10", - "Storage Decryption", "Storage Decryption", "", "Microsoft", mediaProcessorInfo); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaServiceTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaServiceTest.java deleted file mode 100644 index 59713c861809c..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/MediaServiceTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Configuration; - -public class MediaServiceTest { - - @Test - public void createMediaContractSuccessTest() { - // Arrange - Configuration configurationInstance = Configuration.getInstance(); - configurationInstance = MediaConfiguration.configureWithOAuthAuthentication(configurationInstance, - "mediaServiceBaseUri", "oAuthUri", "clientId", "clientSecret", "testScope"); - - // Act - MediaContract mediaContract = MediaService.create(); - - // Assert - assertNotNull(mediaContract); - configurationInstance = null; - - } - - @Test - public void createMediaContractWithSpecifiedConfigurationTest() { - // Arrange - Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication("mediaServiceBaseUri", - "oAuthUri", "clientId", "clientSecret", "testScope"); - - // Act - MediaContract mediaContract = MediaService.create(configuration); - - // Assert - assertNotNull(mediaContract); - } - - @Test - public void createMediaContractWithSpecifiedProfileTest() { - // Arrange - String profile = "testProfile"; - - // Act - MediaContract mediaContract = MediaService.create(profile); - - // Assert - assertNotNull(mediaContract); - - } - - @Test - public void createMediaContractWithSpecifiedProfileAndConfiguration() { - // Arrange - String profile = "testProfile"; - Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication(profile, new Configuration(), - "mediaServiceBaseUri", "oAuthUri", "clientId", "clientSecret", "testScope"); - - // Act - MediaContract mediaContract = MediaService.create(profile, configuration); - - // Assert - assertNotNull(mediaContract); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/NotificationEndPointIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/NotificationEndPointIntegrationTest.java deleted file mode 100644 index 9a27e93e077ab..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/NotificationEndPointIntegrationTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.EndPointType; -import com.microsoft.windowsazure.services.media.models.NotificationEndPoint; -import com.microsoft.windowsazure.services.media.models.NotificationEndPointInfo; - -public class NotificationEndPointIntegrationTest extends IntegrationTestBase { - private final String validButNonexistNotificationEndPointId = "notificationEndPointId"; - private final String testNotificationEndPointPrefix = "testNotificationEndPointPrefix"; - private final String testEndPointAddress = "testendpointaddress"; - - private void verifyNotificationEndPointInfosEqual(String message, NotificationEndPointInfo expected, - NotificationEndPointInfo actual) { - verifyNotificationEndPointProperties(message, expected.getName(), expected.getEndPointType(), - expected.getEndPointAddress(), actual); - } - - private void verifyNotificationEndPointProperties(String message, String name, EndPointType endPointType, - String endPointAddress, NotificationEndPointInfo notificationEndPointInfo) { - assertNotNull(message, notificationEndPointInfo); - assertEquals(message + " Name", name, notificationEndPointInfo.getName()); - assertEquals(message + " EndPointType", endPointType, notificationEndPointInfo.getEndPointType()); - assertEquals(message + " EndPointAddress", endPointAddress, notificationEndPointInfo.getEndPointAddress()); - assertNotNull(message + " Created", notificationEndPointInfo.getCreated()); - assertNotNull(message + " Id", notificationEndPointInfo.getId()); - } - - @Test - public void canCreateNotificationEndPoint() throws Exception { - String testName = testNotificationEndPointPrefix + "CanCreate"; - - NotificationEndPointInfo actualNotificationEndPoint = service.create(NotificationEndPoint.create(testName, - EndPointType.AzureQueue, testEndPointAddress)); - - verifyNotificationEndPointProperties("notification end point ", testName, EndPointType.AzureQueue, - testEndPointAddress, actualNotificationEndPoint); - } - - @Test - public void canCreateNotificationEndPointWithReadPermissions() throws Exception { - String testName = testNotificationEndPointPrefix + "CanCreate"; - - NotificationEndPointInfo actualNotificationEndPoint = service.create(NotificationEndPoint.create(testName, - EndPointType.AzureQueue, testEndPointAddress)); - - verifyNotificationEndPointProperties("notification end point", testName, EndPointType.AzureQueue, - testEndPointAddress, actualNotificationEndPoint); - } - - @Test - public void canGetSingleNotificationEndPointById() throws Exception { - String expectedName = testNotificationEndPointPrefix + "GetOne"; - NotificationEndPointInfo expectedNotificationEndPointInfo = service.create(NotificationEndPoint.create( - expectedName, EndPointType.AzureQueue, testEndPointAddress)); - - NotificationEndPointInfo actualNotificationEndPointInfo = service.get(NotificationEndPoint - .get(expectedNotificationEndPointInfo.getId())); - - assertEquals(expectedNotificationEndPointInfo.getId(), actualNotificationEndPointInfo.getId()); - verifyNotificationEndPointProperties("notification end point", expectedName, EndPointType.AzureQueue, - testEndPointAddress, actualNotificationEndPointInfo); - } - - @Test - public void canGetSingleNotificationEndPointByInvalidId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.get(NotificationEndPoint.get(invalidId)); - } - - @Test - public void cannotGetSingleNotificationEndPointByNonexistId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.get(NotificationEndPoint.get(validButNonexistNotificationEndPointId)); - } - - @Test - public void canRetrieveListOfNotificationEndPoints() throws Exception { - String[] notificationEndPointNames = new String[] { testNotificationEndPointPrefix + "ListOne", - testNotificationEndPointPrefix + "ListTwo" }; - - List expectedNotificationEndPoints = new ArrayList(); - for (int i = 0; i < notificationEndPointNames.length; i++) { - NotificationEndPointInfo notificationEndPointInfo = service.create(NotificationEndPoint.create( - notificationEndPointNames[i], EndPointType.AzureQueue, testEndPointAddress)); - expectedNotificationEndPoints.add(notificationEndPointInfo); - } - - List actualAccessPolicies = service.list(NotificationEndPoint.list()); - - verifyListResultContains("listNotificationEndPoints", expectedNotificationEndPoints, actualAccessPolicies, - new ComponentDelegate() { - @Override - public void verifyEquals(String message, Object expected, Object actual) { - verifyNotificationEndPointInfosEqual(message, (NotificationEndPointInfo) expected, - (NotificationEndPointInfo) actual); - } - }); - } - - @Test - public void canUseQueryParametersWhenListingNotificationEndPoints() throws Exception { - String[] notificationEndPointNames = new String[] { testNotificationEndPointPrefix + "ListThree", - testNotificationEndPointPrefix + "ListFour", testNotificationEndPointPrefix + "ListFive", - testNotificationEndPointPrefix + "ListSix", testNotificationEndPointPrefix + "ListSeven" }; - - List expectedNotificationEndPointInfos = new ArrayList(); - for (int i = 0; i < notificationEndPointNames.length; i++) { - NotificationEndPointInfo notificationEndPointInfo = service.create(NotificationEndPoint.create( - notificationEndPointNames[i], EndPointType.AzureQueue, testEndPointAddress)); - expectedNotificationEndPointInfos.add(notificationEndPointInfo); - } - - List actualNotificationEndPointInfos = service.list(NotificationEndPoint.list() - .setTop(2)); - - assertEquals(2, actualNotificationEndPointInfos.size()); - } - - @Test - public void canDeleteNotificationEndPointById() throws Exception { - String testNotificationEndPointName = testNotificationEndPointPrefix + "ToDelete"; - NotificationEndPointInfo notificationEndPointToBeDeleted = service.create(NotificationEndPoint.create( - testNotificationEndPointName, EndPointType.AzureQueue, testEndPointAddress)); - List listPoliciesResult = service.list(NotificationEndPoint.list()); - int policyCountBaseline = listPoliciesResult.size(); - - service.delete(NotificationEndPoint.delete(notificationEndPointToBeDeleted.getId())); - - listPoliciesResult = service.list(NotificationEndPoint.list()); - assertEquals("listPoliciesResult.size", policyCountBaseline - 1, listPoliciesResult.size()); - - for (NotificationEndPointInfo policy : service.list(NotificationEndPoint.list())) { - assertFalse(notificationEndPointToBeDeleted.getId().equals(policy.getId())); - } - - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(404)); - service.get(NotificationEndPoint.get(notificationEndPointToBeDeleted.getId())); - } - - @Test - public void canDeleteNotificationEndPointByInvalidId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.delete(NotificationEndPoint.delete(invalidId)); - } - - @Test - public void cannotDeleteNotificationEndPointByNonexistId() throws Exception { - expectedException.expect(ServiceException.class); - expectedException.expect(new ServiceExceptionMatcher(400)); - service.delete(NotificationEndPoint.delete(validButNonexistNotificationEndPointId)); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ProtectionKeyIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ProtectionKeyIntegrationTest.java deleted file mode 100644 index 7749249e66a88..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/ProtectionKeyIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.ContentKeyType; -import com.microsoft.windowsazure.services.media.models.ProtectionKey; - -public class ProtectionKeyIntegrationTest extends IntegrationTestBase { - - @Test - public void canGetProtectionKeyId() throws ServiceException { - // Arrange - - // Act - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(ContentKeyType.CommonEncryption)); - - // Assert - assertNotNull(protectionKeyId); - } - - @Test - public void canGetProtectionKey() throws ServiceException { - // Arrange - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(ContentKeyType.CommonEncryption)); - - // Act - String protectionKey = service.action(ProtectionKey.getProtectionKey(protectionKeyId)); - - // Assert - assertNotNull(protectionKey); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/TaskIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/TaskIntegrationTest.java deleted file mode 100644 index 2c576c8c193b7..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/TaskIntegrationTest.java +++ /dev/null @@ -1,288 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media; - -import static org.junit.Assert.*; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.Job; -import com.microsoft.windowsazure.services.media.models.Job.Creator; -import com.microsoft.windowsazure.services.media.models.JobInfo; -import com.microsoft.windowsazure.services.media.models.JobState; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.Task; -import com.microsoft.windowsazure.services.media.models.Task.CreateBatchOperation; -import com.microsoft.windowsazure.services.media.models.TaskInfo; -import com.microsoft.windowsazure.services.media.models.TaskOption; -import com.microsoft.windowsazure.services.media.models.TaskState; -import com.sun.jersey.core.util.Base64; - -public class TaskIntegrationTest extends IntegrationTestBase { - private static AssetInfo assetInfo; - private Creator jobCreator; - - private static final String commonConfiguration = "H.264 256k DSL CBR"; - - @BeforeClass - public static void setup() throws Exception { - IntegrationTestBase.setup(); - assetInfo = setupAssetWithFile(); - } - - @Before - public void instanceSetup() { - this.jobCreator = Job.create().setName(testJobPrefix + UUID.randomUUID().toString()).setPriority(3) - .addInputMediaAsset(assetInfo.getId()); - } - - @Test - public void createTaskSuccess() throws ServiceException, UnsupportedEncodingException { - // Arrange - - // Required - String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_2_2_0_0_ID; - String taskBody = constructTaskBody(0); - - // Optional parameters - String configuration = new String(Base64.encode(commonConfiguration), "UTF8"); - String name = "My encoding Task " + UUID.randomUUID().toString(); - int jobPriority = 3; - TaskOption options = TaskOption.ProtectedConfiguration; - // Use a fake id, to simulate real use. - String encryptionKeyId = "nb:kid:UUID:" + UUID.randomUUID().toString(); - String encryptionScheme = "ConfigurationEncryption"; - String encryptionVersion = "1.0"; - // Use a trivial vector, 16 bytes of zeros, base-64 encoded. - String initializationVector = new String(Base64.encode(new byte[16]), "UTF8"); - - CreateBatchOperation taskCreator = Task.create(mediaProcessorId, taskBody).setConfiguration(configuration) - .setName(name).setPriority(jobPriority).setOptions(options).setEncryptionKeyId(encryptionKeyId) - .setEncryptionScheme(encryptionScheme).setEncryptionVersion(encryptionVersion) - .setInitializationVector(initializationVector); - jobCreator.addTaskCreator(taskCreator); - - // Act - JobInfo job = service.create(jobCreator); - List taskInfos = service.list(Task.list(job.getTasksLink())); - - // Assert - assertEquals("taskInfos count", 1, taskInfos.size()); - verifyTaskPropertiesJustStarted("taskInfo", mediaProcessorId, options, taskBody, configuration, name, - jobPriority, encryptionKeyId, encryptionScheme, encryptionVersion, initializationVector, - taskInfos.get(0)); - } - - @Test - public void createTwoTasksSuccess() throws ServiceException { - // Arrange - - // Required - String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_2_2_0_0_ID; - String[] taskBodies = new String[] { constructTaskBody(0), constructTaskBody(1) }; - - // Optional parameters - String configuration = commonConfiguration; - String baseName = "My encoding Task " + UUID.randomUUID().toString(); - String[] suffixes = new String[] { " 1", " 2" }; - int jobPriority = 3; - TaskOption options = TaskOption.None; - - List taskCreators = new ArrayList(); - - for (int i = 0; i < taskBodies.length; i++) { - CreateBatchOperation taskCreator = Task.create(mediaProcessorId, taskBodies[i]) - .setConfiguration(configuration).setName(baseName + suffixes[i]); - taskCreators.add(taskCreator); - jobCreator.addTaskCreator(taskCreator); - } - - // Act - JobInfo job = service.create(jobCreator); - List taskInfos = service.list(Task.list(job.getTasksLink())); - - // Assert - assertEquals("taskInfos count", taskCreators.size(), taskInfos.size()); - for (int i = 0; i < taskCreators.size(); i++) { - verifyTaskPropertiesJustStartedNoEncryption("taskInfo", mediaProcessorId, options, taskBodies[i], - configuration, baseName + suffixes[i], jobPriority, taskInfos.get(i)); - } - } - - @Test - public void canListTasksWithOptions() throws ServiceException { - // Arrange - String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_2_2_0_0_ID; - String configuration = commonConfiguration; - String[] taskNameSuffixes = new String[] { "A", "B", "C", "D" }; - String baseName = "My encoding Task " + UUID.randomUUID().toString(); - int taskCounter = 0; - for (String suffix : taskNameSuffixes) { - CreateBatchOperation taskCreator = Task.create(mediaProcessorId, constructTaskBody(taskCounter++)) - .setConfiguration(configuration).setName(baseName + suffix); - jobCreator.addTaskCreator(taskCreator); - } - - service.create(jobCreator); - - // Act - ListResult listTaskResult1 = service.list(Task.list().set("$filter", - "startswith(Name, '" + baseName + "') eq true")); - ListResult listTaskResult2 = service.list(Task.list() - .set("$filter", "startswith(Name, '" + baseName + "') eq true").setTop(2)); - - // Assert - assertEquals("listTaskResult1.size", 4, listTaskResult1.size()); - assertEquals("listTaskResult2.size", 2, listTaskResult2.size()); - } - - @Test - public void cancelTaskSuccess() throws ServiceException, InterruptedException { - // Arrange - String mediaProcessorId = MEDIA_ENCODER_MEDIA_PROCESSOR_2_2_0_0_ID; - String taskBody = constructTaskBody(0); - String configuration = commonConfiguration; - String name = "My encoding Task " + UUID.randomUUID().toString(); - CreateBatchOperation taskCreator = Task.create(mediaProcessorId, taskBody).setConfiguration(configuration) - .setName(name); - jobCreator.addTaskCreator(taskCreator); - - JobInfo jobInfo = service.create(jobCreator); - - // Act - service.action(Job.cancel(jobInfo.getId())); - JobInfo cancellingJobInfo = service.get(Job.get(jobInfo.getId())); - while (cancellingJobInfo.getState() == JobState.Canceling) { - Thread.sleep(2000); - cancellingJobInfo = service.get(Job.get(jobInfo.getId())); - } - - //Assert - List taskInfos = service.list(Task.list(cancellingJobInfo.getTasksLink())); - for (TaskInfo taskInfo : taskInfos) { - verifyTaskPropertiesNoEncryption("canceled task", mediaProcessorId, TaskOption.None, taskBody, - configuration, name, 3, new Date(), null, 0.0, 0.0, null, TaskState.Canceled, taskInfo); - } - } - - private void verifyTaskProperties(String message, String mediaProcessorId, TaskOption options, String taskBody, - String configuration, String name, int priority, String encryptionKeyId, String encryptionScheme, - String encryptionVersion, String initializationVector, Date endTime, String errorDetails, double progress, - double runningDuration, Date startTime, TaskState state, TaskInfo actual) throws ServiceException { - assertNotNull(message, actual); - assertNotNull(message + " id", actual.getId()); - - // Required fields - assertEquals(message + " getMediaProcessorId", mediaProcessorId, actual.getMediaProcessorId()); - assertEquals(message + " getOptions", options, actual.getOptions()); - assertEquals(message + " getTaskBody", taskBody, actual.getTaskBody()); - - // Optional fields - assertEquals(message + " getConfiguration", configuration, actual.getConfiguration()); - assertEquals(message + " getName", name, actual.getName()); - assertEquals(message + " getPriority", priority, actual.getPriority()); - - // Optional encryption fields - assertEqualsNullEmpty(message + " getEncryptionKeyId", encryptionKeyId, actual.getEncryptionKeyId()); - assertEqualsNullEmpty(message + " getEncryptionScheme", encryptionScheme, actual.getEncryptionScheme()); - assertEqualsNullEmpty(message + " getEncryptionVersion", encryptionVersion, actual.getEncryptionVersion()); - assertEqualsNullEmpty(message + " getInitializationVector", initializationVector, - actual.getInitializationVector()); - - // Read-only fields - assertDateApproxEquals(message + " getEndTime", endTime, actual.getEndTime()); - assertNotNull(message + " getErrorDetails", actual.getErrorDetails()); - assertEquals(message + " getErrorDetails.size", 0, actual.getErrorDetails().size()); - - ListResult inputAssets = service.list(Asset.list(actual.getInputAssetsLink())); - ListResult outputAssets = service.list(Asset.list(actual.getOutputAssetsLink())); - - assertEquals(message + " inputAssets.size", 1, inputAssets.size()); - assertEquals(message + " inputAssets.get(0).getId", assetInfo.getId(), inputAssets.get(0).getId()); - - assertEquals(message + " outputAssets.size", 1, outputAssets.size()); - // Because this is a new asset, there is not much else to test - assertTrue(message + " outputAssets.get(0).getId != assetInfo.getId", - !assetInfo.getId().equals(outputAssets.get(0).getId())); - - assertEquals(message + " getProgress", progress, actual.getProgress(), 0.01); - assertEquals(message + " getRunningDuration", runningDuration, actual.getRunningDuration(), 0.01); - assertDateApproxEquals(message + " getStartTime", startTime, actual.getStartTime()); - assertEquals(message + " getState", state, actual.getState()); - - // Note: The PerfMessage is not validated because it is server generated. - } - - private void verifyTaskPropertiesJustStarted(String message, String mediaProcessorId, TaskOption options, - String taskBody, String configuration, String name, int priority, String encryptionKeyId, - String encryptionScheme, String encryptionVersion, String initializationVector, TaskInfo actual) - throws ServiceException { - - // Read-only - Date endTime = null; - String errorDetails = null; - double progress = 0.0; - int runningDuration = 0; - Date startTime = null; - TaskState state = TaskState.None; - - verifyTaskProperties(message, mediaProcessorId, options, taskBody, configuration, name, priority, - encryptionKeyId, encryptionScheme, encryptionVersion, initializationVector, endTime, errorDetails, - progress, runningDuration, startTime, state, actual); - } - - private void verifyTaskPropertiesJustStartedNoEncryption(String message, String mediaProcessorId, - TaskOption options, String taskBody, String configuration, String name, int priority, TaskInfo actual) - throws ServiceException { - String encryptionKeyId = null; - String encryptionScheme = null; - String encryptionVersion = null; - String initializationVector = null; - - verifyTaskPropertiesJustStarted(message, mediaProcessorId, options, taskBody, configuration, name, priority, - encryptionKeyId, encryptionScheme, encryptionVersion, initializationVector, actual); - } - - private void verifyTaskPropertiesNoEncryption(String message, String mediaProcessorId, TaskOption options, - String taskBody, String configuration, String name, int priority, Date endTime, String errorDetails, - double progress, double runningDuration, Date startTime, TaskState state, TaskInfo actual) - throws ServiceException { - String encryptionKeyId = null; - String encryptionScheme = null; - String encryptionVersion = null; - String initializationVector = null; - - verifyTaskProperties(message, mediaProcessorId, options, taskBody, configuration, name, priority, - encryptionKeyId, encryptionScheme, encryptionVersion, initializationVector, endTime, errorDetails, - progress, runningDuration, startTime, state, actual); - } - - private String constructTaskBody(int outputIndex) { - return "JobInputAsset(0)" + "JobOutputAsset(" + outputIndex - + ")"; - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperationsTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperationsTest.java deleted file mode 100644 index 22293c734766c..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/MediaBatchOperationsTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.implementation; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.net.URI; - -import javax.mail.MessagingException; -import javax.mail.internet.MimeMultipart; -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.media.models.Job; -import com.microsoft.windowsazure.services.media.models.Task; - -public class MediaBatchOperationsTest { - - @Test - public void createMediaBatchOperationSuccess() throws JAXBException, ParserConfigurationException { - // Arrange - URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media").build(); - - // Act - MediaBatchOperations mediaBatchOperations = new MediaBatchOperations(serviceUri); - - // Assert - assertNotNull(mediaBatchOperations); - - } - - @Test(expected = IllegalArgumentException.class) - public void createMediaBatchOperationFailedWithNullUri() throws JAXBException, ParserConfigurationException { - // Arrange - URI serviceUri = null; - - // Act - @SuppressWarnings("unused") - MediaBatchOperations mediaBatchOperations = new MediaBatchOperations(serviceUri); - - // Assert - assertTrue(false); - - } - - @Test - public void addCreateJobOperationToMediaBatchOperationsSuccess() throws JAXBException, ParserConfigurationException { - // Arrange - URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media").build(); - Job.CreateBatchOperation createJobOperation = new Job.CreateBatchOperation(serviceUri); - - // Act - MediaBatchOperations mediaBatchOperations = new MediaBatchOperations(serviceUri); - mediaBatchOperations.addOperation(createJobOperation); - - // Assert - assertNotNull(mediaBatchOperations); - assertEquals(1, mediaBatchOperations.getOperations().size()); - - } - - @Test - public void addCreateTaskOperationToMediaBatchOperationsSuccess() throws JAXBException, - ParserConfigurationException { - // Arrange - URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media").build(); - String mediaProcessorId = "testMediaProcessorId"; - String taskBody = "testTaskBody"; - - Task.CreateBatchOperation taskCreateBatchOperation = new Task.CreateBatchOperation(mediaProcessorId, taskBody); - - // Act - MediaBatchOperations mediaBatchOperations = new MediaBatchOperations(serviceUri); - mediaBatchOperations.addOperation(taskCreateBatchOperation); - - // Assert - assertNotNull(mediaBatchOperations); - assertEquals(1, mediaBatchOperations.getOperations().size()); - } - - @Test - public void getMimeMultipartSuccess() throws JAXBException, ParserConfigurationException, MessagingException, - IOException { - // Arrange - String mediaProcessorId = "testMediaProcessorId"; - String taskBody = "testTaskBody"; - URI serviceUri = UriBuilder.fromPath("http://www.contoso.com/media").build(); - Task.CreateBatchOperation taskCreateBatchOperation = new Task.CreateBatchOperation(mediaProcessorId, taskBody); - Job.CreateBatchOperation jobCreateBatchOperation = new Job.CreateBatchOperation(serviceUri); - - // Act - MediaBatchOperations mediaBatchOperations = new MediaBatchOperations(serviceUri); - mediaBatchOperations.addOperation(jobCreateBatchOperation); - mediaBatchOperations.addOperation(taskCreateBatchOperation); - MimeMultipart mimeMultipart = mediaBatchOperations.getMimeMultipart(); - - // Assert - assertNotNull(mediaBatchOperations); - assertEquals(2, mediaBatchOperations.getOperations().size()); - assertNotNull(mimeMultipart); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxyIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxyIntegrationTest.java deleted file mode 100644 index 472b1a6ddfbf0..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/implementation/OAuthRestProxyIntegrationTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.media.implementation; - -import static org.junit.Assert.*; - -import java.net.URI; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.media.IntegrationTestBase; -import com.microsoft.windowsazure.services.media.MediaConfiguration; -import com.sun.jersey.api.client.Client; - -public class OAuthRestProxyIntegrationTest extends IntegrationTestBase { - @Test - public void serviceCanBeCalledToCreateAccessToken() throws Exception { - // Arrange - OAuthContract oAuthContract = new OAuthRestProxy(config.create(Client.class), new UserAgentFilter()); - - // Act - URI oAuthUri = new URI((String) config.getProperty(MediaConfiguration.OAUTH_URI)); - String clientId = (String) config.getProperty(MediaConfiguration.OAUTH_CLIENT_ID); - String clientSecret = (String) config.getProperty(MediaConfiguration.OAUTH_CLIENT_SECRET); - String scope = (String) config.getProperty(MediaConfiguration.OAUTH_SCOPE); - OAuthTokenResponse result = oAuthContract.getAccessToken(oAuthUri, clientId, clientSecret, scope); - - // Assert - assertNotNull(result); - assertNotNull(result.getAccessToken()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfoTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfoTest.java deleted file mode 100644 index 7e4a488dd9b75..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/AccessPolicyInfoTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.media.models; - -import java.util.Date; -import java.util.EnumSet; - -import org.junit.Assert; -import org.junit.Test; - -import com.microsoft.windowsazure.services.media.implementation.content.AccessPolicyType; - -public class AccessPolicyInfoTest { - - @Test - public void getSetId() { - String expected = "expectedId"; - - AccessPolicyInfo policy = new AccessPolicyInfo(null, new AccessPolicyType().setId(expected)); - - String actual = policy.getId(); - - Assert.assertEquals(expected, actual); - } - - @Test - public void getSetCreated() { - Date expected = new Date(); - AccessPolicyInfo policy = new AccessPolicyInfo(null, new AccessPolicyType().setCreated(expected)); - - Date actual = policy.getCreated(); - - Assert.assertEquals(expected, actual); - } - - @Test - public void getSetLastModified() { - Date expected = new Date(); - AccessPolicyInfo policy = new AccessPolicyInfo(null, new AccessPolicyType().setLastModified(expected)); - - Date actual = policy.getLastModified(); - - Assert.assertEquals(expected, actual); - } - - @Test - public void getSetName() { - String expected = "policy name goes here"; - AccessPolicyInfo policy = new AccessPolicyInfo(null, new AccessPolicyType().setName(expected)); - - String actual = policy.getName(); - - Assert.assertEquals(expected, actual); - } - - @Test - public void getSetDurationInMinutes() { - double expected = 60; // arbitrary value - AccessPolicyInfo policy = new AccessPolicyInfo(null, new AccessPolicyType().setDurationInMinutes(expected)); - - double actual = policy.getDurationInMinutes(); - - Assert.assertEquals(expected, actual, 0.0); - } - - @Test - public void getSetPermissions() { - EnumSet expected = EnumSet - .of(AccessPolicyPermission.LIST, AccessPolicyPermission.WRITE); - AccessPolicyInfo policy = new AccessPolicyInfo(null, - new AccessPolicyType().setPermissions(AccessPolicyPermission.bitsFromPermissions(expected))); - - EnumSet actual = policy.getPermissions(); - - Assert.assertEquals(expected, actual); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorInfoTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorInfoTest.java deleted file mode 100644 index 25f67d48de245..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/LocatorInfoTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.media.models; - -import static org.junit.Assert.*; - -import java.util.Date; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.media.implementation.content.LocatorRestType; - -public class LocatorInfoTest { - - @Test - public void testGetSetId() { - // Arrange - String expectedId = "testId"; - LocatorInfo locator = new LocatorInfo(null, new LocatorRestType().setId(expectedId)); - - // Act - String actualId = locator.getId(); - - // Assert - assertEquals(expectedId, actualId); - } - - @Test - public void testGetSetExpirationDateTime() { - // Arrange - Date expectedExpirationDateTime = new Date(); - LocatorInfo locatorInfo = new LocatorInfo(null, - new LocatorRestType().setExpirationDateTime(expectedExpirationDateTime)); - - // Act - Date actualExpirationDateTime = locatorInfo.getExpirationDateTime(); - - // Assert - assertEquals(expectedExpirationDateTime, actualExpirationDateTime); - } - - @Test - public void testGetSetType() { - // Arrange - LocatorType expectedLocatorType = LocatorType.SAS; - LocatorInfo locatorInfo = new LocatorInfo(null, new LocatorRestType().setType(expectedLocatorType.getCode())); - - // Act - LocatorType actualLocatorType = locatorInfo.getLocatorType(); - - // Assert - assertEquals(expectedLocatorType, actualLocatorType); - } - - @Test - public void testGetSetPath() { - // Arrange - String expectedPath = "testPath"; - LocatorInfo locatorInfo = new LocatorInfo(null, new LocatorRestType().setPath(expectedPath)); - - // Act - String actualPath = locatorInfo.getPath(); - - // Assert - assertEquals(expectedPath, actualPath); - } - - @Test - public void testGetSetAccessPolicyId() { - // Arrange - String expectedAccessPolicyId = "testAccessPolicyId"; - LocatorInfo locatorInfo = new LocatorInfo(null, new LocatorRestType().setAccessPolicyId(expectedAccessPolicyId)); - - // Act - String actualAccessPolicyId = locatorInfo.getAccessPolicyId(); - - // Assert - assertEquals(expectedAccessPolicyId, actualAccessPolicyId); - } - - @Test - public void testGetSetAssetId() { - // Arrange - String expectedAssetId = "testAssetId"; - LocatorInfo locatorInfo = new LocatorInfo(null, new LocatorRestType().setAssetId(expectedAssetId)); - - // Act - String actualAssetId = locatorInfo.getAssetId(); - - // Assert - assertEquals(expectedAssetId, actualAssetId); - } - - @Test - public void testGetSetStartTime() { - // Arrange - Date expectedStartTime = new Date(); - LocatorInfo locatorInfo = new LocatorInfo(null, new LocatorRestType().setStartTime(expectedStartTime)); - - // Act - Date actualStartTime = locatorInfo.getStartTime(); - - // Assert - assertEquals(expectedStartTime, actualStartTime); - } - - @Test - public void testGetSetBaseUri() { - // Arrange - String expectedBaseUri = "testBaseUri"; - LocatorInfo locatorInfo = new LocatorInfo(null, new LocatorRestType().setBaseUri(expectedBaseUri)); - - // Act - String actualBaseUri = locatorInfo.getBaseUri(); - - // Assert - assertEquals(expectedBaseUri, actualBaseUri); - } - - @Test - public void testGetSetContentAccessComponent() { - // Arrange - String expectedContentAccessComponent = "testContentAccessToken"; - LocatorInfo locatorInfo = new LocatorInfo(null, - new LocatorRestType().setContentAccessComponent(expectedContentAccessComponent)); - - // Act - String actualContentAccessComponent = locatorInfo.getContentAccessToken(); - - // Assert - assertEquals(expectedContentAccessComponent, actualContentAccessComponent); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/TaskInfoTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/TaskInfoTest.java deleted file mode 100644 index a0d32233b9e2b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/media/models/TaskInfoTest.java +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.media.models; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.media.implementation.content.ErrorDetailType; -import com.microsoft.windowsazure.services.media.implementation.content.TaskType; - -public class TaskInfoTest { - - @Test - public void testGetSetId() { - // Arrange - String expectedId = "expectedId"; - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setId(expectedId)); - - // Act - String actualId = taskInfo.getId(); - - // Assert - assertEquals(expectedId, actualId); - - } - - @Test - public void testGetSetConfiguration() { - // Arrange - String expectedConfiguration = "expectedConfiguration"; - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setConfiguration(expectedConfiguration)); - - // Act - String actualConfiguration = taskInfo.getConfiguration(); - - // Assert - assertEquals(expectedConfiguration, actualConfiguration); - } - - @Test - public void testGetSetEndTime() throws Exception { - // Arrange - Date expectedEndTime = new Date(); - - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setEndTime(expectedEndTime)); - - // Act - Date actualEndTime = taskInfo.getEndTime(); - - // Assert - assertEquals(expectedEndTime, actualEndTime); - - } - - @Test - public void testGetSetErrorDetails() throws Exception { - // Arrange - List expectedErrorDetails = new ArrayList(); - List expectedErrorDetailsType = new ArrayList(); - for (ErrorDetailType errorDetailType : expectedErrorDetailsType) { - ErrorDetail errorDetail = new ErrorDetail(errorDetailType.getCode(), errorDetailType.getMessage()); - expectedErrorDetails.add(errorDetail); - } - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setErrorDetails(expectedErrorDetailsType)); - - // Act - List actualErrorDetails = taskInfo.getErrorDetails(); - - // Assert - assertEquals(expectedErrorDetails, actualErrorDetails); - } - - @Test - public void testGetSetMediaProcessorId() { - // Arrange - String expectedName = "testName"; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setName(expectedName)); - - // Act - String actualName = TaskInfo.getName(); - - // Assert - assertEquals(expectedName, actualName); - } - - @Test - public void testGetSetName() { - // Arrange - - TaskOption expectedOptions = TaskOption.None; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setOptions(expectedOptions.getCode())); - - // Act - TaskOption actualOptions = TaskInfo.getOptions(); - - // Assert - assertEquals(expectedOptions, actualOptions); - } - - @Test - public void testGetSetPerfMessage() { - // Arrange - String expectedPerfMessage = "testGetSetPerfMessage"; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setPerfMessage(expectedPerfMessage)); - - // Act - String actualPerfMessage = TaskInfo.getPerfMessage(); - - // Assert - assertEquals(expectedPerfMessage, actualPerfMessage); - } - - @Test - public void testGetSetPriority() { - // Arrange - int expectedPriority = 3; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setPriority(expectedPriority)); - - // Act - int actualPriority = TaskInfo.getPriority(); - - // Assert - assertEquals(expectedPriority, actualPriority); - } - - @Test - public void testGetSetProgress() { - // Arrange - double expectedProgress = 3; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setProgress(expectedProgress)); - - // Act - double actualProgress = TaskInfo.getProgress(); - - // Assert - assertEquals(expectedProgress, actualProgress, 0.00001); - } - - @Test - public void testGetSetRunningDuration() { - // Arrange - double expectedRunningDuration = 3; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setRunningDuration(expectedRunningDuration)); - - // Act - double actualRunningDuration = TaskInfo.getRunningDuration(); - - // Assert - assertEquals(expectedRunningDuration, actualRunningDuration, 0.00001); - } - - @Test - public void testGetSetStartTime() { - // Arrange - Date expectedStartTime = new Date(); - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setStartTime(expectedStartTime)); - - // Act - Date actualStartTime = TaskInfo.getStartTime(); - - // Assert - assertEquals(expectedStartTime, actualStartTime); - } - - @Test - public void testGetSetState() { - // Arrange - TaskState expectedState = TaskState.Completed; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setState(expectedState.getCode())); - - // Act - TaskState actualState = TaskInfo.getState(); - - // Assert - assertEquals(expectedState, actualState); - } - - @Test - public void testGetSetTaskBody() { - // Arrange - String expectedTaskBody = "getSetTaskBody"; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setTaskBody(expectedTaskBody)); - - // Act - String actualTaskBody = TaskInfo.getTaskBody(); - - // Assert - assertEquals(expectedTaskBody, actualTaskBody); - } - - @Test - public void testGetSetOptions() { - // Arrange - TaskOption expectedTaskOption = TaskOption.ProtectedConfiguration; - TaskInfo TaskInfo = new TaskInfo(null, new TaskType().setOptions(expectedTaskOption.getCode())); - - // Act - TaskOption actualTaskOption = TaskInfo.getOptions(); - - // Assert - assertEquals(expectedTaskOption, actualTaskOption); - } - - @Test - public void testGetSetEncryptionKeyId() { - // Arrange - String expectedEncryptionKeyId = "getSetEncryptionKeyId"; - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setEncryptionKeyId(expectedEncryptionKeyId)); - - // Act - String actualEncryptionKeyId = taskInfo.getEncryptionKeyId(); - - // Assert - assertEquals(expectedEncryptionKeyId, actualEncryptionKeyId); - } - - @Test - public void testGetSetEncryptionScheme() { - // Arrange - String expectedEncryptionScheme = "getSetEncryptionScheme"; - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setEncryptionScheme(expectedEncryptionScheme)); - - // Act - String actualEncryptionScheme = taskInfo.getEncryptionScheme(); - - // Assert - assertEquals(expectedEncryptionScheme, actualEncryptionScheme); - } - - @Test - public void testGetSetEncryptionVersion() { - // Arrange - String expectedEncryptionVersion = "1.5"; - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setEncryptionVersion(expectedEncryptionVersion)); - - // Act - String actualEncryptionVersion = taskInfo.getEncryptionVersion(); - - // Assert - assertEquals(expectedEncryptionVersion, actualEncryptionVersion); - } - - @Test - public void testGetSetInitializationVector() { - // Arrange - String expectedInitializationVector = "testInitializationVector"; - TaskInfo taskInfo = new TaskInfo(null, new TaskType().setEncryptionVersion(expectedInitializationVector)); - - // Act - String actualInitializationVector = taskInfo.getEncryptionVersion(); - - // Assert - assertEquals(expectedInitializationVector, actualInitializationVector); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/IntegrationTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/IntegrationTestBase.java deleted file mode 100644 index d682fd2f3fba1..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/IntegrationTestBase.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue; - -import com.microsoft.windowsazure.services.core.Configuration; - -public abstract class IntegrationTestBase { - protected static Configuration createConfiguration() { - Configuration config = Configuration.getInstance(); - overrideWithEnv(config, QueueConfiguration.ACCOUNT_NAME); - overrideWithEnv(config, QueueConfiguration.ACCOUNT_KEY); - overrideWithEnv(config, QueueConfiguration.URI); - return config; - } - - private static void overrideWithEnv(Configuration config, String key) { - String value = System.getenv(key); - if (value == null) - return; - - config.setProperty(key, value); - } - - protected static boolean isRunningWithEmulator(Configuration config) { - String accountName = "devstoreaccount1"; - String accountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; - - return accountName.equals(config.getProperty(QueueConfiguration.ACCOUNT_NAME)) - && accountKey.equals(config.getProperty(QueueConfiguration.ACCOUNT_KEY)); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClientGB18030Test.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClientGB18030Test.java deleted file mode 100644 index 9066107dacd53..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClientGB18030Test.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.net.URISyntaxException; -import java.util.EnumSet; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -public class CloudQueueClientGB18030Test extends QueueTestBase { - - // GB18030CharSet is "啊齄丂狛狜隣郎隣兀﨩ˊ▇█〞〡¦℡㈱‐ー﹡﹢﹫、〓ⅰⅹ⒈€㈠㈩ⅠⅫ! ̄ぁんァヶΑ︴АЯаяāɡㄅㄩ─╋︵﹄︻︱︳︴ⅰⅹɑɡ〇〾⿻⺁䜣€㐀㒣㕴㕵㙉㙊䵯䵰䶴䶵". - public static final String GB18030CharSet = new String(new char[] { 0x554A, 0x9F44, 0x4E02, 0x72DB, 0x72DC, 0xF9F1, - 0xF92C, 0xF9F1, 0xFA0C, 0xFA29, 0x02CA, 0x2587, 0x2588, 0x301E, 0x3021, 0xFFE4, 0x2121, 0x3231, 0x2010, - 0x30FC, 0xFE61, 0xFE62, 0xFE6B, 0x3001, 0x3013, 0x2170, 0x2179, 0x2488, 0x20AC, 0x3220, 0x3229, 0x2160, - 0x216B, 0xFF01, 0xFFE3, 0x3041, 0x3093, 0x30A1, 0x30F6, 0x0391, 0xFE34, 0x0410, 0x042F, 0x0430, 0x044F, - 0x0101, 0x0261, 0x3105, 0x3129, 0x2500, 0x254B, 0xFE35, 0xFE44, 0xFE3B, 0xFE31, 0xFE33, 0xFE34, 0x2170, - 0x2179, 0x0251, 0xE7C7, 0x0261, 0x3007, 0x303E, 0x2FFB, 0x2E81, 0xE843, 0x4723, 0xE864, 0x20AC, 0x3400, - 0x34A3, 0x3574, 0x3575, 0x3649, 0x364A, 0x4D6F, 0x4D70, 0x4DB4, 0x4DB5 }); - - @Test - public void GB18030TestForSingleMessage() throws URISyntaxException, StorageException { - String messageContent = GB18030CharSet; - CloudQueueMessage cqm = new CloudQueueMessage(messageContent); - queue.addMessage(cqm); - - CloudQueueMessage messageFromPeekMessage = queue.peekMessage(); - Assert.assertEquals(messageContent, messageFromPeekMessage.getMessageContentAsString()); - - CloudQueueMessage messageFromRetrieveMessage = queue.retrieveMessage(); - Assert.assertEquals(messageContent, messageFromRetrieveMessage.getMessageContentAsString()); - - String messageContentUpdated = messageContent + " updated"; - messageFromRetrieveMessage.setMessageContent(messageContentUpdated); - queue.updateMessage(messageFromRetrieveMessage, 0); - - messageFromPeekMessage = queue.peekMessage(null, null); - Assert.assertEquals(messageContent, messageFromPeekMessage.getMessageContentAsString()); - - messageContentUpdated = messageContent + " updated again"; - messageFromRetrieveMessage.setMessageContent(messageContentUpdated); - queue.updateMessage(messageFromRetrieveMessage, 0, - EnumSet.of(MessageUpdateFields.VISIBILITY, MessageUpdateFields.CONTENT), null, null); - - messageFromRetrieveMessage = queue.retrieveMessage(5, null, null); - Assert.assertEquals(messageContentUpdated, messageFromRetrieveMessage.getMessageContentAsString()); - - queue.deleteMessage(messageFromRetrieveMessage); - } - - @Test - public void GB18030TestForMultipleMessages() throws URISyntaxException, StorageException { - int messageLength = 2; - String[] messageContents = new String[messageLength]; - for (int i = 0; i < messageLength; i++) { - messageContents[i] = GB18030CharSet + i; - queue.addMessage(new CloudQueueMessage(messageContents[i]), 600, 0, null, null); - } - - Iterable messagesFromPeekMessages = queue.peekMessages(messageLength); - int count = 0; - for (CloudQueueMessage message : messagesFromPeekMessages) { - Assert.assertEquals(messageContents[count], message.getMessageContentAsString()); - count++; - } - - Iterable messagesFromRetrieveMessages = queue.retrieveMessages(messageLength); - count = 0; - for (CloudQueueMessage message : messagesFromRetrieveMessages) { - Assert.assertEquals(messageContents[count], message.getMessageContentAsString()); - message.setMessageContent(message.getMessageContentAsString() + " updated"); - queue.updateMessage(message, 0, EnumSet.of(MessageUpdateFields.VISIBILITY, MessageUpdateFields.CONTENT), - null, null); - count++; - } - - messagesFromPeekMessages = queue.peekMessages(messageLength, null, null); - count = 0; - for (CloudQueueMessage message : messagesFromPeekMessages) { - Assert.assertEquals(messageContents[count] + " updated", message.getMessageContentAsString()); - count++; - } - - messagesFromRetrieveMessages = queue.retrieveMessages(messageLength, 5, null, null); - count = 0; - for (CloudQueueMessage message : messagesFromRetrieveMessages) { - Assert.assertEquals(messageContents[count] + " updated", message.getMessageContentAsString()); - queue.deleteMessage(message, null, null); - count++; - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClientTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClientTests.java deleted file mode 100644 index fd3a57a7f1f1b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueClientTests.java +++ /dev/null @@ -1,227 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.net.URI; -import java.net.URISyntaxException; -import java.text.NumberFormat; -import java.util.HashMap; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.StorageCredentials; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -public final class CloudQueueClientTests extends QueueTestBase { - - @Test - public void testQueueClientConstructor() throws URISyntaxException, StorageException { - StorageCredentials credentials = httpAcc.getCredentials(); - URI baseAddressUri = new URI(httpAcc.getQueueEndpoint().toString()); - - CloudQueueClient queueClient = new CloudQueueClient(baseAddressUri, credentials); - - Assert.assertEquals(baseAddressUri, queueClient.getEndpoint()); - Assert.assertEquals(credentials, queueClient.getCredentials()); - } - - @Test - public void testQueueClientConstructorInvalidParam() throws URISyntaxException, StorageException { - StorageCredentials credentials = httpAcc.getCredentials(); - try { - new CloudQueueClient(null, credentials); - Assert.fail(); - } - catch (IllegalArgumentException e) { - - } - - try { - char[] name = new char[2000]; - new CloudQueueClient(new URI(name.toString()), credentials); - Assert.fail(); - } - catch (URISyntaxException e) { - - } - } - - @Test - public void testListQueuesSmallNumber() throws URISyntaxException, StorageException { - int initialCount = 0; - - for (CloudQueue queue : qClient.listQueues()) { - Assert.assertNotNull(queue); - initialCount++; - } - - HashMap metadata1 = new HashMap(); - metadata1.put("ExistingMetadata1", "ExistingMetadataValue1"); - - for (int i = 0; i < 25; i++) { - CloudQueue q = new CloudQueue(AppendQueueName(httpAcc.getQueueEndpoint(), UUID.randomUUID().toString() - .toLowerCase()), qClient); - q.setMetadata(metadata1); - q.create(); - } - - int count = 0; - for (CloudQueue queue : qClient.listQueues()) { - Assert.assertNotNull(queue); - count++; - } - - Assert.assertEquals(count, initialCount + 25); - - String perfix = "prefixtest" + UUID.randomUUID().toString().substring(0, 8).toLowerCase(); - for (int i = 0; i < 25; i++) { - CloudQueue q = new CloudQueue(AppendQueueName(httpAcc.getQueueEndpoint(), perfix - + UUID.randomUUID().toString().toLowerCase()), qClient); - HashMap metadata2 = new HashMap(); - metadata2.put("tags", q.getName()); - q.setMetadata(metadata2); - q.create(); - } - - count = 0; - for (CloudQueue queue : qClient.listQueues(perfix, QueueListingDetails.METADATA, null, null)) { - count++; - Assert.assertTrue(queue.getMetadata().size() == 1 - && queue.getMetadata().get("tags").equals(queue.getName())); - } - - Assert.assertEquals(count, 25); - } - - @Test - public void testListQueuesAndListQueuesSegmentedLargeNumber() throws URISyntaxException, StorageException { - int count = 0; - for (CloudQueue queue : qClient.listQueues()) { - Assert.assertNotNull(queue); - count++; - } - - int totalLimit = 5005; - if (count < totalLimit) { - - NumberFormat myFormat = NumberFormat.getInstance(); - myFormat.setMinimumIntegerDigits(4); - - for (int i = 0, j = 0; i < totalLimit - count; j++) { - String sub = myFormat.format(j); - CloudQueue q = new CloudQueue(AppendQueueName(httpAcc.getQueueEndpoint(), - String.format("listqueue" + sub.replace(",", ""))), qClient); - if (q.createIfNotExist()) - i++; - } - - count = 0; - for (CloudQueue queue : qClient.listQueues()) { - Assert.assertNotNull(queue); - count++; - } - } - - Assert.assertTrue(count >= totalLimit); - - ResultSegment segment = qClient.listQueuesSegmented(); - Assert.assertTrue(segment.getLength() == 5000); - Assert.assertTrue(segment.getContinuationToken() != null); - } - - @Test - public void testListQueuesSegmented() throws URISyntaxException, StorageException { - String perfix = "segment" + UUID.randomUUID().toString().substring(0, 8).toLowerCase(); - - HashMap metadata1 = new HashMap(); - metadata1.put("ExistingMetadata1", "ExistingMetadataValue1"); - - for (int i = 0; i < 35; i++) { - CloudQueue q = new CloudQueue(AppendQueueName(httpAcc.getQueueEndpoint(), perfix - + UUID.randomUUID().toString().toLowerCase()), qClient); - q.setMetadata(metadata1); - q.create(); - } - - ResultSegment segment1 = qClient.listQueuesSegmented(perfix); - Assert.assertTrue(segment1.getLength() == 35); - - ResultSegment segment2 = qClient.listQueuesSegmented(perfix, QueueListingDetails.NONE, 5, null, - null, null); - Assert.assertTrue(segment2.getLength() == 5); - - int totalRoundTrip = 1; - while (segment2.getHasMoreResults()) { - segment2 = qClient.listQueuesSegmented(perfix, QueueListingDetails.NONE, 5, - segment2.getContinuationToken(), null, null); - Assert.assertTrue(segment2.getLength() == 5); - totalRoundTrip++; - } - - Assert.assertTrue(totalRoundTrip == 7); - - ResultSegment segment3 = qClient.listQueuesSegmented(perfix, QueueListingDetails.NONE, 0, null, - null, null); - Assert.assertTrue(segment3.getLength() == 35); - } - - @Test - public void testListQueuesEqual() throws URISyntaxException, StorageException { - int count1 = 0; - for (CloudQueue queue : qClient.listQueues()) { - Assert.assertNotNull(queue); - count1++; - } - - int count2 = 0; - for (CloudQueue queue : qClient.listQueues("")) { - Assert.assertNotNull(queue); - count2++; - } - - int count3 = 0; - for (CloudQueue queue : qClient.listQueues(null)) { - Assert.assertNotNull(queue); - count3++; - } - - Assert.assertEquals(count1, count2); - Assert.assertEquals(count1, count3); - } - - @Test - public void testTimeout() throws URISyntaxException, StorageException { - Assert.assertTrue(qClient.getTimeoutInMs() == 30 * 1000); - qClient.setTimeoutInMs(60 * 1000); - Assert.assertTrue(qClient.getTimeoutInMs() == 60 * 1000); - } - - static String AppendQueueName(URI baseURI, String queueName) throws URISyntaxException { - if (baseURI == null) - return queueName; - - String baseAddress = baseURI.toString(); - if (baseAddress.endsWith("/")) { - return baseAddress + queueName; - } - else { - return baseAddress + "/" + queueName; - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueTests.java deleted file mode 100644 index 2f91a392326cd..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/CloudQueueTests.java +++ /dev/null @@ -1,1394 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.EnumSet; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Random; -import java.util.UUID; - -import javax.xml.stream.XMLStreamException; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.AuthenticationScheme; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Table Client Tests - */ -public class CloudQueueTests extends QueueTestBase { - @Test - public void queueGetSetPermissionTest() throws StorageException, URISyntaxException { - String name = generateRandomQueueName(); - CloudQueue newQueue = qClient.getQueueReference(name); - newQueue.create(); - - QueuePermissions expectedPermissions; - QueuePermissions testPermissions; - - try { - // Test new permissions. - expectedPermissions = new QueuePermissions(); - testPermissions = newQueue.downloadPermissions(); - assertQueuePermissionsEqual(expectedPermissions, testPermissions); - - // Test setting empty permissions. - newQueue.uploadPermissions(expectedPermissions); - testPermissions = newQueue.downloadPermissions(); - assertQueuePermissionsEqual(expectedPermissions, testPermissions); - - // Add a policy, check setting and getting. - SharedAccessQueuePolicy policy1 = new SharedAccessQueuePolicy(); - Calendar now = GregorianCalendar.getInstance(); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 10); - policy1.setSharedAccessExpiryTime(now.getTime()); - - policy1.setPermissions(EnumSet.of(SharedAccessQueuePermissions.READ, - SharedAccessQueuePermissions.PROCESSMESSAGES, SharedAccessQueuePermissions.ADD, - SharedAccessQueuePermissions.UPDATE)); - expectedPermissions.getSharedAccessPolicies().put(UUID.randomUUID().toString(), policy1); - - newQueue.uploadPermissions(expectedPermissions); - testPermissions = newQueue.downloadPermissions(); - assertQueuePermissionsEqual(expectedPermissions, testPermissions); - } - finally { - // cleanup - newQueue.deleteIfExists(); - } - } - - @Test - public void testQueueSAS() throws StorageException, URISyntaxException, InvalidKeyException { - String name = generateRandomQueueName(); - CloudQueue newQueue = qClient.getQueueReference(name); - newQueue.create(); - newQueue.addMessage(new CloudQueueMessage("sas queue test")); - - QueuePermissions expectedPermissions; - - try { - expectedPermissions = new QueuePermissions(); - // Add a policy, check setting and getting. - SharedAccessQueuePolicy policy1 = new SharedAccessQueuePolicy(); - Calendar now = GregorianCalendar.getInstance(); - now.add(Calendar.MINUTE, -15); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 30); - policy1.setSharedAccessExpiryTime(now.getTime()); - String identifier = UUID.randomUUID().toString(); - - policy1.setPermissions(EnumSet.of(SharedAccessQueuePermissions.READ, - SharedAccessQueuePermissions.PROCESSMESSAGES, SharedAccessQueuePermissions.ADD, - SharedAccessQueuePermissions.UPDATE)); - expectedPermissions.getSharedAccessPolicies().put(identifier, policy1); - - newQueue.uploadPermissions(expectedPermissions); - - CloudQueueClient queueClientFromIdentifierSAS = getQueueClientForSas(newQueue, null, identifier); - CloudQueue identifierSasQueue = queueClientFromIdentifierSAS.getQueueReference(newQueue.getName()); - - identifierSasQueue.downloadAttributes(); - identifierSasQueue.exists(); - - identifierSasQueue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null); - CloudQueueMessage message1 = identifierSasQueue.retrieveMessage(); - identifierSasQueue.deleteMessage(message1); - - CloudQueueClient queueClientFromPolicySAS = getQueueClientForSas(newQueue, policy1, null); - CloudQueue policySasQueue = queueClientFromPolicySAS.getQueueReference(newQueue.getName()); - policySasQueue.exists(); - policySasQueue.downloadAttributes(); - - policySasQueue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null); - CloudQueueMessage message2 = policySasQueue.retrieveMessage(); - policySasQueue.deleteMessage(message2); - } - finally { - // cleanup - newQueue.deleteIfExists(); - } - } - - private CloudQueueClient getQueueClientForSas(CloudQueue queue, SharedAccessQueuePolicy policy, - String accessIdentifier) throws InvalidKeyException, StorageException { - String sasString = queue.generateSharedAccessSignature(policy, accessIdentifier); - return new CloudQueueClient(qClient.getEndpoint(), new StorageCredentialsSharedAccessSignature(sasString)); - } - - static void assertQueuePermissionsEqual(QueuePermissions expected, QueuePermissions actual) { - HashMap expectedPolicies = expected.getSharedAccessPolicies(); - HashMap actualPolicies = actual.getSharedAccessPolicies(); - Assert.assertEquals("SharedAccessPolicies.Count", expectedPolicies.size(), actualPolicies.size()); - for (String name : expectedPolicies.keySet()) { - Assert.assertTrue("Key" + name + " doesn't exist", actualPolicies.containsKey(name)); - SharedAccessQueuePolicy expectedPolicy = expectedPolicies.get(name); - SharedAccessQueuePolicy actualPolicy = actualPolicies.get(name); - Assert.assertEquals("Policy: " + name + "\tPermissions\n", expectedPolicy.getPermissions().toString(), - actualPolicy.getPermissions().toString()); - Assert.assertEquals("Policy: " + name + "\tStartDate\n", expectedPolicy.getSharedAccessStartTime() - .toString(), actualPolicy.getSharedAccessStartTime().toString()); - Assert.assertEquals("Policy: " + name + "\tExpireDate\n", expectedPolicy.getSharedAccessExpiryTime() - .toString(), actualPolicy.getSharedAccessExpiryTime().toString()); - - } - - } - - @Test - public void testQueueClientConstructor() throws URISyntaxException, StorageException { - String queueName = "queue"; - String baseAddress = AppendQueueName(qClient.getEndpoint(), queueName); - CloudQueue queue1 = new CloudQueue(baseAddress, qClient); - Assert.assertEquals(queueName, queue1.getName()); - Assert.assertTrue(queue1.getUri().toString().endsWith(baseAddress)); - Assert.assertEquals(qClient, queue1.getServiceClient()); - - CloudQueue queue2 = new CloudQueue(new URI(AppendQueueName(qClient.getEndpoint(), queueName)), qClient); - - Assert.assertEquals(queueName, queue2.getName()); - Assert.assertEquals(qClient, queue2.getServiceClient()); - - CloudQueue queue3 = new CloudQueue(queueName, qClient); - Assert.assertEquals(queueName, queue3.getName()); - Assert.assertEquals(qClient, queue3.getServiceClient()); - } - - @Test - public void testGetMetadata() throws URISyntaxException, StorageException { - HashMap metadata = new HashMap(); - metadata.put("ExistingMetadata", "ExistingMetadataValue"); - queue.setMetadata(metadata); - queue.uploadMetadata(); - queue.downloadAttributes(); - Assert.assertEquals(queue.getMetadata().get("ExistingMetadata"), "ExistingMetadataValue"); - Assert.assertTrue(queue.getMetadata().containsKey("ExistingMetadata")); - - HashMap empytMetadata = null; - queue.setMetadata(empytMetadata); - queue.uploadMetadata(); - queue.downloadAttributes(); - Assert.assertTrue(queue.getMetadata().size() == 0); - } - - @Test - public void testUploadMetadata() throws URISyntaxException, StorageException { - CloudQueue queueForGet = new CloudQueue(queue.getUri(), queue.getServiceClient()); - - HashMap metadata1 = new HashMap(); - metadata1.put("ExistingMetadata1", "ExistingMetadataValue1"); - queue.setMetadata(metadata1); - - queueForGet.downloadAttributes(); - Assert.assertFalse(queueForGet.getMetadata().containsKey("ExistingMetadata1")); - - queue.uploadMetadata(); - queueForGet.downloadAttributes(); - Assert.assertTrue(queueForGet.getMetadata().containsKey("ExistingMetadata1")); - } - - @Test - public void testUploadMetadataNullInput() throws URISyntaxException, StorageException { - CloudQueue queueForGet = new CloudQueue(queue.getUri(), queue.getServiceClient()); - - HashMap metadata1 = new HashMap(); - String key = "ExistingMetadata1" + UUID.randomUUID().toString().replace("-", ""); - metadata1.put(key, "ExistingMetadataValue1"); - queue.setMetadata(metadata1); - - queueForGet.downloadAttributes(); - Assert.assertFalse(queueForGet.getMetadata().containsKey(key)); - - queue.uploadMetadata(); - queueForGet.downloadAttributes(); - Assert.assertTrue(queueForGet.getMetadata().containsKey(key)); - - queue.setMetadata(null); - queue.uploadMetadata(); - queueForGet.downloadAttributes(); - Assert.assertTrue(queueForGet.getMetadata().size() == 0); - } - - @Test - public void testUploadMetadataClearExisting() throws URISyntaxException, StorageException { - CloudQueue queueForGet = new CloudQueue(queue.getUri(), queue.getServiceClient()); - - HashMap metadata1 = new HashMap(); - String key = "ExistingMetadata1" + UUID.randomUUID().toString().replace("-", ""); - metadata1.put(key, "ExistingMetadataValue1"); - queue.setMetadata(metadata1); - - queueForGet.downloadAttributes(); - Assert.assertFalse(queueForGet.getMetadata().containsKey(key)); - - HashMap metadata2 = new HashMap(); - queue.setMetadata(metadata2); - queue.uploadMetadata(); - queueForGet.downloadAttributes(); - Assert.assertTrue(queueForGet.getMetadata().size() == 0); - } - - @Test - public void testUploadMetadataNotFound() throws URISyntaxException, StorageException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - try { - newQueue.uploadMetadata(); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND); - - } - } - - @Test - public void testQueueCreate() throws URISyntaxException, StorageException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - try { - HashMap metadata1 = new HashMap(); - metadata1.put("ExistingMetadata1", "ExistingMetadataValue1"); - queue.setMetadata(metadata1); - queue.create(); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT); - - } - - queue.downloadAttributes(); - OperationContext createQueueContext2 = new OperationContext(); - queue.create(null, createQueueContext2); - Assert.assertEquals(createQueueContext2.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - queue.delete(); - } - - @Test - public void testQueueCreateAlreadyExists() throws URISyntaxException, StorageException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext1 = new OperationContext(); - queue.create(null, createQueueContext1); - Assert.assertEquals(createQueueContext1.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - OperationContext createQueueContext2 = new OperationContext(); - queue.create(null, createQueueContext2); - Assert.assertEquals(createQueueContext2.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - @Test - public void testQueueCreateAfterDelete() throws URISyntaxException, StorageException { - - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext1 = new OperationContext(); - Assert.assertTrue(queue.createIfNotExist(null, createQueueContext1)); - Assert.assertEquals(createQueueContext1.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - Assert.assertTrue(queue.deleteIfExists()); - try { - queue.create(); - Assert.fail("Queue CreateIfNotExists did not throw exception while trying to create a queue in BeingDeleted State"); - } - catch (StorageException ex) { - Assert.assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex.getHttpStatusCode(), - HttpURLConnection.HTTP_CONFLICT); - Assert.assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex - .getExtendedErrorInformation().getErrorCode(), StorageErrorCodeStrings.QUEUE_BEING_DELETED); - } - } - - @Test - public void testQueueCreateIfNotExists() throws URISyntaxException, StorageException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext = new OperationContext(); - Assert.assertTrue(queue.createIfNotExist(null, createQueueContext)); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - } - - @Test - public void testQueueCreateIfNotExistsAfterCreate() throws URISyntaxException, StorageException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext1 = new OperationContext(); - Assert.assertTrue(queue.createIfNotExist(null, createQueueContext1)); - Assert.assertEquals(createQueueContext1.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - OperationContext createQueueContext2 = new OperationContext(); - Assert.assertFalse(queue.createIfNotExist(null, createQueueContext2)); - Assert.assertEquals(createQueueContext2.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - @Test - public void testQueueCreateIfNotExistsAfterDelete() throws URISyntaxException, StorageException { - - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext1 = new OperationContext(); - Assert.assertTrue(queue.createIfNotExist(null, createQueueContext1)); - Assert.assertEquals(createQueueContext1.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - Assert.assertTrue(queue.deleteIfExists()); - try { - queue.createIfNotExist(); - Assert.fail("Queue CreateIfNotExists did not throw exception while trying to create a queue in BeingDeleted State"); - } - catch (StorageException ex) { - Assert.assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex.getHttpStatusCode(), - HttpURLConnection.HTTP_CONFLICT); - Assert.assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex - .getExtendedErrorInformation().getErrorCode(), StorageErrorCodeStrings.QUEUE_BEING_DELETED); - } - } - - @Test - public void testQueueDelete() throws URISyntaxException, StorageException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - OperationContext deleteQueueContext = new OperationContext(); - queue.delete(null, deleteQueueContext); - Assert.assertEquals(deleteQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - try { - queue.downloadAttributes(); - Assert.fail(); - } - catch (StorageException ex) { - Assert.assertEquals("Expected 404 Exception", ex.getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - } - - queue.delete(); - } - - @Test - public void testDeleteQueueIfExists() throws URISyntaxException, StorageException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - - Assert.assertFalse(queue.deleteIfExists()); - - final OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - Assert.assertTrue(queue.deleteIfExists()); - - try { - queue.create(); - Assert.fail("Queue CreateIfNotExists did not throw exception while trying to create a queue in BeingDeleted State"); - } - catch (StorageException ex) { - Assert.assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex.getHttpStatusCode(), - HttpURLConnection.HTTP_CONFLICT); - Assert.assertEquals("Expected 409 Exception, QueueBeingDeleted not thrown", ex - .getExtendedErrorInformation().getErrorCode(), StorageErrorCodeStrings.QUEUE_BEING_DELETED); - } - } - - @Test - public void testDeleteNonExistingQueue() throws URISyntaxException, StorageException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - - final OperationContext existQueueContext1 = new OperationContext(); - Assert.assertTrue(!queue.exists(null, existQueueContext1)); - Assert.assertEquals(existQueueContext1.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - - try { - queue.delete(); - Assert.fail("Queue delete no exsiting queue. "); - } - catch (StorageException ex) { - Assert.assertEquals("Expected 404 Exception", ex.getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - } - } - - @Test - public void testQueueExist() throws URISyntaxException, StorageException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - - final OperationContext existQueueContext1 = new OperationContext(); - Assert.assertTrue(!queue.exists(null, existQueueContext1)); - Assert.assertEquals(existQueueContext1.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - - final OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - final OperationContext existQueueContext2 = new OperationContext(); - Assert.assertTrue(queue.exists(null, existQueueContext2)); - Assert.assertEquals(existQueueContext2.getLastResult().getStatusCode(), HttpURLConnection.HTTP_OK); - } - - @Test - public void testClearMessages() throws URISyntaxException, StorageException, UnsupportedEncodingException { - final CloudQueue queue = qClient.getQueueReference(UUID.randomUUID().toString().toLowerCase()); - queue.create(); - - CloudQueueMessage message1 = new CloudQueueMessage("messagetest1"); - queue.addMessage(message1); - - CloudQueueMessage message2 = new CloudQueueMessage("messagetest2"); - queue.addMessage(message2); - - int count = 0; - for (CloudQueueMessage m : queue.peekMessages(32)) { - Assert.assertNotNull(m); - count++; - } - - Assert.assertTrue(count == 2); - - OperationContext oc = new OperationContext(); - queue.clear(null, oc); - Assert.assertEquals(oc.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - count = 0; - for (CloudQueueMessage m : queue.peekMessages(32)) { - Assert.assertNotNull(m); - count++; - } - - Assert.assertTrue(count == 0); - } - - public void testClearMessagesEmptyQueue() throws URISyntaxException, StorageException, UnsupportedEncodingException { - final CloudQueue queue = qClient.getQueueReference(UUID.randomUUID().toString().toLowerCase()); - queue.create(); - queue.clear(); - queue.delete(); - } - - public void testClearMessagesNotFound() throws URISyntaxException, StorageException, UnsupportedEncodingException { - final CloudQueue queue = qClient.getQueueReference(UUID.randomUUID().toString().toLowerCase()); - try { - queue.clear(); - Assert.fail(); - } - catch (StorageException ex) { - Assert.assertEquals("Expected 404 Exception", ex.getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - } - } - - @Test - public void testAddMessage() throws URISyntaxException, StorageException, UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(); - - String msgContent = UUID.randomUUID().toString(); - final CloudQueueMessage message = new CloudQueueMessage(msgContent); - queue.addMessage(message); - CloudQueueMessage msgFromRetrieve1 = queue.retrieveMessage(); - Assert.assertEquals(message.getMessageContentAsString(), msgContent); - Assert.assertEquals(msgFromRetrieve1.getMessageContentAsString(), msgContent); - - queue.delete(); - } - - @Test - public void testAddMessageUnicode() throws URISyntaxException, StorageException, UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(); - - ArrayList messages = new ArrayList(); - messages.add("Le débat sur l'identité nationale, l'idée du président Nicolas Sarkozy de déchoir des personnes d'origine étrangère de la nationalité française ... certains cas et les récentes mesures prises contre les Roms ont choqué les experts, qui rendront leurs conclusions le 27 août."); - messages.add("Ваш логин Yahoo! дает доступ к таким мощным инструментам связи, как электронная почта, отправка мгновенных сообщений, функции безопасности, в частности, антивирусные средства и блокировщик всплывающей рекламы, и избранное, например, фото и музыка в сети — все бесплат"); - messages.add("据新华社8月12日电 8月11日晚,舟曲境内再次出现强降雨天气,使特大山洪泥石流灾情雪上加霜。白龙江水在梨坝子村的交汇地带形成一个新的堰塞湖,水位比平时高出3米。甘肃省国土资源厅副厅长张国华当日22时许在新闻发布会上介绍,截至12日21时50分,舟曲堰塞湖堰塞体已消除,溃坝险情已消除,目前针对堰塞湖的主要工作是疏通河道。"); - messages.add("ל כולם\", הדהים יעלון, ויישר קו עם העדות שמסר ראש הממשלה, בנימין נתניהו, לוועדת טירקל. לדבריו, אכן השרים דנו רק בהיבטים התקשורתיים של עצירת המשט: \"בשביעייה לא התקיים דיון על האלטרנטיבות. עסקנו בהיבטים "); - messages.add("Prozent auf 0,5 Prozent. Im Vergleich zum Vorjahresquartal wuchs die deutsche Wirtschaft von Januar bis März um 2,1 Prozent. Auch das ist eine Korrektur nach oben, ursprünglich waren es hier 1,7 Prozent"); - messages.add("\n\n\n\n Computer Parts\n \n Motherboard\n ASUS\n " - + "P3B-F\n 123.00\n \n \n Video Card\n ATI\n All-in-Wonder Pro\n 160.00\n \n \n Sound Card\n " - + "Creative Labs\n Sound Blaster Live\n 80.00\n \n \n inch Monitor\n LG Electronics\n 995E\n 290.00\n \n"); - - for (int i = 0; i < messages.size(); i++) { - String msg = messages.get(i); - queue.addMessage(new CloudQueueMessage(msg)); - CloudQueueMessage readBack = queue.retrieveMessage(); - Assert.assertEquals(msg, readBack.getMessageContentAsString()); - queue.deleteMessage(readBack); - } - - queue.shouldEncodeMessage = false; - for (int i = 0; i < messages.size(); i++) { - String msg = messages.get(i); - queue.addMessage(new CloudQueueMessage(msg)); - CloudQueueMessage readBack = queue.retrieveMessage(); - Assert.assertEquals(msg, readBack.getMessageContentAsString()); - queue.deleteMessage(readBack); - } - - queue.delete(); - } - - @Test - public void testAddMessageLargeVisibilityDelay() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(); - - String msgContent = UUID.randomUUID().toString(); - final CloudQueueMessage message = new CloudQueueMessage(msgContent); - queue.addMessage(message, 100, 50, null, null); - CloudQueueMessage msgFromRetrieve1 = queue.retrieveMessage(); - Assert.assertNull(msgFromRetrieve1); - - queue.delete(); - } - - @Test - public void testDeleteMessageWithDifferentQueueInstance() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue1 = qClient.getQueueReference(queueName); - queue1.create(); - - String msgContent = UUID.randomUUID().toString(); - final CloudQueueMessage message = new CloudQueueMessage(msgContent); - queue1.addMessage(message); - CloudQueueMessage msgFromRetrieved = queue1.retrieveMessage(); - - final CloudQueue queue2 = qClient.getQueueReference(queueName); - queue2.deleteMessage(msgFromRetrieved); - - queue1.delete(); - } - - @Test - public void testAddMessageToNonExistingQueue() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - - String messageContent = "messagetest"; - CloudQueueMessage message1 = new CloudQueueMessage(messageContent); - - try { - newQueue.addMessage(message1); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND); - - } - } - - @Test - public void testQueueUnicodeAndXmlMessageTest() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(); - - String msgContent = "好"; - final CloudQueueMessage message = new CloudQueueMessage(msgContent); - queue.addMessage(message); - CloudQueueMessage msgFromRetrieve1 = queue.retrieveMessage(); - Assert.assertEquals(message.getMessageContentAsString(), msgContent); - Assert.assertEquals(msgFromRetrieve1.getMessageContentAsString(), msgContent); - //Assert.assertEquals(message.getMessageContentAsByte(), msgFromRetrieve1.getMessageContentAsByte()); - - queue.delete(); - } - - @Test - public void testAddMessageLargeMessageInput() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - final OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - final Random rand = new Random(); - - byte[] content = new byte[64 * 1024]; - rand.nextBytes(content); - CloudQueueMessage message1 = new CloudQueueMessage(new String(content)); - - try { - queue.addMessage(message1); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - queue.delete(); - } - - @Test - public void testAddMessageWithVisibilityTimeout() throws URISyntaxException, StorageException, - UnsupportedEncodingException, InterruptedException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(); - queue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null); - CloudQueueMessage m1 = queue.retrieveMessage(); - Date d1 = m1.getExpirationTime(); - queue.deleteMessage(m1); - - Thread.sleep(2000); - - queue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null); - CloudQueueMessage m2 = queue.retrieveMessage(); - Date d2 = m2.getExpirationTime(); - queue.deleteMessage(m2); - Assert.assertTrue(d1.before(d2)); - } - - @Test - public void testAddMessageNullMessage() throws URISyntaxException, StorageException, UnsupportedEncodingException { - try { - queue.addMessage(null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - } - - @Test - public void testAddMessageSpecialVisibilityTimeout() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - final OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - CloudQueueMessage message = new CloudQueueMessage("test"); - queue.addMessage(message, 1, 0, null, null); - queue.addMessage(message, 7 * 24 * 60 * 60, 0, null, null); - queue.addMessage(message, 7 * 24 * 60 * 60, 7 * 24 * 60 * 60 - 1, null, null); - - try { - queue.addMessage(message, -1, 0, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.addMessage(message, 0, -1, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.addMessage(message, 7 * 24 * 60 * 60, 7 * 24 * 60 * 60, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.addMessage(message, 7 * 24 * 60 * 60 + 1, 0, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.addMessage(message, 0, 7 * 24 * 60 * 60 + 1, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.updateMessage(message, 0, EnumSet.of(MessageUpdateFields.CONTENT), null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - queue.delete(); - } - - @Test - public void testDeleteMessage() throws URISyntaxException, StorageException, UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - - CloudQueueMessage message1 = new CloudQueueMessage("messagetest1"); - newQueue.addMessage(message1); - - CloudQueueMessage message2 = new CloudQueueMessage("messagetest2"); - newQueue.addMessage(message2); - - for (CloudQueueMessage message : newQueue.retrieveMessages(32)) { - OperationContext deleteQueueContext = new OperationContext(); - newQueue.deleteMessage(message, null, deleteQueueContext); - Assert.assertEquals(deleteQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - Assert.assertTrue(newQueue.retrieveMessage() == null); - } - - @Test - public void testQueueCreateAddingMetaData() throws URISyntaxException, StorageException { - final CloudQueue queue = qClient.getQueueReference(UUID.randomUUID().toString().toLowerCase()); - - final HashMap metadata = new HashMap(5); - for (int i = 0; i < 5; i++) { - metadata.put("key" + i, "value" + i); - } - - queue.setMetadata(metadata); - - final OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - } - - @Test - public void testDeleteMessageNullMessage() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - try { - queue.deleteMessage(null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - } - - @Test - public void testRetrieveMessage() throws URISyntaxException, StorageException, UnsupportedEncodingException, - InterruptedException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - newQueue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null); - OperationContext opContext = new OperationContext(); - CloudQueueMessage message1 = newQueue.retrieveMessage(10, null /*QueueRequestOptions*/, opContext); - Date expirationTime1 = message1.getExpirationTime(); - Date insertionTime1 = message1.getInsertionTime(); - Date nextVisibleTime1 = message1.getNextVisibleTime(); - - Assert.assertEquals(HttpURLConnection.HTTP_OK, opContext.getLastResult().getStatusCode()); - - newQueue.deleteMessage(message1); - - Thread.sleep(2000); - - newQueue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null); - CloudQueueMessage message2 = newQueue.retrieveMessage(); - Date expirationTime2 = message2.getExpirationTime(); - Date insertionTime2 = message2.getInsertionTime(); - Date nextVisibleTime2 = message2.getNextVisibleTime(); - newQueue.deleteMessage(message2); - Assert.assertTrue(expirationTime1.before(expirationTime2)); - Assert.assertTrue(insertionTime1.before(insertionTime2)); - Assert.assertTrue(nextVisibleTime1.before(nextVisibleTime2)); - } - - @Test - public void testRetrieveMessageNonExistingQueue() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - try { - newQueue.retrieveMessage(); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND); - - } - } - - @Test - public void testRetrieveMessageInvalidInput() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - - try { - queue.retrieveMessage(-1, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.retrieveMessage(7 * 24 * 3600 + 1, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - } - - @Test - public void testRetrieveMessagesFromEmptyQueue() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - - for (CloudQueueMessage m : newQueue.retrieveMessages(32)) { - Assert.assertTrue(m.getId() != null); - Assert.assertTrue(m.getPopReceipt() == null); - } - } - - @Test - public void testRetrieveMessagesNonFound() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - try { - newQueue.retrieveMessages(1); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND); - - } - } - - @Test - public void testDequeueCountIncreases() throws URISyntaxException, StorageException, UnsupportedEncodingException, - InterruptedException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - newQueue.addMessage(new CloudQueueMessage("message"), 20, 0, null, null); - CloudQueueMessage message1 = newQueue.retrieveMessage(1, null, null); - Assert.assertTrue(message1.getDequeueCount() == 1); - - for (int i = 2; i < 5; i++) { - Thread.sleep(2000); - CloudQueueMessage message2 = newQueue.retrieveMessage(1, null, null); - Assert.assertTrue(message2.getDequeueCount() == i); - } - - } - - @Test - public void testRetrieveMessageSpecialVisibilityTimeout() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - - try { - queue.retrieveMessage(-1, null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - } - - @Test - public void testRetrieveMessages() throws URISyntaxException, StorageException, UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - - CloudQueueMessage message1 = new CloudQueueMessage("messagetest1"); - newQueue.addMessage(message1); - - CloudQueueMessage message2 = new CloudQueueMessage("messagetest2"); - newQueue.addMessage(message2); - - for (CloudQueueMessage m : newQueue.retrieveMessages(32)) { - Assert.assertTrue(m.getId() != null); - Assert.assertTrue(m.getPopReceipt() != null); - } - } - - @Test - public void testRetrieveMessagesInvalidInput() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.createIfNotExist(); - - for (int i = 0; i < 33; i++) { - queue.addMessage(new CloudQueueMessage("test" + i)); - } - - queue.retrieveMessages(1, 1, null, null); - queue.retrieveMessages(32, 1, null, null); - - try { - queue.retrieveMessages(-1); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.retrieveMessages(0); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.retrieveMessages(33); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - queue.delete(); - } - - @Test - public void testPeekMessage() throws URISyntaxException, StorageException, UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - - CloudQueueMessage message1 = new CloudQueueMessage("messagetest1"); - newQueue.addMessage(message1); - - CloudQueueMessage msg = newQueue.peekMessage(); - Assert.assertTrue(msg.getId() != null); - Assert.assertTrue(msg.getPopReceipt() == null); - - newQueue.delete(); - } - - @Test - public void testPeekMessages() throws URISyntaxException, StorageException, UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - - CloudQueueMessage message1 = new CloudQueueMessage("messagetest1"); - newQueue.addMessage(message1); - - CloudQueueMessage message2 = new CloudQueueMessage("messagetest2"); - newQueue.addMessage(message2); - - for (CloudQueueMessage m : newQueue.peekMessages(32)) { - Assert.assertTrue(m.getId() != null); - Assert.assertTrue(m.getPopReceipt() == null); - } - - newQueue.delete(); - } - - @Test - public void testPeekMessagesInvalidInput() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.createIfNotExist(); - - for (int i = 0; i < 33; i++) { - queue.addMessage(new CloudQueueMessage("test" + i)); - } - - queue.peekMessages(1); - queue.peekMessages(32); - - try { - queue.peekMessages(-1); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.peekMessages(0); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - try { - queue.peekMessages(33); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - queue.delete(); - } - - @Test - public void testPeekMessageNonExistingQueue() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - try { - newQueue.peekMessage(); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND); - - } - } - - @Test - public void testPeekMessagesNonFound() throws URISyntaxException, StorageException, UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - try { - newQueue.peekMessages(1); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND); - - } - } - - @Test - public void testPeekMessagesFromEmptyQueue() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - - for (CloudQueueMessage m : newQueue.peekMessages(32)) { - Assert.assertTrue(m.getId() != null); - Assert.assertTrue(m.getPopReceipt() == null); - } - } - - @Test - public void testUpdateMessage() throws URISyntaxException, StorageException, UnsupportedEncodingException { - - queue.clear(); - - String messageContent = "messagetest"; - CloudQueueMessage message1 = new CloudQueueMessage(messageContent); - queue.addMessage(message1); - - CloudQueueMessage message2 = new CloudQueueMessage(messageContent); - queue.addMessage(message2); - - String newMesage = message1.getMessageContentAsString() + "updated"; - - for (CloudQueueMessage message : queue.retrieveMessages(32)) { - OperationContext oc = new OperationContext(); - message.setMessageContent(newMesage); - queue.updateMessage(message, 0, EnumSet.of(MessageUpdateFields.VISIBILITY), null, oc); - Assert.assertEquals(oc.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - CloudQueueMessage messageFromGet = queue.retrieveMessage(); - Assert.assertEquals(messageFromGet.getMessageContentAsString(), messageContent); - } - } - - @Test - public void testUpdateMessageFullPass() throws URISyntaxException, StorageException, UnsupportedEncodingException, - InterruptedException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - newQueue.create(); - CloudQueueMessage message = new CloudQueueMessage("message"); - newQueue.addMessage(message, 20, 0, null, null); - CloudQueueMessage message1 = newQueue.retrieveMessage(); - String popreceipt1 = message1.getPopReceipt(); - Date NextVisibleTim1 = message1.getNextVisibleTime(); - newQueue.updateMessage(message1, 100, EnumSet.of(MessageUpdateFields.VISIBILITY), null, null); - String popreceipt2 = message1.getPopReceipt(); - Date NextVisibleTim2 = message1.getNextVisibleTime(); - Assert.assertTrue(popreceipt2 != popreceipt1); - Assert.assertTrue(NextVisibleTim1.before(NextVisibleTim2)); - - Thread.sleep(2000); - - String newMesage = message.getMessageContentAsString() + "updated"; - message.setMessageContent(newMesage); - OperationContext oc = new OperationContext(); - newQueue.updateMessage(message1, 100, EnumSet.of(MessageUpdateFields.CONTENT), null, oc); - Assert.assertEquals(oc.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - String popreceipt3 = message1.getPopReceipt(); - Date NextVisibleTim3 = message1.getNextVisibleTime(); - Assert.assertTrue(popreceipt3 != popreceipt2); - Assert.assertTrue(NextVisibleTim2.before(NextVisibleTim3)); - - Assert.assertTrue(newQueue.retrieveMessage() == null); - - newQueue.updateMessage(message1, 0, EnumSet.of(MessageUpdateFields.VISIBILITY), null, null); - - CloudQueueMessage messageFromGet = newQueue.retrieveMessage(); - Assert.assertEquals(messageFromGet.getMessageContentAsString(), message1.getMessageContentAsString()); - } - - @Test - public void testUpdateMessageWithContentChange() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - - CloudQueueMessage message1 = new CloudQueueMessage("messagetest1"); - queue.addMessage(message1); - - CloudQueueMessage message2 = new CloudQueueMessage("messagetest2"); - queue.addMessage(message2); - - for (CloudQueueMessage message : queue.retrieveMessages(32)) { - OperationContext oc = new OperationContext(); - message.setMessageContent(message.getMessageContentAsString() + "updated"); - queue.updateMessage(message, 100, EnumSet.of(MessageUpdateFields.CONTENT), null, oc); - Assert.assertEquals(oc.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - } - - @Test - public void testUpdateMessageNullMessage() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - try { - queue.updateMessage(null, 0); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - } - - @Test - public void testUpdateMessageInvalidMessage() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(null, null); - - CloudQueueMessage message = new CloudQueueMessage("test"); - queue.addMessage(message, 1, 0, null, null); - - try { - queue.updateMessage(message, 0, EnumSet.of(MessageUpdateFields.CONTENT), null, null); - Assert.fail(); - } - catch (final IllegalArgumentException e) { - } - - queue.delete(); - } - - @Test - public void testGetApproximateMessageCount() throws URISyntaxException, StorageException, - UnsupportedEncodingException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(); - Assert.assertTrue(queue.getApproximateMessageCount() == 0); - queue.addMessage(new CloudQueueMessage("message1")); - queue.addMessage(new CloudQueueMessage("message2")); - Assert.assertTrue(queue.getApproximateMessageCount() == 0); - queue.downloadAttributes(); - Assert.assertTrue(queue.getApproximateMessageCount() == 2); - queue.delete(); - } - - @Test - public void testShouldEncodeMessage() throws URISyntaxException, StorageException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - queue.create(); - - String msgContent = UUID.randomUUID().toString(); - final CloudQueueMessage message = new CloudQueueMessage(msgContent); - queue.setShouldEncodeMessage(true); - queue.addMessage(message); - CloudQueueMessage msgFromRetrieve1 = queue.retrieveMessage(); - Assert.assertEquals(msgFromRetrieve1.getMessageContentAsString(), msgContent); - queue.deleteMessage(msgFromRetrieve1); - - queue.setShouldEncodeMessage(false); - queue.addMessage(message); - CloudQueueMessage msgFromRetrieve2 = queue.retrieveMessage(); - Assert.assertEquals(msgFromRetrieve2.getMessageContentAsString(), msgContent); - queue.deleteMessage(msgFromRetrieve2); - - queue.setShouldEncodeMessage(true); - } - - @Test - public void testQueueDownloadAttributes() throws URISyntaxException, StorageException, - UnsupportedEncodingException, XMLStreamException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - - final CloudQueue queue1 = qClient.getQueueReference(queueName); - queue1.create(); - - final CloudQueueMessage message1 = new CloudQueueMessage("messagetest1"); - queue1.addMessage(message1); - - final CloudQueueMessage message2 = new CloudQueueMessage("messagetest2"); - queue1.addMessage(message2); - - final HashMap metadata = new HashMap(5); - int sum = 5; - for (int i = 0; i < sum; i++) { - metadata.put("key" + i, "value" + i); - } - - queue1.setMetadata(metadata); - queue1.uploadMetadata(); - - final CloudQueue queue2 = qClient.getQueueReference(queueName); - queue2.downloadAttributes(); - - System.out.println(queue2.getApproximateMessageCount()); - - int count = 0; - for (final String s : queue2.getMetadata().keySet()) { - count++; - System.out.println(s + ":" + queue2.getMetadata().get(s)); - } - - Assert.assertEquals(count, sum); - - queue1.delete(); - } - - @Test - public void testQueueDownloadAttributesNotFound() throws URISyntaxException, StorageException { - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue newQueue = qClient.getQueueReference(queueName); - try { - newQueue.downloadAttributes(); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND); - - } - } - - @Test - public void testQueueUpdateMetaData() throws URISyntaxException, StorageException { - final String queueName = UUID.randomUUID().toString().toLowerCase(); - final CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - final OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - final HashMap metadata = new HashMap(5); - for (int i = 0; i < 5; i++) { - metadata.put("key" + i, "value" + i); - } - - queue.setMetadata(metadata); - queue.uploadMetadata(); - } - - @Test - public void testSASClientParse() throws StorageException, URISyntaxException, InvalidKeyException { - - // Add a policy, check setting and getting. - SharedAccessQueuePolicy policy1 = new SharedAccessQueuePolicy(); - Calendar now = GregorianCalendar.getInstance(); - now.add(Calendar.MINUTE, -15); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 30); - policy1.setSharedAccessExpiryTime(now.getTime()); - - policy1.setPermissions(EnumSet.of(SharedAccessQueuePermissions.READ, - SharedAccessQueuePermissions.PROCESSMESSAGES, SharedAccessQueuePermissions.ADD, - SharedAccessQueuePermissions.UPDATE)); - - String sasString = queue.generateSharedAccessSignature(policy1, null); - - URI queueUri = new URI("http://myaccount.queue.core.windows.net/myqueue"); - - CloudQueueClient queueClient1 = new CloudQueueClient(new URI("http://myaccount.queue.core.windows.net/"), - new StorageCredentialsSharedAccessSignature(sasString)); - - CloudQueue queue1 = new CloudQueue(queueUri, queueClient1); - queue1.getName(); - - CloudQueueClient queueClient2 = new CloudQueueClient(new URI("http://myaccount.queue.core.windows.net/"), - new StorageCredentialsSharedAccessSignature(sasString)); - CloudQueue queue2 = new CloudQueue(queueUri, queueClient2); - queue2.getName(); - } - - @Test - public void testQueueSharedKeyLite() throws URISyntaxException, StorageException { - qClient.setAuthenticationScheme(AuthenticationScheme.SHAREDKEYLITE); - String queueName = UUID.randomUUID().toString().toLowerCase(); - CloudQueue queue = qClient.getQueueReference(queueName); - Assert.assertEquals(queueName, queue.getName()); - - OperationContext createQueueContext = new OperationContext(); - queue.create(null, createQueueContext); - Assert.assertEquals(createQueueContext.getLastResult().getStatusCode(), HttpURLConnection.HTTP_CREATED); - - try { - HashMap metadata1 = new HashMap(); - metadata1.put("ExistingMetadata1", "ExistingMetadataValue1"); - queue.setMetadata(metadata1); - queue.create(); - Assert.fail(); - } - catch (StorageException e) { - Assert.assertTrue(e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT); - - } - - queue.downloadAttributes(); - OperationContext createQueueContext2 = new OperationContext(); - queue.create(null, createQueueContext2); - Assert.assertEquals(createQueueContext2.getLastResult().getStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - queue.delete(); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/QueueTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/QueueTestBase.java deleted file mode 100644 index 4ccfa9f781365..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/queue/client/QueueTestBase.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.queue.client; - -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; - -import com.microsoft.windowsazure.services.core.storage.AuthenticationScheme; -import com.microsoft.windowsazure.services.core.storage.CloudStorageAccount; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Queue Test Base - * Queue test refactoring will be done in future. - */ -public class QueueTestBase { - public static boolean USE_DEV_FABRIC = false; - public static final String CLOUD_ACCOUNT_HTTP = "DefaultEndpointsProtocol=http;AccountName=[ACCOUNT NAME];AccountKey=[ACCOUNT KEY]"; - public static final String CLOUD_ACCOUNT_HTTPS = "DefaultEndpointsProtocol=https;AccountName=[ACCOUNT NAME];AccountKey=[ACCOUNT KEY]"; - - protected static CloudStorageAccount httpAcc; - protected static CloudQueueClient qClient; - protected static String testSuiteQueueName = generateRandomQueueName(); - protected static CloudQueue queue; - - @BeforeClass - public static void setup() throws URISyntaxException, StorageException, InvalidKeyException { - if (USE_DEV_FABRIC) { - httpAcc = CloudStorageAccount.getDevelopmentStorageAccount(); - } - else { - String cloudAccount = CLOUD_ACCOUNT_HTTP; - cloudAccount = cloudAccount.replace("[ACCOUNT NAME]", System.getenv("queue.accountName")); - cloudAccount = cloudAccount.replace("[ACCOUNT KEY]", System.getenv("queue.accountKey")); - - httpAcc = CloudStorageAccount.parse(cloudAccount); - } - - qClient = httpAcc.createCloudQueueClient(); - qClient.setAuthenticationScheme(AuthenticationScheme.SHAREDKEYFULL); - testSuiteQueueName = generateRandomQueueName(); - queue = qClient.getQueueReference(testSuiteQueueName); - queue.create(); - } - - @AfterClass - public static void teardown() throws StorageException, URISyntaxException { - CloudQueue queue = qClient.getQueueReference(testSuiteQueueName); - queue.delete(); - } - - protected static String generateRandomQueueName() { - String queueName = "queue" + UUID.randomUUID().toString(); - return queueName.replace("-", ""); - } - - static String AppendQueueName(URI baseURI, String queueName) throws URISyntaxException { - if (baseURI == null) - return queueName; - - String baseAddress = baseURI.toString(); - if (baseAddress.endsWith("/")) { - return baseAddress + queueName; - } - else { - return baseAddress + "/" + queueName; - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceValidation.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceValidation.java deleted file mode 100644 index 45c8611da58c5..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceValidation.java +++ /dev/null @@ -1,251 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.scenarios; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.InputStream; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.List; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.media.MediaContract; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetFile; -import com.microsoft.windowsazure.services.media.models.AssetFileInfo; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.AssetOption; -import com.microsoft.windowsazure.services.media.models.AssetState; -import com.microsoft.windowsazure.services.media.models.ContentKey; -import com.microsoft.windowsazure.services.media.models.ContentKeyInfo; -import com.microsoft.windowsazure.services.media.models.JobInfo; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.Task; - -class MediaServiceValidation { - private final MediaContract service; - - public MediaServiceValidation(MediaContract service) { - this.service = service; - } - - public void validateAsset(AssetInfo asset, String name, AssetOption encryption) throws ServiceException { - // Check the asset state. - assertNotNull("asset", asset); - assertNotNull("asset.getId", asset.getId()); - assertFalse("asset.getId != ''", "".equals(asset.getId())); - assertEquals("asset.state", AssetState.Initialized, asset.getState()); - assertEquals("asset.getOptions", encryption, asset.getOptions()); - - // Verify no files by default. - List initialFiles = service.list(AssetFile.list(asset.getAssetFilesLink())); - assertNotNull("initialFiles", initialFiles); - assertEquals("initialFiles.size", 0, initialFiles.size()); - - // Reload asset from server for ID - AssetInfo reloadedAsset = service.get(Asset.get(asset.getId())); - - // Verify names match - assertNotNull("reloadedAsset", reloadedAsset); - assertNotNull("reloadedAsset.getId", reloadedAsset.getId()); - assertEquals("reloadedAsset.getId, asset.getId", asset.getId(), reloadedAsset.getId()); - assertEquals("reloadedAsset.state", AssetState.Initialized, reloadedAsset.getState()); - assertEquals("reloadedAsset.getOptions", encryption, reloadedAsset.getOptions()); - } - - public void validateAssetSortedPages(List> pages, List assetNames, int pageSize) { - int sumSizeOfPages = 0; - List actualAssetNames = new ArrayList(); - - for (ListResult page : pages) { - sumSizeOfPages += page.size(); - for (AssetInfo asset : page) { - actualAssetNames.add(asset.getName()); - } - } - - assertEquals("sumSizeOfPages", assetNames.size(), sumSizeOfPages); - assertEquals("size of last page", 0, pages.get(pages.size() - 1).size()); - - // Do not worry about comparing the details of the sorted pages, - // because Media Services splits on the internal order, then sorts - // each page individually. - } - - public void validateAssetFiles(AssetInfo asset, Hashtable inputFiles) throws ServiceException, - IOException, NoSuchAlgorithmException { - List assetFiles = service.list(AssetFile.list(asset.getAssetFilesLink())); - - assertNotNull("assetFiles", assetFiles); - assertEquals("assetFiles.size", inputFiles.size(), assetFiles.size()); - - ContentKeyInfo contentKey = null; - if (asset.getOptions() == AssetOption.StorageEncrypted) { - ListResult contentKeys = service.list(ContentKey.list(asset.getContentKeysLink())); - assertEquals("contentKeys size", 1, contentKeys.size()); - contentKey = contentKeys.get(0); - } - - // Compare encryption info for asset files - for (AssetFileInfo assetFile : assetFiles) { - if (asset.getOptions() == AssetOption.StorageEncrypted) { - assertEquals("assetFile.getIsEncrypted", true, assetFile.getIsEncrypted()); - assertEquals("assetFile.getEncryptionKeyId", contentKey.getId(), assetFile.getEncryptionKeyId()); - assertNotNullOrEmpty("assetFile.getEncryptionScheme", assetFile.getEncryptionScheme()); - assertNotNullOrEmpty("assetFile.getEncryptionVersion", assetFile.getEncryptionVersion()); - assertNotNullOrEmpty("assetFile.getInitializationVector", assetFile.getInitializationVector()); - } - else { - assertEquals("assetFile.getIsEncrypted", false, assetFile.getIsEncrypted()); - assertNullOrEmpty("assetFile.getEncryptionKeyId", assetFile.getEncryptionKeyId()); - assertNullOrEmpty("assetFile.getEncryptionScheme", assetFile.getEncryptionScheme()); - assertNullOrEmpty("assetFile.getEncryptionVersion", assetFile.getEncryptionVersion()); - assertNullOrEmpty("assetFile.getInitializationVector", assetFile.getInitializationVector()); - } - } - - // Compare the asset files with all files - List allFiles = service.list(AssetFile.list()); - for (AssetFileInfo assetFile : assetFiles) { - assertEquals("fi.getParentAssetId", asset.getId(), assetFile.getParentAssetId()); - AssetFileInfo match = null; - for (AssetFileInfo aFile : allFiles) { - if (aFile.getId().equals(assetFile.getId())) { - match = aFile; - break; - } - } - - assertFileInfosEqual("match from all files", assetFile, match); - } - } - - public void validateAssetFiles(Hashtable inputFiles, - Hashtable actualFileStreams) throws IOException, InterruptedException { - assertEquals("fileUrls count", inputFiles.size(), actualFileStreams.size()); - for (String fileName : actualFileStreams.keySet()) { - InputStream expected = inputFiles.get(fileName); - InputStream actual = actualFileStreams.get(fileName); - assertStreamsEqual(expected, actual); - } - } - - public void validateJob(JobInfo job, String name, AssetInfo asset, List createTasks) - throws ServiceException { - assertDateApproxEquals("getEndTime", new Date(), job.getCreated()); - assertEquals("job.getName", name, job.getName()); - - List inputAssets = service.list(Asset.list(job.getInputAssetsLink())); - assertNotNull("inputAssets", inputAssets); - assertEquals("inputAssets.size()", 1, inputAssets.size()); - assertEquals("inputAssets.get(0)", asset.getId(), inputAssets.get(0).getId()); - - List outputAssets = service.list(Asset.list(job.getOutputAssetsLink())); - assertNotNull("outputAssets", outputAssets); - assertEquals("outputAssets.size()", createTasks.size(), outputAssets.size()); - } - - public void validateOutputAssets(List outputAssets, Enumeration enumeration) { - assertNotNull("outputAssets", outputAssets); - for (AssetInfo asset : outputAssets) { - assertNotNull("asset", asset); - assertNotNull("asset.getId", asset.getId()); - assertFalse("asset.getId != ''", "".equals(asset.getId())); - assertEquals("asset.state", AssetState.Initialized, asset.getState()); - assertEquals("asset.getOptions", AssetOption.None, asset.getOptions()); - } - } - - public void assertFileInfosEqual(String message, AssetFileInfo fi, AssetFileInfo match) { - assertNotNull(message + ":fi", fi); - assertNotNull(message + ":match", match); - assertEquals(message + ":getContentChecksum", fi.getContentChecksum(), match.getContentChecksum()); - assertEquals(message + ":getContentFileSize", fi.getContentFileSize(), match.getContentFileSize()); - assertEquals(message + ":getCreated", fi.getCreated(), match.getCreated()); - assertEquals(message + ":getEncryptionKeyId", fi.getEncryptionKeyId(), match.getEncryptionKeyId()); - assertEquals(message + ":getEncryptionScheme", fi.getEncryptionScheme(), match.getEncryptionScheme()); - assertEquals(message + ":getEncryptionVersion", fi.getEncryptionVersion(), match.getEncryptionVersion()); - assertEquals(message + ":getId", fi.getId(), match.getId()); - assertEquals(message + ":getIsEncrypted", fi.getIsEncrypted(), match.getIsEncrypted()); - assertEquals(message + ":getIsPrimary", fi.getIsPrimary(), match.getIsPrimary()); - assertEquals(message + ":getLastModified", fi.getLastModified(), match.getLastModified()); - assertEquals(message + ":getMimeType", fi.getMimeType(), match.getMimeType()); - assertEquals(message + ":getName", fi.getName(), match.getName()); - assertEquals(message + ":getParentAssetId", fi.getParentAssetId(), match.getParentAssetId()); - } - - protected void assertDateApproxEquals(String message, Date expected, Date actual) { - // Default allows for a 30 seconds difference in dates, for clock skew, network delays, etc. - long deltaInMilliseconds = 30000; - - if (expected == null || actual == null) { - assertEquals(message, expected, actual); - } - else { - long diffInMilliseconds = Math.abs(expected.getTime() - actual.getTime()); - - if (diffInMilliseconds > deltaInMilliseconds) { - assertEquals(message, expected, actual); - } - } - } - - private void assertStreamsEqual(InputStream inputStream1, InputStream inputStream2) throws IOException { - byte[] buffer1 = new byte[1024]; - byte[] buffer2 = new byte[1024]; - try { - while (true) { - int n1 = inputStream1.read(buffer1); - int n2 = inputStream2.read(buffer2); - assertEquals("number of bytes read from streams", n1, n2); - if (n1 == -1) { - break; - } - for (int i = 0; i < n1; i++) { - assertEquals("byte " + i + " read from streams", buffer1[i], buffer2[i]); - } - } - } - finally { - inputStream1.close(); - inputStream2.close(); - } - } - - private void assertNullOrEmpty(String message, String actual) { - if (actual == null) { - assertNull(message, actual); - } - else { - assertEquals(message, "", actual); - } - } - - private void assertNotNullOrEmpty(String message, String actual) { - if (actual == null) { - assertNotNull(message, actual); - } - else { - assertTrue(message + ": expect " + actual + " to be null or empty", actual.length() > 0); - } - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceWrapper.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceWrapper.java deleted file mode 100644 index 4401044999b3d..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/scenarios/MediaServiceWrapper.java +++ /dev/null @@ -1,494 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.scenarios; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.DigestInputStream; -import java.security.Key; -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Hashtable; -import java.util.List; -import java.util.Random; -import java.util.UUID; - -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import junit.framework.Assert; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.storage.utils.Base64; -import com.microsoft.windowsazure.services.media.MediaContract; -import com.microsoft.windowsazure.services.media.WritableBlobContainerContract; -import com.microsoft.windowsazure.services.media.entityoperations.EntityListOperation; -import com.microsoft.windowsazure.services.media.implementation.content.AssetFileType; -import com.microsoft.windowsazure.services.media.models.AccessPolicy; -import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo; -import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission; -import com.microsoft.windowsazure.services.media.models.Asset; -import com.microsoft.windowsazure.services.media.models.AssetFile; -import com.microsoft.windowsazure.services.media.models.AssetFile.Updater; -import com.microsoft.windowsazure.services.media.models.AssetFileInfo; -import com.microsoft.windowsazure.services.media.models.AssetInfo; -import com.microsoft.windowsazure.services.media.models.AssetOption; -import com.microsoft.windowsazure.services.media.models.ContentKey; -import com.microsoft.windowsazure.services.media.models.ContentKeyType; -import com.microsoft.windowsazure.services.media.models.Job; -import com.microsoft.windowsazure.services.media.models.Job.Creator; -import com.microsoft.windowsazure.services.media.models.JobInfo; -import com.microsoft.windowsazure.services.media.models.ListResult; -import com.microsoft.windowsazure.services.media.models.Locator; -import com.microsoft.windowsazure.services.media.models.LocatorInfo; -import com.microsoft.windowsazure.services.media.models.LocatorType; -import com.microsoft.windowsazure.services.media.models.MediaProcessor; -import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo; -import com.microsoft.windowsazure.services.media.models.ProtectionKey; -import com.microsoft.windowsazure.services.media.models.Task; - -class MediaServiceWrapper { - private final MediaContract service; - - private static final String accessPolicyPrefix = "scenarioTestPrefix"; - - private final String MEDIA_PROCESSOR_STORAGE_DECRYPTION = "Storage Decryption"; - private final String MEDIA_PROCESSOR_WINDOWS_AZURE_MEDIA_ENCODER = "Windows Azure Media Encoder"; - - public static enum EncoderType { - WindowsAzureMediaEncoder, StorageDecryption - } - - public MediaServiceWrapper(MediaContract service) { - this.service = service; - } - - // Manage - public AssetInfo createAsset(String name, AssetOption encryption) throws ServiceException { - if (encryption == AssetOption.StorageEncrypted && !EncryptionHelper.canUseStrongCrypto()) { - Assert.fail("JVM does not support the required encryption"); - } - - // Create asset. The SDK's top-level method is the simplest way to do that. - return service.create(Asset.create().setName(name).setAlternateId("altId").setOptions(encryption)); - } - - public List> getAssetSortedPagedResults(String rootName, int pageSize) - throws ServiceException { - List> pages = new ArrayList>(); - for (int skip = 0; true; skip += pageSize) { - EntityListOperation listOperation = Asset.list().setTop(pageSize).setSkip(skip) - .set("$filter", "startswith(Name,'" + rootName + "')").set("$orderby", "Name"); - - ListResult listAssetResult = service.list(listOperation); - pages.add(listAssetResult); - if (listAssetResult.size() == 0) { - break; - } - } - - return pages; - } - - // Ingest - public void uploadFilesToAsset(AssetInfo asset, int uploadWindowInMinutes, Hashtable inputFiles) - throws Exception { - uploadFilesToAsset(asset, uploadWindowInMinutes, inputFiles, null); - } - - public void uploadFilesToAsset(AssetInfo asset, int uploadWindowInMinutes, - Hashtable inputFiles, byte[] aesKey) throws Exception { - AccessPolicyInfo accessPolicy = service.create(AccessPolicy.create(accessPolicyPrefix + "tempAccessPolicy", - uploadWindowInMinutes, EnumSet.of(AccessPolicyPermission.WRITE))); - LocatorInfo locator = service.create(Locator.create(accessPolicy.getId(), asset.getId(), LocatorType.SAS)); - - String contentKeyId = createAssetContentKey(asset, aesKey); - - WritableBlobContainerContract uploader = service.createBlobWriter(locator); - - Hashtable infoToUpload = new Hashtable(); - - boolean isFirst = true; - for (String fileName : inputFiles.keySet()) { - MessageDigest digest = MessageDigest.getInstance("MD5"); - - InputStream inputStream = inputFiles.get(fileName); - - byte[] iv = null; - if (aesKey != null) { - iv = createIV(); - inputStream = EncryptionHelper.encryptFile(inputStream, aesKey, iv); - } - - InputStream digestStream = new DigestInputStream(inputStream, digest); - CountingStream countingStream = new CountingStream(digestStream); - uploader.createBlockBlob(fileName, countingStream); - - inputStream.close(); - byte[] md5hash = digest.digest(); - String md5 = Base64.encode(md5hash); - - AssetFileInfo fi = new AssetFileInfo(null, new AssetFileType().setContentChecksum(md5) - .setContentFileSize(countingStream.getCount()).setIsPrimary(isFirst).setName(fileName) - .setInitializationVector(getIVString(iv))); - infoToUpload.put(fileName, fi); - - isFirst = false; - } - - service.action(AssetFile.createFileInfos(asset.getId())); - for (AssetFileInfo assetFile : service.list(AssetFile.list(asset.getAssetFilesLink()))) { - AssetFileInfo fileInfo = infoToUpload.get(assetFile.getName()); - Updater updateOp = AssetFile.update(assetFile.getId()).setContentChecksum(fileInfo.getContentChecksum()) - .setContentFileSize(fileInfo.getContentFileSize()).setIsPrimary(fileInfo.getIsPrimary()); - - if (aesKey != null) { - updateOp.setIsEncrypted(true).setEncryptionKeyId(contentKeyId).setEncryptionScheme("StorageEncryption") - .setEncryptionVersion("1.0").setInitializationVector(fileInfo.getInitializationVector()); - } - - service.update(updateOp); - } - - service.list(AssetFile.list(asset.getAssetFilesLink())); - - service.delete(Locator.delete(locator.getId())); - service.delete(AccessPolicy.delete(accessPolicy.getId())); - } - - private String getIVString(byte[] iv) { - if (iv == null) { - return null; - } - - // Offset the bytes to ensure that the sign-bit is not set. - // Media Services expects unsigned Int64 values. - byte[] sub = new byte[9]; - System.arraycopy(iv, 0, sub, 1, 8); - BigInteger longIv = new BigInteger(sub); - return longIv.toString(); - } - - private byte[] createIV() { - // Media Services requires 128-bit (16-byte) initialization vectors (IV) - // for AES encryption, but also that only the first 8 bytes are filled. - Random random = new Random(); - byte[] effectiveIv = new byte[8]; - random.nextBytes(effectiveIv); - byte[] iv = new byte[16]; - System.arraycopy(effectiveIv, 0, iv, 0, effectiveIv.length); - return iv; - } - - private String createAssetContentKey(AssetInfo asset, byte[] aesKey) throws Exception { - if (aesKey == null) { - return null; - } - - String protectionKeyId = service.action(ProtectionKey.getProtectionKeyId(ContentKeyType.StorageEncryption)); - String protectionKey = service.action(ProtectionKey.getProtectionKey(protectionKeyId)); - - String contentKeyIdUuid = UUID.randomUUID().toString(); - String contentKeyId = "nb:kid:UUID:" + contentKeyIdUuid; - - byte[] encryptedContentKey = EncryptionHelper.encryptSymmetricKey(protectionKey, aesKey); - String encryptedContentKeyString = Base64.encode(encryptedContentKey); - String checksum = EncryptionHelper.calculateContentKeyChecksum(contentKeyIdUuid, aesKey); - - service.create(ContentKey.create(contentKeyId, ContentKeyType.StorageEncryption, encryptedContentKeyString) - .setChecksum(checksum).setProtectionKeyId(protectionKeyId)); - service.action(Asset.linkContentKey(asset.getId(), contentKeyId)); - return contentKeyId; - } - - private static class CountingStream extends InputStream { - private final InputStream wrappedStream; - private long count; - - public CountingStream(InputStream wrapped) { - wrappedStream = wrapped; - count = 0; - } - - @Override - public int read() throws IOException { - count++; - return wrappedStream.read(); - } - - public long getCount() { - return count; - } - } - - // Process - public JobInfo createJob(String jobName, AssetInfo inputAsset, Task.CreateBatchOperation task) - throws ServiceException { - List tasks = new ArrayList(); - tasks.add(task); - return createJob(jobName, inputAsset, tasks); - } - - public JobInfo createJob(String jobName, AssetInfo inputAsset, List tasks) - throws ServiceException { - Creator jobCreator = Job.create().setName(jobName).addInputMediaAsset(inputAsset.getId()).setPriority(2); - - for (Task.CreateBatchOperation task : tasks) { - jobCreator.addTaskCreator(task); - } - - return service.create(jobCreator); - } - - // Process - public Task.CreateBatchOperation createTaskOptions(String taskName, int inputAssetId, int outputAssetId, - EncoderType encoderType) throws ServiceException { - String taskBody = getTaskBody(inputAssetId, outputAssetId); - - String processor = null; - String configuration = null; - switch (encoderType) { - case WindowsAzureMediaEncoder: - processor = getMediaProcessorIdByName(MEDIA_PROCESSOR_WINDOWS_AZURE_MEDIA_ENCODER); - // Full list of configurations strings for version 2.1 is at: - // http://msdn.microsoft.com/en-us/library/jj129582.aspx - configuration = "VC1 Broadband SD 4x3"; - break; - case StorageDecryption: - processor = getMediaProcessorIdByName(MEDIA_PROCESSOR_STORAGE_DECRYPTION); - configuration = null; - break; - default: - break; - } - - Task.CreateBatchOperation taskCreate = Task.create(processor, taskBody).setName(taskName) - .setConfiguration(configuration); - - return taskCreate; - } - - private String getTaskBody(int inputAssetId, int outputAssetId) { - return "JobInputAsset(" + inputAssetId + ")" - + "JobOutputAsset(" + outputAssetId + ")"; - } - - private String getMediaProcessorIdByName(String processorName) throws ServiceException { - EntityListOperation operation = MediaProcessor.list(); - operation.getQueryParameters().putSingle("$filter", "(Name eq '" + processorName + "')"); - MediaProcessorInfo processor = service.list(operation).get(0); - return processor.getId(); - } - - // Process - public boolean isJobFinished(JobInfo initialJobInfo) throws ServiceException { - JobInfo currentJob = service.get(Job.get(initialJobInfo.getId())); - System.out.println(currentJob.getState()); - switch (currentJob.getState()) { - case Finished: - case Canceled: - case Error: - return true; - default: - return false; - } - } - - public List getJobOutputMediaAssets(JobInfo job) throws ServiceException { - return service.list(Asset.list(job.getOutputAssetsLink())); - } - - // Process - public void cancelJob(JobInfo job) throws ServiceException { - // Use the service function - service.action(Job.cancel(job.getId())); - } - - // Deliver - private Hashtable createFileURLsFromAsset(AssetInfo asset, int availabilityWindowInMinutes) - throws ServiceException, MalformedURLException { - Hashtable ret = new Hashtable(); - - AccessPolicyInfo readAP = service.create(AccessPolicy.create(accessPolicyPrefix + "tempAccessPolicy", - availabilityWindowInMinutes, EnumSet.of(AccessPolicyPermission.READ))); - LocatorInfo readLocator = service.create(Locator.create(readAP.getId(), asset.getId(), LocatorType.SAS)); - - List publishedFiles = service.list(AssetFile.list(asset.getAssetFilesLink())); - for (AssetFileInfo fi : publishedFiles) { - ret.put(fi.getName(), - new URL(readLocator.getBaseUri() + "/" + fi.getName() + readLocator.getContentAccessToken())); - } - - return ret; - } - - // Deliver - public Hashtable downloadFilesFromAsset(AssetInfo asset, int downloadWindowInMinutes) - throws Exception { - Hashtable urls = createFileURLsFromAsset(asset, downloadWindowInMinutes); - Hashtable ret = new Hashtable(); - - for (String fileName : urls.keySet()) { - URL url = urls.get(fileName); - InputStream stream = getInputStreamWithRetry(url); - ret.put(fileName, stream); - } - - return ret; - } - - // This method is needed because there can be a delay before a new read locator - // is applied for the asset files. - private InputStream getInputStreamWithRetry(URL file) throws IOException, InterruptedException { - InputStream reader = null; - for (int counter = 0; true; counter++) { - try { - reader = file.openConnection().getInputStream(); - break; - } - catch (IOException e) { - System.out.println("Got error, wait a bit and try again"); - if (counter < 6) { - Thread.sleep(10000); - } - else { - // No more retries. - throw e; - } - } - } - - return reader; - } - - public void removeAllAssetsWithPrefix(String assetPrefix) throws ServiceException { - ListResult locators = service.list(Locator.list()); - EntityListOperation operation = Asset.list(); - operation.getQueryParameters().add("$filter", "startswith(Name,'" + assetPrefix + "')"); - List assets = service.list(operation); - for (AssetInfo asset : assets) { - if (asset.getName().length() > assetPrefix.length() - && asset.getName().substring(0, assetPrefix.length()).equals(assetPrefix)) { - for (LocatorInfo locator : locators) { - if (locator.getAssetId().equals(asset.getId())) { - try { - service.delete(Locator.delete(locator.getId())); - } - catch (ServiceException e) { - // Don't worry if cannot delete now. - // Might be held on to by a running job - } - } - } - - try { - service.delete(Asset.delete(asset.getId())); - } - catch (ServiceException e) { - // Don't worry if cannot delete now. - // Might be held on to by a running job - } - } - } - } - - public void removeAllAccessPoliciesWithPrefix() throws ServiceException { - List accessPolicies = service.list(AccessPolicy.list()); - for (AccessPolicyInfo accessPolicy : accessPolicies) { - if (accessPolicy.getName().length() > accessPolicyPrefix.length() - && accessPolicy.getName().substring(0, accessPolicyPrefix.length()).equals(accessPolicyPrefix)) { - try { - service.delete(AccessPolicy.delete(accessPolicy.getId())); - } - catch (ServiceException e) { - // Don't worry if cannot delete now. - // Might be held on to by a running job - } - } - } - } - - public void removeAllJobWithPrefix(String testJobPrefix) throws ServiceException { - List jobInfos = service.list(Job.list()); - for (JobInfo jobInfo : jobInfos) { - if (jobInfo.getName().startsWith(testJobPrefix)) { - try { - service.delete(Job.delete(jobInfo.getId())); - } - catch (ServiceException e) { - } - } - } - } - - private static class EncryptionHelper { - public static boolean canUseStrongCrypto() { - try { - Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); - SecretKeySpec secretKeySpec = new SecretKeySpec(new byte[32], "AES"); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - } - catch (Exception e) { - return false; - } - return true; - } - - public static byte[] encryptSymmetricKey(String protectionKey, byte[] inputData) throws Exception { - Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"); - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - byte[] protectionKeyBytes = Base64.decode(protectionKey); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(protectionKeyBytes); - Certificate certificate = certificateFactory.generateCertificate(byteArrayInputStream); - Key publicKey = certificate.getPublicKey(); - SecureRandom secureRandom = new SecureRandom(); - cipher.init(Cipher.ENCRYPT_MODE, publicKey, secureRandom); - byte[] cipherText = cipher.doFinal(inputData); - return cipherText; - } - - public static String calculateContentKeyChecksum(String uuid, byte[] aesKey) throws Exception { - Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); - SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, "AES"); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); - byte[] encryptionResult = cipher.doFinal(uuid.getBytes("UTF8")); - byte[] checksumByteArray = new byte[8]; - System.arraycopy(encryptionResult, 0, checksumByteArray, 0, 8); - String checksum = Base64.encode(checksumByteArray); - return checksum; - } - - public static InputStream encryptFile(InputStream inputStream, byte[] key, byte[] iv) throws Exception { - Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); - SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec); - CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher); - return cipherInputStream; - } - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/BrokerPropertiesMapperTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/BrokerPropertiesMapperTest.java deleted file mode 100644 index ce827d0430ec5..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/BrokerPropertiesMapperTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import static org.junit.Assert.*; - -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.serviceBus.implementation.BrokerProperties; -import com.microsoft.windowsazure.services.serviceBus.implementation.BrokerPropertiesMapper; - -public class BrokerPropertiesMapperTest { - - private final String testBrokerPropertiesString = "{" + "\"CorrelationId\": \"corid\"," - + "\"SessionId\": \"sesid\"," + "\"DeliveryCount\": 5," - + "\"LockedUntilUtc\": \" Fri, 14 Oct 2011 12:34:56 GMT\"," + "\"LockToken\": \"loctok\"," - + "\"MessageId\": \"mesid\"," + "\"Label\": \"lab\"," + "\"ReplyTo\": \"repto\"," - + "\"SequenceNumber\": 7," + "\"TimeToLive\": 8.123," + "\"To\": \"to\"," - + "\"ScheduledEnqueueTimeUtc\": \" Sun, 06 Nov 1994 08:49:37 GMT\"," - + "\"ReplyToSessionId\": \"reptosesid\"," + "\"MessageLocation\": \"mesloc\"," - + "\"LockLocation\": \"locloc\"" + "}"; - - private static Date schedTimeUtc, lockedUntilUtc; - - @BeforeClass - public static void setup() { - Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - calendar.set(1994, 10, 6, 8, 49, 37); - schedTimeUtc = calendar.getTime(); - - Calendar calendar2 = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - calendar2.set(2011, 9, 14, 12, 34, 56); - lockedUntilUtc = calendar2.getTime(); - - } - - @Test - public void jsonStringMapsToBrokerPropertiesObject() { - // Arrange - BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); - - // Act - BrokerProperties properties = mapper.fromString("{\"DeliveryCount\":5,\"MessageId\":\"something\"}"); - - // Assert - assertNotNull(properties); - assertEquals(new Integer(5), properties.getDeliveryCount()); - assertEquals("something", properties.getMessageId()); - } - - @Test - public void nonDefaultPropertiesMapToJsonString() { - // Arrange - BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); - - // Act - BrokerProperties properties = new BrokerProperties(); - properties.setMessageId("foo"); - properties.setDeliveryCount(7); - String json = mapper.toString(properties); - - // Assert - assertNotNull(json); - assertEquals("{\"DeliveryCount\":7,\"MessageId\":\"foo\"}", json); - } - - @Test - public void deserializingAllPossibleValues() { - // Arrange - BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); - - // Act - BrokerProperties properties = mapper.fromString(testBrokerPropertiesString); - - // Assert - assertNotNull(properties); - - long lockedUntilDelta = properties.getLockedUntilUtc().getTime() - lockedUntilUtc.getTime(); - long schedTimeDelta = properties.getScheduledEnqueueTimeUtc().getTime() - schedTimeUtc.getTime(); - - assertEquals("corid", properties.getCorrelationId()); - assertEquals("sesid", properties.getSessionId()); - assertEquals(5, (int) properties.getDeliveryCount()); - assertTrue(Math.abs(lockedUntilDelta) < 2000); - assertEquals("loctok", properties.getLockToken()); - assertEquals("mesid", properties.getMessageId()); - assertEquals("lab", properties.getLabel()); - assertEquals("repto", properties.getReplyTo()); - assertEquals(7, (long) properties.getSequenceNumber()); - assertEquals(8.123, properties.getTimeToLive(), .001); - assertEquals("to", properties.getTo()); - assertTrue(Math.abs(schedTimeDelta) < 2000); - assertEquals("reptosesid", properties.getReplyToSessionId()); - assertEquals("mesloc", properties.getMessageLocation()); - assertEquals("locloc", properties.getLockLocation()); - } - - @Test - public void missingDatesDeserializeAsNull() { - // Arrange - BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); - - // Act - BrokerProperties properties = mapper.fromString("{}"); - - // Assert - assertNull(properties.getLockedUntilUtc()); - assertNull(properties.getScheduledEnqueueTimeUtc()); - } - - @Test - public void deserializeDateInKrKrLocaleCorrectly() { - // Arrange - BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); - Locale defaultLocale = Locale.getDefault(); - Locale.setDefault(Locale.KOREA); - - // Act - BrokerProperties brokerProperties = mapper.fromString(testBrokerPropertiesString); - Locale.setDefault(defaultLocale); - - // Assert - long lockedUntilDelta = brokerProperties.getLockedUntilUtc().getTime() - lockedUntilUtc.getTime(); - assertTrue(Math.abs(lockedUntilDelta) < 2000); - } - - @Test - public void deserializeDateInEnUsLocaleCorrectly() { - // Arrange - BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); - Locale defaultLocale = Locale.getDefault(); - Locale.setDefault(Locale.US); - - // Act - BrokerProperties brokerProperties = mapper.fromString(testBrokerPropertiesString); - Locale.setDefault(defaultLocale); - - // Assert - long lockedUntilDelta = brokerProperties.getLockedUntilUtc().getTime() - lockedUntilUtc.getTime(); - assertTrue(Math.abs(lockedUntilDelta) < 2000); - - } - - @Test - public void deserializeDateInZhCnLocaleCorrectly() { - // Arrange - BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); - Locale defaultLocale = Locale.getDefault(); - Locale.setDefault(Locale.CHINA); - - // Act - BrokerProperties brokerProperties = mapper.fromString(testBrokerPropertiesString); - Locale.setDefault(defaultLocale); - - // Assert - long lockedUntilDelta = brokerProperties.getLockedUntilUtc().getTime() - lockedUntilUtc.getTime(); - assertTrue(Math.abs(lockedUntilDelta) < 2000); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/IntegrationTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/IntegrationTestBase.java deleted file mode 100644 index 02e0cbee1984b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/IntegrationTestBase.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import static com.microsoft.windowsazure.services.serviceBus.Util.*; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; - -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.serviceBus.models.QueueInfo; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageOptions; -import com.microsoft.windowsazure.services.serviceBus.models.TopicInfo; - -public abstract class IntegrationTestBase { - - private ServiceBusContract service; - - @BeforeClass - public static void initializeSystem() { - System.setProperty("http.keepAlive", "false"); - } - - @Before - public void initialize() throws Exception { - - boolean testAlphaExists = false; - Configuration config = createConfiguration(); - service = ServiceBusService.create(config); - for (QueueInfo queue : iterateQueues(service)) { - String queueName = queue.getPath(); - if (queueName.startsWith("Test") || queueName.startsWith("test")) { - if (queueName.equalsIgnoreCase("TestAlpha")) { - testAlphaExists = true; - long count = queue.getMessageCount(); - for (long i = 0; i != count; ++i) { - service.receiveQueueMessage(queueName, new ReceiveMessageOptions().setTimeout(20)); - } - } - else { - service.deleteQueue(queueName); - } - } - } - - removeTopics(); - - if (!testAlphaExists) { - service.createQueue(new QueueInfo("TestAlpha")); - } - } - - protected void removeTopics() throws ServiceException { - for (TopicInfo topic : iterateTopics(service)) { - String topicName = topic.getPath(); - if (topicName.startsWith("Test") || topicName.startsWith("test")) { - service.deleteTopic(topicName); - } - } - } - - @AfterClass - public static void cleanUpTestArtifacts() throws Exception { - Configuration config = createConfiguration(); - ServiceBusContract service = ServiceBusService.create(config); - for (QueueInfo queue : iterateQueues(service)) { - String queueName = queue.getPath(); - if (queueName.startsWith("Test") || queueName.startsWith("test")) { - service.deleteQueue(queueName); - } - } - for (TopicInfo topic : iterateTopics(service)) { - String topicName = topic.getPath(); - if (topicName.startsWith("Test") || topicName.startsWith("test")) { - service.deleteTopic(topicName); - } - } - } - - protected static Configuration createConfiguration() throws Exception { - Configuration config = Configuration.load(); - overrideWithEnv(config, ServiceBusConfiguration.CONNECTION_STRING); - return config; - } - - private static void overrideWithEnv(Configuration config, String key) { - String value = System.getenv(key); - if (value == null) - return; - - config.setProperty(key, value); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusConfigurationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusConfigurationTest.java deleted file mode 100644 index 2bffd260cf64a..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusConfigurationTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Configuration; - -public class ServiceBusConfigurationTest { - @Test - public void ConfigureSetsExpectedProperties() { - // Arrange - Configuration config = new Configuration(); - - // Act - ServiceBusConfiguration.configureWithWrapAuthentication(config, "alpha", "beta", "gamma", - ".servicebus.windows.net/", "-sb.accesscontrol.windows.net/WRAPv0.9"); - - // Assert - assertEquals("https://alpha.servicebus.windows.net/", config.getProperty("serviceBus.uri")); - assertEquals("https://alpha-sb.accesscontrol.windows.net/WRAPv0.9", config.getProperty("serviceBus.wrap.uri")); - assertEquals("beta", config.getProperty("serviceBus.wrap.name")); - assertEquals("gamma", config.getProperty("serviceBus.wrap.password")); - } - - @Test - public void UsingProfileAddsPrefix() { - // Arrange - Configuration config = new Configuration(); - - // Act - ServiceBusConfiguration.configureWithWrapAuthentication("backup", config, "alpha", "beta", "gamma", - ".servicebus.windows.net/", "-sb.accesscontrol.windows.net/WRAPv0.9"); - - // Assert - assertEquals("https://alpha.servicebus.windows.net/", config.getProperty("backup.serviceBus.uri")); - assertEquals("https://alpha-sb.accesscontrol.windows.net/WRAPv0.9", - config.getProperty("backup.serviceBus.wrap.uri")); - assertEquals("beta", config.getProperty("backup.serviceBus.wrap.name")); - assertEquals("gamma", config.getProperty("backup.serviceBus.wrap.password")); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusCreationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusCreationTest.java deleted file mode 100644 index d86163d799467..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusCreationTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.serviceBus.implementation.ServiceBusExceptionProcessor; - -public class ServiceBusCreationTest { - @Test - public void theServiceClassMayBeCreatedDirectlyViaSingletonConfig() throws Exception { - ServiceBusConfiguration.configureWithWrapAuthentication("my-namespace", "my-identity", "my-shared-secret", - ".servicebus.windows.net", "-sb.accesscontrol.windows.net/WRAPv0.9"); - ServiceBusContract service = ServiceBusService.create(); - - assertNotNull(service); - assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); - } - - public Configuration newConfiguration() { - Configuration config = new Configuration(); - ServiceBusConfiguration.configureWithWrapAuthentication(config, "my-namespace", "my-identity", - "my-shared-secret", ".servicebus.windows.net", "-sb.accesscontrol.windows.net/WRAPv0.9"); - return config; - } - - private Configuration newConfigurationWithProfile() { - Configuration config = newConfiguration(); - ServiceBusConfiguration.configureWithWrapAuthentication("other", config, - "my-other-namespace", "my-other-identity", - "my-shared-secret", ".servicebus.windows.net", "-sb.accesscontrol.windows.net/WRAPv0.9"); - return config; - } - - private Configuration newConfigurationWithConnectionString() { - Configuration config = newConfiguration(); - ServiceBusConfiguration.configureWithConnectionString(null, config, - "Endpoint=https://my-other-namespace.servicebus.windows.net/;" + - "SharedSecretIssuer=owner;" + - "SharedSecretValue=my-shared-secret"); - return config; - } - @Test - public void theServiceClassMayBeCreatedDirectlyWithConfig() throws Exception { - Configuration config = newConfiguration(); - ServiceBusContract service = ServiceBusService.create(config); - - assertNotNull(service); - assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); - } - - @Test - public void theServiceClassMayAlsoBeCreatedFromConfig() throws Exception { - Configuration config = newConfiguration(); - ServiceBusContract service = config.create(ServiceBusContract.class); - - assertNotNull(service); - assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); - } - - @Test - public void testDefaultBuilderCreatesServiceImpl() throws Exception { - Configuration config = newConfiguration(); - ServiceBusContract service = config.create(ServiceBusContract.class); - - assertNotNull(service); - } - - @Test - public void theServiceClassCanBeCreatedThroughAProfile() throws Exception { - Configuration config = newConfigurationWithProfile(); - ServiceBusContract service = config.create("other", ServiceBusContract.class); - - assertNotNull(service); - assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); - } - - @Test - public void theServiceClassCanBeCreatedThroughConnectionString() throws Exception { - Configuration config = newConfigurationWithConnectionString(); - - ServiceBusContract service = config.create(ServiceBusContract.class); - assertNotNull(service); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusIntegrationTest.java deleted file mode 100644 index 0101756681134..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusIntegrationTest.java +++ /dev/null @@ -1,1074 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Builder; -import com.microsoft.windowsazure.services.core.Builder.Alteration; -import com.microsoft.windowsazure.services.core.Builder.Registry; -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceFilter; -import com.microsoft.windowsazure.services.core.ServiceFilter.Request; -import com.microsoft.windowsazure.services.core.ServiceFilter.Response; -import com.microsoft.windowsazure.services.serviceBus.implementation.CorrelationFilter; -import com.microsoft.windowsazure.services.serviceBus.implementation.EmptyRuleAction; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.FalseFilter; -import com.microsoft.windowsazure.services.serviceBus.implementation.MessageCountDetails; -import com.microsoft.windowsazure.services.serviceBus.implementation.RuleDescription; -import com.microsoft.windowsazure.services.serviceBus.implementation.SqlFilter; -import com.microsoft.windowsazure.services.serviceBus.implementation.SqlRuleAction; -import com.microsoft.windowsazure.services.serviceBus.implementation.TrueFilter; -import com.microsoft.windowsazure.services.serviceBus.models.BrokeredMessage; -import com.microsoft.windowsazure.services.serviceBus.models.GetQueueResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListQueuesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListRulesResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListSubscriptionsResult; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ListTopicsResult; -import com.microsoft.windowsazure.services.serviceBus.models.QueueInfo; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveMessageOptions; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveQueueMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.ReceiveSubscriptionMessageResult; -import com.microsoft.windowsazure.services.serviceBus.models.RuleInfo; -import com.microsoft.windowsazure.services.serviceBus.models.SubscriptionInfo; -import com.microsoft.windowsazure.services.serviceBus.models.TopicInfo; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.filter.LoggingFilter; - -public class ServiceBusIntegrationTest extends IntegrationTestBase { - - private ServiceBusContract service; - - static ReceiveMessageOptions RECEIVE_AND_DELETE_5_SECONDS = new ReceiveMessageOptions().setReceiveAndDelete() - .setTimeout(5); - static ReceiveMessageOptions PEEK_LOCK_5_SECONDS = new ReceiveMessageOptions().setPeekLock().setTimeout(5); - - private String createLongString(int length) { - String result = new String(); - for (int i = 0; i < length; i++) { - result = result + "a"; - } - return result; - } - - @Before - public void createService() throws Exception { - // reinitialize configuration from known state - Configuration config = createConfiguration(); - - // add LoggingFilter to any pipeline that is created - Registry builder = (Registry) config.getBuilder(); - builder.alter(ServiceBusContract.class, Client.class, new Alteration() { - @Override - public Client alter(String profile, Client instance, Builder builder, Map properties) { - instance.addFilter(new LoggingFilter()); - return instance; - } - }); - - // applied as default configuration - Configuration.setInstance(config); - service = ServiceBusService.create(); - } - - @Test - public void fetchQueueAndListQueuesWorks() throws Exception { - // Arrange - - // Act - QueueInfo entry = service.getQueue("TestAlpha").getValue(); - ListQueuesResult feed = service.listQueues(); - - // Assert - assertNotNull(entry); - assertNotNull(feed); - } - - @Test - public void createQueueWorks() throws Exception { - // Arrange - - // Act - QueueInfo queue = new QueueInfo("TestCreateQueueWorks").setMaxSizeInMegabytes(1024L); - QueueInfo saved = service.createQueue(queue).getValue(); - - // Assert - assertNotNull(saved); - assertNotSame(queue, saved); - assertEquals(false, saved.isDeadLetteringOnMessageExpiration()); - assertEquals(false, saved.isAnonymousAccessible()); - assertNotNull(saved.getAutoDeleteOnIdle()); - assertEquals(true, saved.isSupportOrdering()); - assertEquals("TestCreateQueueWorks", saved.getPath()); - } - - @Test - public void updateQueueWorks() throws Exception { - // Arrange - QueueInfo queue = new QueueInfo("TestUpdateQueueWorks").setMaxSizeInMegabytes(1024L); - QueueInfo originalQueue = service.createQueue(queue).getValue(); - Long expectedMaxSizeInMegaBytes = 512L; - - // Act - QueueInfo updatedQueue = service.updateQueue(originalQueue.setMaxSizeInMegabytes(512L)); - - // Assert - assertEquals(expectedMaxSizeInMegaBytes, updatedQueue.getMaxSizeInMegabytes()); - } - - @Test - public void getQueueWorks() throws Exception { - // Arrange - String queuePath = "TestGetQueueWorks"; - service.createQueue(new QueueInfo(queuePath)); - - // Act - GetQueueResult getQueueResult = service.getQueue(queuePath); - - // Assert - assertNotNull(getQueueResult); - - } - - @Test(expected = ServiceException.class) - public void getNonExistQueueFail() throws Exception { - // Arrange - String queuePath = "testGetNonExistQueueFail"; - - // Act - service.getQueue(queuePath); - - // Assert - } - - @Test - public void deleteQueueWorks() throws Exception { - // Arrange - service.createQueue(new QueueInfo("TestDeleteQueueWorks")); - - // Act - service.deleteQueue("TestDeleteQueueWorks"); - - // Assert - } - - @Test - public void sendMessageWorks() throws Exception { - // Arrange - BrokeredMessage message = new BrokeredMessage("sendMessageWorks"); - - // Act - service.sendQueueMessage("TestAlpha", message); - - // Assert - } - - @Test - public void getQueueMessageCountDetails() throws Exception { - // Arrange - String queueName = "testGetQueueMessageCountDetails"; - service.createQueue(new QueueInfo(queueName)); - service.sendQueueMessage(queueName, new BrokeredMessage("Hello World")); - Long expectedActiveMessageCount = 1L; - Long expectedDeadLetterMessageCount = 0L; - Long expectedScheduledMessageCount = 0L; - Long expectedTransferMessageCount = 0L; - Long expectedTransferDeadLetterMessageCount = 0L; - - // Act - QueueInfo queueInfo = service.getQueue(queueName).getValue(); - MessageCountDetails countDetails = queueInfo.getCountDetails(); - - // Assert - assertEquals(true, queueInfo.isSupportOrdering()); - assertNotNull(countDetails); - assertEquals(expectedActiveMessageCount, countDetails.getActiveMessageCount()); - assertEquals(expectedDeadLetterMessageCount, countDetails.getDeadLetterMessageCount()); - assertEquals(expectedScheduledMessageCount, countDetails.getScheduledMessageCount()); - assertEquals(expectedTransferMessageCount, countDetails.getTransferMessageCount()); - assertEquals(expectedTransferDeadLetterMessageCount, countDetails.getTransferDeadLetterMessageCount()); - - } - - @Test - public void getTopicMessageCountDetails() throws Exception { - // Arrange - String topicName = "TestGetTopicMessageCountDetails"; - service.createTopic(new TopicInfo(topicName)).getValue(); - Long expectedActiveMessageCount = 0L; - Long expectedDeadLetterMessageCount = 0L; - Long expectedScheduledMessageCount = 0L; - Long expectedTransferMessageCount = 0L; - Long expectedTransferDeadLetterMessageCount = 0L; - - // Act - TopicInfo topicInfo = service.getTopic(topicName).getValue(); - MessageCountDetails countDetails = topicInfo.getCountDetails(); - - // Assert - assertNotNull(topicInfo); - assertNotNull(countDetails); - assertEquals(expectedActiveMessageCount, countDetails.getActiveMessageCount()); - assertEquals(expectedDeadLetterMessageCount, countDetails.getDeadLetterMessageCount()); - assertEquals(expectedScheduledMessageCount, countDetails.getScheduledMessageCount()); - assertEquals(expectedTransferMessageCount, countDetails.getTransferMessageCount()); - assertEquals(expectedTransferDeadLetterMessageCount, countDetails.getTransferDeadLetterMessageCount()); - - } - - @Test - public void getSubscriptionMessageCountDetails() throws Exception { - // Arrange - String topicName = "TestGetSubscriptionMessageCountDetails"; - String subscriptionName = "TestGetSubscriptionMessageCountDetails"; - service.createTopic(new TopicInfo(topicName)).getValue(); - service.createSubscription(topicName, new SubscriptionInfo(subscriptionName)); - Long expectedActiveMessageCount = 1L; - Long expectedDeadLetterMessageCount = 0L; - Long expectedScheduledMessageCount = 0L; - Long expectedTransferMessageCount = 0L; - Long expectedTransferDeadLetterMessageCount = 0L; - - // Act - service.sendTopicMessage(topicName, new BrokeredMessage("Hello world!")); - SubscriptionInfo subscriptionInfo = service.getSubscription(topicName, subscriptionName).getValue(); - MessageCountDetails countDetails = subscriptionInfo.getCountDetails(); - - // Assert - assertNotNull(subscriptionInfo); - assertNotNull(countDetails); - assertEquals(expectedActiveMessageCount, countDetails.getActiveMessageCount()); - assertEquals(expectedDeadLetterMessageCount, countDetails.getDeadLetterMessageCount()); - assertEquals(expectedScheduledMessageCount, countDetails.getScheduledMessageCount()); - assertEquals(expectedTransferMessageCount, countDetails.getTransferMessageCount()); - assertEquals(expectedTransferDeadLetterMessageCount, countDetails.getTransferDeadLetterMessageCount()); - - } - - @Test - public void receiveMessageWorks() throws Exception { - // Arrange - String queueName = "TestReceiveMessageWorks"; - service.createQueue(new QueueInfo(queueName)); - service.sendQueueMessage(queueName, new BrokeredMessage("Hello World")); - - // Act - BrokeredMessage message = service.receiveQueueMessage(queueName, RECEIVE_AND_DELETE_5_SECONDS).getValue(); - byte[] data = new byte[100]; - int size = message.getBody().read(data); - - // Assert - assertEquals(11, size); - assertArrayEquals("Hello World".getBytes(), Arrays.copyOf(data, size)); - } - - @Test - public void receiveLargeMessageWorks() throws Exception { - // Arrange - String queueName = "TestReceiveLargeMessageWorks"; - service.createQueue(new QueueInfo(queueName)); - String expectedBody = createLongString(64000); - BrokeredMessage expectedMessage = new BrokeredMessage(expectedBody); - service.sendQueueMessage(queueName, expectedMessage); - - // Act - BrokeredMessage message = service.receiveQueueMessage(queueName, RECEIVE_AND_DELETE_5_SECONDS).getValue(); - byte[] data = new byte[64000]; - int size = message.getBody().read(data); - - // Assert - assertEquals(expectedBody.length(), size); - assertArrayEquals(expectedBody.getBytes(), Arrays.copyOf(data, size)); - - } - - @Test - public void renewSubscriptionMessageLockWorks() throws Exception { - // Arrange - String topicName = "TestRenewSubscriptionLockMessageWorks"; - String subscriptionName = "renewSubscriptionMessageLockWorks"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo(subscriptionName)); - service.sendTopicMessage(topicName, new BrokeredMessage("Hello Again")); - - // Act - BrokeredMessage message = service.receiveSubscriptionMessage(topicName, subscriptionName, PEEK_LOCK_5_SECONDS) - .getValue(); - service.renewSubscriptionLock(topicName, subscriptionName, message.getMessageId(), message.getLockToken()); - - // Assert - assertNotNull(message); - } - - @Test - public void renewQueueMessageLockWorks() throws Exception { - // Arrange - String queueName = "TestRenewSubscriptionLockMessageWorks"; - service.createQueue(new QueueInfo(queueName)); - service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); - - // Act - BrokeredMessage message = service.receiveQueueMessage(queueName, PEEK_LOCK_5_SECONDS).getValue(); - service.renewQueueLock(queueName, message.getMessageId(), message.getLockToken()); - - // Assert - assertNotNull(message); - } - - @Test - public void receiveMessageEmptyQueueWorks() throws Exception { - // Arrange - String queueName = "TestReceiveMessageEmptyQueueWorks"; - service.createQueue(new QueueInfo(queueName)); - - // Act - ReceiveQueueMessageResult receiveQueueMessageResult = service.receiveQueueMessage(queueName, - RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveQueueMessageResult); - assertNull(receiveQueueMessageResult.getValue()); - } - - @Test - public void receiveQueueForwardToQueueMessageSuccess() throws Exception { - // Arrange - String sourceQueueName = "TestReceiveQueueForwardToQueueMessageSuccessSource"; - String destinationQueueName = "TestReceiveQueueForwardToQueueMessageSuccessDestination"; - QueueInfo destinationQueueInfo = service.createQueue(new QueueInfo(destinationQueueName)).getValue(); - service.createQueue(new QueueInfo(sourceQueueName).setForwardTo(destinationQueueInfo.getUri().toString())) - .getValue(); - - // Act - service.sendQueueMessage(sourceQueueName, new BrokeredMessage("Hello source queue!")); - ReceiveQueueMessageResult receiveQueueMessageResult = service.receiveQueueMessage(destinationQueueName, - RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveQueueMessageResult); - assertNotNull(receiveQueueMessageResult.getValue()); - } - - @Test - public void receiveUpdatedQueueForwardToQueueMessageSuccess() throws Exception { - // Arrange - String sourceQueueName = "TestReceiveUpdatedQueueForwardToQueueMessageSuccessSource"; - String destinationQueueName = "TestReceiveUpdatedQueueForwardToQueueMessageSuccessDestination"; - QueueInfo destinationQueueInfo = service.createQueue(new QueueInfo(destinationQueueName)).getValue(); - QueueInfo sourceQueueInfo = new QueueInfo(sourceQueueName); - service.createQueue(sourceQueueInfo).getValue(); - service.updateQueue(sourceQueueInfo.setForwardTo(destinationQueueInfo.getUri().toString())); - - // Act - service.sendQueueMessage(sourceQueueName, new BrokeredMessage("Hello source queue!")); - ReceiveQueueMessageResult receiveQueueMessageResult = service.receiveQueueMessage(destinationQueueName, - RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveQueueMessageResult); - assertNotNull(receiveQueueMessageResult.getValue()); - } - - @Test - public void receiveSubscriptionForwardToQueueMessageSuccess() throws Exception { - // Arrange - String sourceTopicName = "TestReceiveSubForwardToQueueMessageSuccessSource"; - String sourceSubscriptionName = "TestReceiveSubForwardToQueueMessageSuccessSource"; - String destinationQueueName = "TestReceiveSubForwardToQueueMessageSuccessDestination"; - service.createTopic(new TopicInfo(sourceTopicName)).getValue(); - QueueInfo destinationQueueInfo = service.createQueue(new QueueInfo(destinationQueueName)).getValue(); - service.createSubscription(sourceTopicName, - new SubscriptionInfo(sourceSubscriptionName).setForwardTo(destinationQueueInfo.getUri().toString())); - - // Act - service.sendTopicMessage(sourceTopicName, new BrokeredMessage("Hello source queue!")); - ReceiveQueueMessageResult receiveQueueMessageResult = service.receiveQueueMessage(destinationQueueName, - RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveQueueMessageResult); - assertNotNull(receiveQueueMessageResult.getValue()); - } - - @Test - public void receiveUpdatedSubscriptionForwardToQueueMessageSuccess() throws Exception { - // Arrange - String sourceTopicName = "TestUpdatedReceiveSubForwardToQMessageSuccessSrc"; - String sourceSubscriptionName = "TestUpdatedReceiveSubForwardToQMessageSuccessSrc"; - String destinationQueueName = "TestUpdatedReceiveSubForwardToQMessageSuccessDest"; - service.createTopic(new TopicInfo(sourceTopicName)).getValue(); - QueueInfo destinationQueueInfo = service.createQueue(new QueueInfo(destinationQueueName)).getValue(); - SubscriptionInfo sourceSubscriptionInfo = service.createSubscription(sourceTopicName, - new SubscriptionInfo(sourceSubscriptionName)).getValue(); - service.updateSubscription(sourceTopicName, - sourceSubscriptionInfo.setForwardTo(destinationQueueInfo.getUri().toString())); - // Act - service.sendTopicMessage(sourceTopicName, new BrokeredMessage("Hello source queue!")); - ReceiveQueueMessageResult receiveQueueMessageResult = service.receiveQueueMessage(destinationQueueName, - RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveQueueMessageResult); - assertNotNull(receiveQueueMessageResult.getValue()); - } - - @Test - public void receiveQueueForwardToTopicMessageSuccess() throws Exception { - // Arrange - String sourceQueueName = "TestReceiveQueueForwardToTopicMessageSuccessSource"; - String destinationTopicName = "TestReceiveQueueForwardToTopicMessageSuccessDestination"; - String destinationSubscriptionName = "TestReceiveQueueForwardToTopicMessageSuccessDestination"; - TopicInfo destinationTopicInfo = service.createTopic(new TopicInfo(destinationTopicName)).getValue(); - service.createQueue(new QueueInfo(sourceQueueName).setForwardTo(destinationTopicInfo.getUri().toString())) - .getValue(); - - // Act - service.sendQueueMessage(sourceQueueName, new BrokeredMessage("Hello source queue!")); - ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service.receiveSubscriptionMessage( - destinationTopicName, destinationSubscriptionName, RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveSubscriptionMessageResult); - assertNotNull(receiveSubscriptionMessageResult.getValue()); - } - - @Test - public void receiveUpdatedQueueForwardToTopicMessageSuccess() throws Exception { - // Arrange - String sourceQueueName = "TestReceiveUpdatedQueueForwardToTopicMessageSuccessSource"; - String destinationTopicName = "TestReceiveUpdatedQueueForwardToTopicMessageSuccessDestination"; - String destinationSubscriptionName = "TestReceiveUpdatedQueueForwardToTopicMessageSuccessDestination"; - TopicInfo destinationTopicInfo = service.createTopic(new TopicInfo(destinationTopicName)).getValue(); - QueueInfo sourceQueueInfo = new QueueInfo(sourceQueueName); - service.createQueue(sourceQueueInfo).getValue(); - service.updateQueue(sourceQueueInfo.setForwardTo(destinationTopicInfo.getUri().toString())); - - // Act - service.sendQueueMessage(sourceQueueName, new BrokeredMessage("Hello source queue!")); - ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service.receiveSubscriptionMessage( - destinationTopicName, destinationSubscriptionName, RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveSubscriptionMessageResult); - assertNotNull(receiveSubscriptionMessageResult.getValue()); - } - - @Test - public void receiveSubscriptionForwardToTopicMessageSuccess() throws Exception { - // Arrange - String sourceTopicName = "TestReceiveSubForwardToTopMessageSuccessSrc"; - String sourceSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessSrc"; - String destinationTopicName = "TestReceiveSubForwardToTopMessageSuccessDest"; - String destinationSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessDest"; - service.createTopic(new TopicInfo(sourceTopicName)).getValue(); - TopicInfo destinationTopicInfo = service.createTopic(new TopicInfo(destinationTopicName)).getValue(); - service.createSubscription(destinationTopicName, new SubscriptionInfo(destinationSubscriptionName)).getValue(); - service.createSubscription(sourceTopicName, - new SubscriptionInfo(sourceSubscriptionName).setForwardTo(destinationTopicInfo.getUri().toString())); - - // Act - service.sendTopicMessage(sourceTopicName, new BrokeredMessage("Hello source queue!")); - ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service.receiveSubscriptionMessage( - destinationTopicName, destinationSubscriptionName, RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveSubscriptionMessageResult); - assertNotNull(receiveSubscriptionMessageResult.getValue()); - } - - @Test - public void receiveUpdatedSubscriptionForwardToTopicMessageSuccess() throws Exception { - // Arrange - String sourceTopicName = "TestReceiveSubForwardToTopMessageSuccessSrc"; - String sourceSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessSrc"; - String destinationTopicName = "TestReceiveSubForwardToTopMessageSuccessDest"; - String destinationSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessDest"; - service.createTopic(new TopicInfo(sourceTopicName)).getValue(); - TopicInfo destinationTopicInfo = service.createTopic(new TopicInfo(destinationTopicName)).getValue(); - service.createSubscription(destinationTopicName, new SubscriptionInfo(destinationSubscriptionName)).getValue(); - SubscriptionInfo sourceSubscriptionInfo = service.createSubscription(sourceTopicName, - new SubscriptionInfo(sourceSubscriptionName)).getValue(); - service.updateSubscription(sourceTopicName, - sourceSubscriptionInfo.setForwardTo(destinationTopicInfo.getUri().toString())); - Thread.sleep(1000); - - // Act - service.sendTopicMessage(sourceTopicName, new BrokeredMessage("Hello source queue!")); - ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service.receiveSubscriptionMessage( - destinationTopicName, destinationSubscriptionName, RECEIVE_AND_DELETE_5_SECONDS); - - // Assert - assertNotNull(receiveSubscriptionMessageResult); - assertNotNull(receiveSubscriptionMessageResult.getValue()); - } - - @Test - public void peekLockMessageWorks() throws Exception { - // Arrange - String queueName = "TestPeekLockMessageWorks"; - service.createQueue(new QueueInfo(queueName)); - service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); - - // Act - BrokeredMessage message = service.receiveQueueMessage(queueName, PEEK_LOCK_5_SECONDS).getValue(); - - // Assert - byte[] data = new byte[100]; - int size = message.getBody().read(data); - assertEquals(11, size); - assertEquals("Hello Again", new String(data, 0, size)); - } - - @Test - public void peekLockMessageEmptyQueueWorks() throws Exception { - // Arrange - String queueName = "TestPeekLockMessageEmptyQueueWorks"; - service.createQueue(new QueueInfo(queueName)); - - // Act - ReceiveQueueMessageResult result = service.receiveQueueMessage(queueName, PEEK_LOCK_5_SECONDS); - - // Assert - assertNotNull(result); - assertNull(result.getValue()); - } - - @Test - public void peekLockedMessageCanBeCompleted() throws Exception { - // Arrange - String queueName = "TestPeekLockedMessageCanBeCompleted"; - service.createQueue(new QueueInfo(queueName)); - service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); - BrokeredMessage message = service.receiveQueueMessage(queueName, PEEK_LOCK_5_SECONDS).getValue(); - - // Act - String lockToken = message.getLockToken(); - Date lockedUntil = message.getLockedUntilUtc(); - String lockLocation = message.getLockLocation(); - - service.deleteMessage(message); - - // Assert - assertNotNull(lockToken); - assertNotNull(lockedUntil); - assertNotNull(lockLocation); - } - - @Test - public void peekLockedMessageCanBeUnlocked() throws Exception { - // Arrange - String queueName = "TestPeekLockedMessageCanBeUnlocked"; - service.createQueue(new QueueInfo(queueName)); - service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); - BrokeredMessage peekedMessage = service.receiveQueueMessage(queueName, PEEK_LOCK_5_SECONDS).getValue(); - - // Act - String lockToken = peekedMessage.getLockToken(); - Date lockedUntil = peekedMessage.getLockedUntilUtc(); - - service.unlockMessage(peekedMessage); - BrokeredMessage receivedMessage = service.receiveQueueMessage(queueName, RECEIVE_AND_DELETE_5_SECONDS) - .getValue(); - - // Assert - assertNotNull(lockToken); - assertNotNull(lockedUntil); - assertNull(receivedMessage.getLockToken()); - assertNull(receivedMessage.getLockedUntilUtc()); - } - - @Test - public void peekLockedMessageCanBeDeleted() throws Exception { - // Arrange - String queueName = "TestPeekLockedMessageCanBeDeleted"; - service.createQueue(new QueueInfo(queueName)); - service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); - BrokeredMessage peekedMessage = service.receiveQueueMessage(queueName, PEEK_LOCK_5_SECONDS).getValue(); - - // Act - String lockToken = peekedMessage.getLockToken(); - Date lockedUntil = peekedMessage.getLockedUntilUtc(); - - service.deleteMessage(peekedMessage); - BrokeredMessage receivedMessage = service.receiveQueueMessage(queueName, RECEIVE_AND_DELETE_5_SECONDS) - .getValue(); - - // Assert - assertNotNull(lockToken); - assertNotNull(lockedUntil); - assertNull(receivedMessage); - } - - @Test - public void emptyQueueReturnsNullMessage() throws Exception { - // Arrange - String queueName = "testEmptyQueueReturnsNullMessage"; - service.createQueue(new QueueInfo(queueName)); - - // Act - BrokeredMessage brokeredMessage = service.receiveQueueMessage(queueName, PEEK_LOCK_5_SECONDS).getValue(); - - // Assert - assertNull(brokeredMessage); - } - - @Test - public void contentTypePassesThrough() throws Exception { - // Arrange - String queueName = "TestContentTypePassesThrough"; - service.createQueue(new QueueInfo(queueName)); - - // Act - service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again").setContentType("text/xml")); - - BrokeredMessage message = service.receiveQueueMessage(queueName, RECEIVE_AND_DELETE_5_SECONDS).getValue(); - - // Assert - assertNotNull(message); - assertEquals("text/xml", message.getContentType()); - } - - @Test - public void topicCanBeCreatedListedFetchedAndDeleted() throws ServiceException { - // Arrange - String topicName = "TestTopicCanBeCreatedListedFetchedAndDeleted"; - - // Act - TopicInfo created = service.createTopic(new TopicInfo().setPath(topicName)).getValue(); - ListTopicsResult listed = service.listTopics(); - TopicInfo fetched = service.getTopic(topicName).getValue(); - service.deleteTopic(topicName); - ListTopicsResult listed2 = service.listTopics(); - - // Assert - assertNotNull(created); - assertNotNull(listed); - assertNotNull(fetched); - assertNotNull(listed2); - - assertEquals(listed.getItems().size() - 1, listed2.getItems().size()); - } - - @Test - public void listTopicsUnderASpecificPath() throws ServiceException { - // Arrange - String topicName = "testPathA/testPathB/listTopicUnderASpecificPath"; - - // Act - TopicInfo topicInfo = service.createTopic(new TopicInfo().setPath(topicName)).getValue(); - ListTopicsResult listTopicResult = service.listTopics(new ListTopicsOptions() - .setFilter("startswith(path, 'testPathA/testPathB') eq true")); - - // Assert - assertNotNull(topicInfo); - assertEquals(1, listTopicResult.getItems().size()); - } - - @Test - public void listTopicsUpdatedInLastFiveMinutes() throws ServiceException { - String topicName = "testListTopicUpdatedInLastFiveMinutes"; - - // Act - TopicInfo topicInfo = service.createTopic(new TopicInfo().setPath(topicName)).getValue(); - ListTopicsResult listTopicResult = service.listTopics(new ListTopicsOptions() - .setFilter("ModifiedAt gt '1/25/2012 3:41:41 PM'")); - - // Assert - assertNotNull(topicInfo); - assertEquals(1, listTopicResult.getItems().size()); - } - - @Test - public void listTopicsAccessedSinceASpecificTime() throws ServiceException { - removeTopics(); - String topicName = "testListTopicAccessedInLastFiveMinutes"; - - // Act - TopicInfo topicInfo = service.createTopic(new TopicInfo().setPath(topicName)).getValue(); - ListTopicsResult listTopicResult = service.listTopics(new ListTopicsOptions() - .setFilter("AccessedAt gt '1/25/2012 3:41:41 PM'")); - - // Assert - assertNotNull(topicInfo); - assertEquals(0, listTopicResult.getItems().size()); - } - - @Test - public void listTopicsCreatedSinceASpecificTime() throws ServiceException { - removeTopics(); - String topicName = "testListTopicCreatedInLastFiveMinutes"; - - // Act - TopicInfo topicInfo = service.createTopic(new TopicInfo().setPath(topicName)).getValue(); - ListTopicsResult listTopicResult = service.listTopics(new ListTopicsOptions() - .setFilter("CreatedAt gt '1/25/2012 3:41:41 PM'")); - - // Assert - assertNotNull(topicInfo); - assertEquals(1, listTopicResult.getItems().size()); - } - - @Test - public void topicCreatedContainsMetadata() throws ServiceException { - // Arrange - String topicName = "TestTopicCreatedContainsMetadata"; - - // Act - TopicInfo createdTopicInfo = service.createTopic(new TopicInfo().setPath(topicName)).getValue(); - - // Assert - assertNotNull(createdTopicInfo); - assertNotNull(createdTopicInfo.getAutoDeleteOnIdle()); - assertEquals(false, createdTopicInfo.isRequiresDuplicateDetection()); - assertEquals(false, createdTopicInfo.isFilteringMessageBeforePublishing()); - assertEquals(EntityStatus.ACTIVE, createdTopicInfo.getStatus()); - assertEquals(true, createdTopicInfo.isSupportOrdering()); - assertEquals(false, createdTopicInfo.isAnonymousAccessible()); - - } - - @Test - public void topicCanBeUpdated() throws ServiceException { - // Arrange - String topicName = "testTopicCanBeUpdated"; - Long expectedMaxSizeInMegabytes = 2048L; - - // Act - TopicInfo createdTopicInfo = service.createTopic( - new TopicInfo().setPath(topicName).setMaxSizeInMegabytes(1024L)).getValue(); - TopicInfo updatedTopicInfo = service.updateTopic(createdTopicInfo - .setMaxSizeInMegabytes(expectedMaxSizeInMegabytes)); - - // Assert - assertEquals(expectedMaxSizeInMegabytes, updatedTopicInfo.getMaxSizeInMegabytes()); - } - - @Test - public void filterCanSeeAndChangeRequestOrResponse() throws ServiceException { - // Arrange - final List requests = new ArrayList(); - final List responses = new ArrayList(); - - ServiceBusContract filtered = service.withFilter(new ServiceFilter() { - @Override - public Response handle(Request request, Next next) throws Exception { - requests.add(request); - Response response = next.handle(request); - responses.add(response); - return response; - } - }); - - // Act - QueueInfo created = filtered.createQueue(new QueueInfo("TestFilterCanSeeAndChangeRequestOrResponse")) - .getValue(); - - // Assert - assertNotNull(created); - assertEquals(1, requests.size()); - assertEquals(1, responses.size()); - } - - @Test - public void subscriptionsCanBeCreatedOnTopics() throws Exception { - // Arrange - String topicName = "TestSubscriptionsCanBeCreatedOnTopics"; - service.createTopic(new TopicInfo(topicName)); - - // Act - SubscriptionInfo created = service.createSubscription(topicName, new SubscriptionInfo("MySubscription")) - .getValue(); - - // Assert - assertNotNull(created); - assertEquals("MySubscription", created.getName()); - assertEquals(false, created.isRequiresSession()); - assertEquals(true, created.isDeadLetteringOnFilterEvaluationExceptions()); - assertNotNull(created.getCreatedAt()); - assertNotNull(created.getUpdatedAt()); - assertNotNull(created.getAccessedAt()); - assertNotNull(created.getAutoDeleteOnIdle()); - } - - @Test - public void createSubscriptionWithCorrelationFilter() throws Exception { - // Arrange - String topicName = "testCreateSubscriptionWithCorrelationFilter"; - String expectedCorrelationId = "sampleCorrelationId"; - String expectedContentType = "sampleContentType"; - String expectedLabel = "sampleLabel"; - String expectedMessageId = "sampleMessageId"; - String expectedSessionId = "sampleSessionId"; - String expectedReplyTo = "sampleReplyTo"; - String expectedTo = "sampleTo"; - service.createTopic(new TopicInfo(topicName)); - CorrelationFilter correlationFilter = new CorrelationFilter(); - correlationFilter.setCorrelationId(expectedCorrelationId); - correlationFilter.setContentType(expectedContentType); - correlationFilter.setLabel(expectedLabel); - correlationFilter.setMessageId(expectedMessageId); - correlationFilter.setReplyTo(expectedReplyTo); - correlationFilter.setSessionId(expectedSessionId); - correlationFilter.setTo(expectedTo); - RuleDescription ruleDescription = new RuleDescription(); - ruleDescription.setFilter(correlationFilter); - - // Act - SubscriptionInfo created = service.createSubscription(topicName, - new SubscriptionInfo("MySubscription").setDefaultRuleDescription(ruleDescription)).getValue(); - - RuleInfo ruleInfo = service.getRule(topicName, "MySubscription", "$Default").getValue(); - CorrelationFilter correlationFilterResult = (CorrelationFilter) ruleInfo.getFilter(); - - // Assert - assertNotNull(created); - assertEquals("MySubscription", created.getName()); - assertEquals(false, created.isRequiresSession()); - assertEquals(true, created.isDeadLetteringOnFilterEvaluationExceptions()); - assertNotNull(created.getCreatedAt()); - assertNotNull(created.getUpdatedAt()); - assertNotNull(created.getAccessedAt()); - assertNotNull(created.getAutoDeleteOnIdle()); - assertNotNull(correlationFilterResult); - assertEquals(expectedCorrelationId, correlationFilterResult.getCorrelationId()); - assertEquals(expectedContentType, correlationFilterResult.getContentType()); - assertEquals(expectedLabel, correlationFilterResult.getLabel()); - assertEquals(expectedMessageId, correlationFilterResult.getMessageId()); - assertEquals(expectedSessionId, correlationFilterResult.getSessionId()); - assertEquals(expectedReplyTo, correlationFilterResult.getReplyTo()); - assertEquals(expectedTo, correlationFilterResult.getTo()); - } - - @Test - public void subscriptionsCanBeListed() throws Exception { - // Arrange - String topicName = "TestSubscriptionsCanBeListed"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("MySubscription2")); - - // Act - ListSubscriptionsResult result = service.listSubscriptions(topicName); - - // Assert - assertNotNull(result); - assertEquals(1, result.getItems().size()); - assertEquals("MySubscription2", result.getItems().get(0).getName()); - } - - @Test - public void subscriptionsDetailsMayBeFetched() throws Exception { - // Arrange - String topicName = "TestSubscriptionsDetailsMayBeFetched"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("MySubscription3")); - - // Act - SubscriptionInfo result = service.getSubscription(topicName, "MySubscription3").getValue(); - - // Assert - assertNotNull(result); - assertEquals("MySubscription3", result.getName()); - } - - @Test - public void subscriptionsMayBeDeleted() throws Exception { - // Arrange - String topicName = "TestSubscriptionsMayBeDeleted"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("MySubscription4")); - service.createSubscription(topicName, new SubscriptionInfo("MySubscription5")); - - // Act - service.deleteSubscription(topicName, "MySubscription4"); - - // Assert - ListSubscriptionsResult result = service.listSubscriptions(topicName); - assertNotNull(result); - assertEquals(1, result.getItems().size()); - assertEquals("MySubscription5", result.getItems().get(0).getName()); - } - - @Test - public void subscriptionWillReceiveMessage() throws Exception { - // Arrange - String topicName = "TestSubscriptionWillReceiveMessage"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("sub")); - service.sendTopicMessage(topicName, - new BrokeredMessage("

Testing subscription

").setContentType("text/html")); - - // Act - BrokeredMessage message = service.receiveSubscriptionMessage(topicName, "sub", RECEIVE_AND_DELETE_5_SECONDS) - .getValue(); - - // Assert - assertNotNull(message); - - byte[] data = new byte[100]; - int size = message.getBody().read(data); - assertEquals("

Testing subscription

", new String(data, 0, size)); - assertEquals("text/html", message.getContentType()); - } - - @Test - public void subscriptionCanBeUpdated() throws Exception { - // Arrange - String topicName = "testSubscriptionCanBeUpdated"; - service.createTopic(new TopicInfo(topicName)); - SubscriptionInfo originalSubscription = service.createSubscription(topicName, new SubscriptionInfo("sub")) - .getValue(); - Integer expectedMaxDeliveryCount = 1024; - - // Act - SubscriptionInfo updatedSubscription = service.updateSubscription(topicName, - originalSubscription.setMaxDeliveryCount(expectedMaxDeliveryCount)); - - // Assert - assertEquals(expectedMaxDeliveryCount, updatedSubscription.getMaxDeliveryCount()); - } - - @Test - public void rulesCanBeCreatedOnSubscriptions() throws Exception { - // Arrange - String topicName = "TestrulesCanBeCreatedOnSubscriptions"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("sub")); - - // Act - RuleInfo created = service.createRule(topicName, "sub", new RuleInfo("MyRule1")).getValue(); - - // Assert - assertNotNull(created); - assertEquals("MyRule1", created.getName()); - } - - @Test - public void rulesCanBeListedAndDefaultRuleIsPrecreated() throws Exception { - // Arrange - String topicName = "TestrulesCanBeListedAndDefaultRuleIsPrecreated"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("sub")); - service.createRule(topicName, "sub", new RuleInfo("MyRule2")); - - // Act - ListRulesResult result = service.listRules(topicName, "sub"); - - // Assert - assertNotNull(result); - assertEquals(2, result.getItems().size()); - RuleInfo rule0 = result.getItems().get(0); - RuleInfo rule1 = result.getItems().get(1); - if (rule0.getName() == "MyRule2") { - RuleInfo swap = rule1; - rule1 = rule0; - rule0 = swap; - } - - assertEquals("$Default", rule0.getName()); - assertEquals("MyRule2", rule1.getName()); - assertNotNull(result.getItems().get(0).getModel()); - } - - @Test - public void ruleDetailsMayBeFetched() throws Exception { - // Arrange - String topicName = "TestruleDetailsMayBeFetched"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("sub")); - - // Act - RuleInfo result = service.getRule(topicName, "sub", "$Default").getValue(); - - // Assert - assertNotNull(result); - assertEquals("$Default", result.getName()); - } - - @Test - public void rulesMayBeDeleted() throws Exception { - // Arrange - String topicName = "TestRulesMayBeDeleted"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("sub")); - service.createRule(topicName, "sub", new RuleInfo("MyRule4")); - service.createRule(topicName, "sub", new RuleInfo("MyRule5")); - - // Act - service.deleteRule(topicName, "sub", "MyRule5"); - service.deleteRule(topicName, "sub", "$Default"); - - // Assert - ListRulesResult result = service.listRules(topicName, "sub"); - assertNotNull(result); - assertEquals(1, result.getItems().size()); - assertEquals("MyRule4", result.getItems().get(0).getName()); - } - - @Test - public void rulesMayHaveActionAndFilter() throws ServiceException { - // Arrange - String topicName = "TestRulesMayHaveAnActionAndFilter"; - service.createTopic(new TopicInfo(topicName)); - service.createSubscription(topicName, new SubscriptionInfo("sub")); - - // Act - RuleInfo ruleOne = service.createRule(topicName, "sub", new RuleInfo("One").withCorrelationIdFilter("my-id")) - .getValue(); - RuleInfo ruleTwo = service.createRule(topicName, "sub", new RuleInfo("Two").withTrueFilter()).getValue(); - RuleInfo ruleThree = service.createRule(topicName, "sub", new RuleInfo("Three").withFalseFilter()).getValue(); - RuleInfo ruleFour = service.createRule(topicName, "sub", new RuleInfo("Four").withEmptyRuleAction()).getValue(); - RuleInfo ruleFive = service.createRule(topicName, "sub", new RuleInfo("Five").withSqlRuleAction("SET x = 5")) - .getValue(); - RuleInfo ruleSix = service.createRule(topicName, "sub", new RuleInfo("Six").withSqlExpressionFilter("x != 5")) - .getValue(); - - // Assert - assertEquals(CorrelationFilter.class, ruleOne.getFilter().getClass()); - assertEquals(TrueFilter.class, ruleTwo.getFilter().getClass()); - assertEquals(FalseFilter.class, ruleThree.getFilter().getClass()); - assertEquals(EmptyRuleAction.class, ruleFour.getAction().getClass()); - assertEquals(SqlRuleAction.class, ruleFive.getAction().getClass()); - assertEquals(SqlFilter.class, ruleSix.getFilter().getClass()); - - } - - @Test - public void messagesMayHaveCustomProperties() throws ServiceException { - // Arrange - String queueName = "TestMessagesMayHaveCustomProperties"; - service.createQueue(new QueueInfo(queueName)); - - // Act - service.sendQueueMessage(queueName, new BrokeredMessage("").setProperty("hello", "world") - .setProperty("foo", 42)); - BrokeredMessage message = service.receiveQueueMessage(queueName, RECEIVE_AND_DELETE_5_SECONDS).getValue(); - - // Assert - assertEquals("world", message.getProperty("hello")); - assertEquals(42, message.getProperty("foo")); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/CustomPropertiesMapperTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/CustomPropertiesMapperTest.java deleted file mode 100644 index 323912b282773..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/CustomPropertiesMapperTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import static org.junit.Assert.*; - -import java.text.ParseException; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; - -public class CustomPropertiesMapperTest { - private CustomPropertiesMapper mapper; - - @Before - public void init() { - mapper = new CustomPropertiesMapper(); - } - - @Test - public void stringValuesShouldComeThroughInQuotes() { - // Arrange - - // Act - String text = mapper.toString("This is a string"); - - // Assert - assertEquals("\"This is a string\"", text); - } - - @Test - public void nonStringValuesShouldNotHaveQuotes() { - // Arrange - - // Act - String text = mapper.toString(78); - - // Assert - assertEquals("78", text); - } - - @Test - public void supportedJavaTypesHaveExpectedRepresentations() { - // Arrange - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.set(1971, Calendar.OCTOBER, 14, 12, 34, 56); - - // Act - - // Assert - // assertEquals("78;byte", mapper.toString((byte) 78)); - assertEquals("78", mapper.toString((byte) 78)); - assertEquals("\"a\"", mapper.toString('a')); - assertEquals("-78", mapper.toString((short) -78)); - // assertEquals("78;ushort", mapper.toString((unsigned short)78); - assertEquals("-78", mapper.toString(-78)); - // assertEquals("78;uint", mapper.toString(78)); - assertEquals("-78", mapper.toString((long) -78)); - // assertEquals("78;ulong", mapper.toString(78)); - assertEquals("78.5", mapper.toString((float) 78.5)); - assertEquals("78.5", mapper.toString(78.5)); - //assertEquals("78;decimal", mapper.toString(78)); - assertEquals("true", mapper.toString(true)); - assertEquals("false", mapper.toString(false)); - assertEquals("\"12345678-9abc-def0-9abc-def012345678\"", - mapper.toString(new UUID(0x123456789abcdef0L, 0x9abcdef012345678L))); - assertEquals("\"Thu, 14 Oct 1971 12:34:56 GMT\"", mapper.toString(cal)); - assertEquals("\"Thu, 14 Oct 1971 12:34:56 GMT\"", mapper.toString(cal.getTime())); - //assertEquals("78;date-seconds", mapper.toString(78)); - } - - @Test - public void valuesComeBackAsStringsWhenInQuotes() throws ParseException { - // Arrange - - // Act - Object value = mapper.fromString("\"Hello world\""); - - // Assert - assertEquals("Hello world", value); - assertEquals(String.class, value.getClass()); - } - - @Test - public void nonStringTypesWillBeParsedAsNumeric() throws ParseException { - // Arrange - - // Act - Object value = mapper.fromString("5"); - - // Assert - assertEquals(5, value); - assertEquals(Integer.class, value.getClass()); - } - - @Test - public void supportedFormatsHaveExpectedJavaTypes() throws ParseException { - // Arrange - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.set(1971, Calendar.OCTOBER, 14, 12, 34, 56); - - // Act - Date dt = (Date) mapper.fromString("\"Thu, 14 Oct 1971 12:34:56 GMT\""); - - // Assert - // assertEquals("78;byte", mapper.toString((byte) 78)); - // assertEquals((byte) 78, mapper.fromString("78")); - // assertEquals('a', mapper.fromString("a;char")); - // assertEquals((short) -78, mapper.fromString("-78;short")); - // assertEquals("78;ushort", mapper.toString((unsigned short)78); - assertEquals(-78, mapper.fromString("-78")); - // assertEquals("78;uint", mapper.toString(78)); - // assertEquals((long) -78, mapper.fromString("-78;long")); - // assertEquals("78;ulong", mapper.toString(78)); - // assertEquals((float) 78.5, mapper.fromString("78.5;float")); - assertEquals(78.5, mapper.fromString("78.5")); - //assertEquals("78;decimal", mapper.toString(78)); - assertEquals(true, mapper.fromString("true")); - assertEquals(false, mapper.fromString("false")); - // assertEquals(new UUID(0x123456789abcdef0L, 0x9abcdef012345678L), - // mapper.fromString("12345678-9abc-def0-9abc-def012345678;uuid")); - - assertEquals(cal.getTime().getTime(), dt.getTime(), 1000); - //assertEquals("78;date-seconds", mapper.toString(78)); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionSettingsTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionSettingsTest.java deleted file mode 100644 index 263213071b87b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionSettingsTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import static junit.framework.Assert.*; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.serviceBus.ServiceBusConfiguration; - -public class ServiceBusConnectionSettingsTest { - - @Test - public void settingsAreParsedFromConnectionString() throws Exception { - String ns = "myNamespace"; - String issuer = "myissuer"; - String secret = "mysecret"; - - String connectionString = getConnectionString(ns, issuer, secret); - - ServiceBusConnectionSettings settings = new ServiceBusConnectionSettings(connectionString, null, null, null, - null); - - assertEquals(String.format("https://%1$s.servicebus.windows.net/", ns), settings.getUri()); - assertEquals(String.format("https://%1$s-sb.accesscontrol.windows.net/WRAPv0.9", ns), settings.getWrapUri()); - assertEquals(issuer, settings.getWrapName()); - assertEquals(secret, settings.getWrapPassword()); - } - - private String getConnectionString(String ns, String issuer, String secret) { - return String.format( - "Endpoint=sb://%1$s.servicebus.windows.net/;SharedSecretIssuer=%2$s;SharedSecretValue=%3$s", ns, - issuer, secret); - } - - private String getConnectionString(String ns, String stsEndpoint, String issuer, String secret) { - return String - .format("Endpoint=sb://%1$s.servicebus.windows.net/;StsEndpoint=https://%1$s%4$s;SharedSecretIssuer=%2$s;SharedSecretValue=%3$s", - ns, issuer, secret, stsEndpoint); - } - - @Test - public void settingsAreUsedFromConnectionStringInConfig() throws Exception { - Configuration config = Configuration.load(); - ServiceBusConfiguration.configureWithConnectionString(null, config, - getConnectionString("myNamespace", "owner", "secret")); - - ServiceBusConnectionSettings settings = config.create(ServiceBusConnectionSettings.class); - - assertEquals("https://myNamespace.servicebus.windows.net/", settings.getUri()); - assertEquals("https://myNamespace-sb.accesscontrol.windows.net/WRAPv0.9", settings.getWrapUri()); - assertEquals("owner", settings.getWrapName()); - assertEquals("secret", settings.getWrapPassword()); - } - - @Test - public void settingsAreUsedFromIndividualSettingsInConfiguration() throws Exception { - Configuration config = Configuration.load(); - - ServiceBusConfiguration.configureWithWrapAuthentication(config, "myNamespace", "owner", "secret", - ".servicebus.windows.net/", "-sb.accesscontrol.windows.net/WRAPv0.9"); - - ServiceBusConnectionSettings settings = config.create(ServiceBusConnectionSettings.class); - - assertEquals("https://myNamespace.servicebus.windows.net/", settings.getUri()); - assertEquals("https://myNamespace-sb.accesscontrol.windows.net/WRAPv0.9", settings.getWrapUri()); - assertEquals("owner", settings.getWrapName()); - assertEquals("secret", settings.getWrapPassword()); - } - - @Test - public void settingsPreferConnectionStringIfBothPresentInConfiguration() throws Exception { - Configuration config = Configuration.load(); - - ServiceBusConfiguration.configureWithWrapAuthentication(config, "myIndividualNamespace", "individualowner", - "individualsecret", ".servicebus.windows.net/", "-sb.accesscontrol.windows.net/WRAPv0.9"); - - ServiceBusConfiguration.configureWithConnectionString(null, config, - getConnectionString("myNamespaceCS", "ownerCS", "secretCS")); - - ServiceBusConnectionSettings settings = config.create(ServiceBusConnectionSettings.class); - - assertEquals("https://myNamespaceCS.servicebus.windows.net/", settings.getUri()); - assertEquals("https://myNamespaceCS-sb.accesscontrol.windows.net/WRAPv0.9", settings.getWrapUri()); - assertEquals("ownerCS", settings.getWrapName()); - assertEquals("secretCS", settings.getWrapPassword()); - } - - @Test - public void canSetStSEndPointInConnectionString() throws Exception { - ServiceBusConnectionSettings settings = new ServiceBusConnectionSettings(getConnectionString("myNs", - "-some.accesscontrol.net", "owner", "secret"), null, null, null, null); - - assertEquals("https://myNs.servicebus.windows.net/", settings.getUri()); - assertEquals("https://myNs-some.accesscontrol.net/WRAPv0.9", settings.getWrapUri()); - assertEquals("owner", settings.getWrapName()); - assertEquals("secret", settings.getWrapPassword()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapRestProxyIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapRestProxyIntegrationTest.java deleted file mode 100644 index 7033d388c392b..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapRestProxyIntegrationTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import static org.junit.Assert.*; - -import java.net.URI; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.UserAgentFilter; -import com.microsoft.windowsazure.services.serviceBus.ServiceBusConfiguration; -import com.sun.jersey.api.client.Client; - -public class WrapRestProxyIntegrationTest { - @Test - public void serviceCanBeCalledToCreateAccessToken() throws Exception { - // Arrange - Configuration config = Configuration.getInstance(); - overrideWithEnv(config, ServiceBusConfiguration.URI); - overrideWithEnv(config, ServiceBusConfiguration.WRAP_URI); - overrideWithEnv(config, ServiceBusConfiguration.WRAP_NAME); - overrideWithEnv(config, ServiceBusConfiguration.WRAP_PASSWORD); - WrapContract contract = new WrapRestProxy(config.create(Client.class), new UserAgentFilter()); - - // Act - String serviceBusUri = (String) config.getProperty(ServiceBusConfiguration.URI); - String uri = (String) config.getProperty(ServiceBusConfiguration.WRAP_URI); - String name = (String) config.getProperty(ServiceBusConfiguration.WRAP_NAME); - String password = (String) config.getProperty(ServiceBusConfiguration.WRAP_PASSWORD); - String scope = new URI("http", new URI(serviceBusUri).getAuthority(), new URI(serviceBusUri).getPath(), null, - null).toString(); - WrapAccessTokenResult result = contract.wrapAccessToken(uri, name, password, scope); - - // Assert - assertNotNull(result); - assertNotNull(result.getAccessToken()); - } - - private static void overrideWithEnv(Configuration config, String key) { - String value = System.getenv(key); - if (value == null) - return; - - config.setProperty(key, value); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManagerTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManagerTest.java deleted file mode 100644 index 5fb85b33358ed..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManagerTest.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.implementation; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.utils.DateFactory; - -public class WrapTokenManagerTest { - private WrapContract contract; - private WrapTokenManager client; - private DateFactory dateFactory; - private Calendar calendar; - - @Before - public void init() throws Exception { - calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - - dateFactory = mock(DateFactory.class); - contract = mock(WrapContract.class); - ServiceBusConnectionSettings settings = new ServiceBusConnectionSettings(null, null, "testurl", "testname", "testpassword"); - client = new WrapTokenManager(contract, dateFactory, settings); - - when(dateFactory.getDate()).thenAnswer(new Answer() { - @Override - public Date answer(InvocationOnMock invocation) throws Throwable { - return calendar.getTime(); - } - }); - } - - private void doIncrementingTokens() throws ServiceException { - doAnswer(new Answer() { - int count = 0; - - @Override - public WrapAccessTokenResult answer(InvocationOnMock invocation) throws Throwable { - ++count; - WrapAccessTokenResult wrapResponse = new WrapAccessTokenResult(); - wrapResponse.setAccessToken("testaccesstoken1-" + count); - wrapResponse.setExpiresIn(83); - return wrapResponse; - } - }).when(contract).wrapAccessToken("testurl", "testname", "testpassword", "http://test/scope"); - - doAnswer(new Answer() { - int count = 0; - - @Override - public WrapAccessTokenResult answer(InvocationOnMock invocation) throws Throwable { - ++count; - WrapAccessTokenResult wrapResponse = new WrapAccessTokenResult(); - wrapResponse.setAccessToken("testaccesstoken2-" + count); - wrapResponse.setExpiresIn(83); - return wrapResponse; - } - }).when(contract).wrapAccessToken("testurl", "testname", "testpassword", "http://test/scope2"); - } - - @Test - public void clientUsesContractToGetToken() throws ServiceException, URISyntaxException { - // Arrange - doIncrementingTokens(); - - // Act - String accessToken = client.getAccessToken(new URI("https://test/scope")); - - // Assert - assertNotNull(accessToken); - assertEquals("testaccesstoken1-1", accessToken); - } - - @Test - public void clientWillNotCallMultipleTimesWhileAccessTokenIsValid() throws ServiceException, URISyntaxException { - // Arrange - doIncrementingTokens(); - - // Act - String accessToken1 = client.getAccessToken(new URI("https://test/scope?arg=1")); - String accessToken2 = client.getAccessToken(new URI("https://test/scope?arg=2")); - calendar.add(Calendar.SECOND, 40); - String accessToken3 = client.getAccessToken(new URI("https://test/scope?arg=3")); - - // Assert - assertEquals("testaccesstoken1-1", accessToken1); - assertEquals("testaccesstoken1-1", accessToken2); - assertEquals("testaccesstoken1-1", accessToken3); - - verify(contract, times(1)).wrapAccessToken("testurl", "testname", "testpassword", "http://test/scope"); - } - - @Test - public void callsToDifferentPathsWillResultInDifferentAccessTokens() throws ServiceException, URISyntaxException { - // Arrange - doIncrementingTokens(); - - // Act - String accessToken1 = client.getAccessToken(new URI("https://test/scope?arg=1")); - String accessToken2 = client.getAccessToken(new URI("https://test/scope2?arg=2")); - calendar.add(Calendar.SECOND, 40); - String accessToken3 = client.getAccessToken(new URI("https://test/scope?arg=3")); - - // Assert - assertEquals("testaccesstoken1-1", accessToken1); - assertEquals("testaccesstoken2-1", accessToken2); - assertEquals("testaccesstoken1-1", accessToken3); - - verify(contract, times(1)).wrapAccessToken("testurl", "testname", "testpassword", "http://test/scope"); - verify(contract, times(1)).wrapAccessToken("testurl", "testname", "testpassword", "http://test/scope2"); - } - - @Test - public void clientWillBeCalledWhenTokenIsHalfwayToExpiring() throws ServiceException, URISyntaxException { - // Arrange - doIncrementingTokens(); - - // Act - String accessToken1 = client.getAccessToken(new URI("https://test/scope")); - String accessToken2 = client.getAccessToken(new URI("https://test/scope")); - calendar.add(Calendar.SECOND, 45); - String accessToken3 = client.getAccessToken(new URI("https://test/scope")); - - // Assert - assertEquals("testaccesstoken1-1", accessToken1); - assertEquals("testaccesstoken1-1", accessToken2); - assertEquals("testaccesstoken1-2", accessToken3); - - verify(contract, times(2)).wrapAccessToken("testurl", "testname", "testpassword", "http://test/scope"); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/QueueInfoTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/QueueInfoTest.java deleted file mode 100644 index dff449d9a6d7f..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/QueueInfoTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.models; - -import static org.junit.Assert.*; - -import java.util.Calendar; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.Duration; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityAvailabilityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.PartitioningPolicy; - -public class QueueInfoTest { - - private Duration createDuration(int milliSeconds) { - DatatypeFactory datatypeFactory; - try { - datatypeFactory = DatatypeFactory.newInstance(); - } - catch (DatatypeConfigurationException e) { - throw new RuntimeException(e); - } - return datatypeFactory.newDuration(milliSeconds); - } - - @Test - public void testGetSetLockDuration() { - // Arrange - Duration expectedLockDuration = createDuration(100); - QueueInfo queueInfo = new QueueInfo(); - - // Act - Duration actualLockDuration = queueInfo.setLockDuration(expectedLockDuration).getLockDuration(); - - // Assert - assertEquals(expectedLockDuration, actualLockDuration); - - } - - @Test - public void testGetSetMaxSizeInMegabytes() { - // Arrange - Long expectedMaxSizeInMegabytes = 1024L; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Long actualMaxSizeInMegabytes = queueInfo.setMaxSizeInMegabytes(expectedMaxSizeInMegabytes) - .getMaxSizeInMegabytes(); - - // Assert - assertEquals(expectedMaxSizeInMegabytes, actualMaxSizeInMegabytes); - - } - - @Test - public void testGetSetRequiresDuplicateDetection() { - // Arrange - Boolean expectedRequiresDuplicateDetection = true; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Boolean actualRequiresDuplicateDetection = queueInfo.setRequiresDuplicateDetection( - expectedRequiresDuplicateDetection).isRequiresDuplicateDetection(); - - // Assert - assertEquals(expectedRequiresDuplicateDetection, actualRequiresDuplicateDetection); - - } - - @Test - public void testGetSetRequiresSession() { - // Arrange - Boolean expectedRequiresSession = true; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Boolean actualRequiresSession = queueInfo.setRequiresSession(expectedRequiresSession).isRequiresSession(); - - // Assert - assertEquals(expectedRequiresSession, actualRequiresSession); - } - - @Test - public void testGetSetDefaultMessageTimeToLive() { - // Arrange - Duration expectedDefaultMessageTimeToLive = createDuration(100); - QueueInfo queueInfo = new QueueInfo(); - - // Act - Duration actualDefaultMessageTimeToLive = queueInfo.setDefaultMessageTimeToLive( - expectedDefaultMessageTimeToLive).getDefaultMessageTimeToLive(); - - // Assert - assertEquals(expectedDefaultMessageTimeToLive, actualDefaultMessageTimeToLive); - } - - @Test - public void testGetSetDeadLetteringOnMessageExpiration() { - // Arrange - Boolean expectedDeadLetteringOnMessageExpiration = true; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Boolean actualDeadLetteringOnMessageExpiration = queueInfo.setDeadLetteringOnMessageExpiration( - expectedDeadLetteringOnMessageExpiration).isDeadLetteringOnMessageExpiration(); - - // Assert - assertEquals(expectedDeadLetteringOnMessageExpiration, actualDeadLetteringOnMessageExpiration); - } - - @Test - public void testGetSetDuplicateDetectionHistoryTimeWindow() { - // Arrange - Duration expectedDefaultMessageTimeToLive = createDuration(100); - QueueInfo queueInfo = new QueueInfo(); - - // Act - Duration actualDefaultMessageTimeToLive = queueInfo.setDefaultMessageTimeToLive( - expectedDefaultMessageTimeToLive).getDefaultMessageTimeToLive(); - - // Assert - assertEquals(expectedDefaultMessageTimeToLive, actualDefaultMessageTimeToLive); - } - - @Test - public void testGetSetMaxDeliveryCount() { - // Arrange - Integer expectedMaxDeliveryCount = 1024; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Integer actualMaxDeliveryCount = queueInfo.setMaxDeliveryCount(expectedMaxDeliveryCount).getMaxDeliveryCount(); - - // Assert - assertEquals(expectedMaxDeliveryCount, actualMaxDeliveryCount); - } - - @Test - public void testGetSetEnableBatchedOperations() { - // Arrange - Boolean expectedEnableBatchedOperations = true; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Boolean actualEnableBatchedOperations = queueInfo.setEnableBatchedOperations(expectedEnableBatchedOperations) - .isEnableBatchedOperations(); - - // Assert - assertEquals(expectedEnableBatchedOperations, actualEnableBatchedOperations); - } - - @Test - public void testGetSetSizeInBytes() { - // Arrange - Long expectedSizeInBytes = 1024L; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Long actualSizeInBytes = queueInfo.setSizeInBytes(expectedSizeInBytes).getSizeInBytes(); - - // Assert - assertEquals(expectedSizeInBytes, actualSizeInBytes); - } - - @Test - public void testGetSetMessageCount() { - // Arrange - Long expectedMessageCount = 1024L; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Long actualMessageCount = queueInfo.setMessageCount(expectedMessageCount).getMessageCount(); - - // Assert - assertEquals(expectedMessageCount, actualMessageCount); - } - - @Test - public void testGetSetIsAnonymousAccessible() { - // Arrange - Boolean expectedIsAnonymousAccessible = true; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Boolean actualIsAnonymousAccessible = queueInfo.setIsAnonymousAccessible(expectedIsAnonymousAccessible) - .isAnonymousAccessible(); - - // Assert - assertEquals(expectedIsAnonymousAccessible, actualIsAnonymousAccessible); - } - - @Test - public void testGetSetStatus() { - // Arrange - EntityStatus expectedEntityStatus = EntityStatus.ACTIVE; - QueueInfo queueInfo = new QueueInfo(); - - // Act - EntityStatus actualEntityStatus = queueInfo.setStatus(expectedEntityStatus).getStatus(); - - // Assert - assertEquals(expectedEntityStatus, actualEntityStatus); - } - - @Test - public void testGetSetCreatedAt() { - // Arrange - Calendar expectedCreatedAt = Calendar.getInstance(); - QueueInfo queueInfo = new QueueInfo(); - - // Act - Calendar actualCreatedAt = queueInfo.setCreatedAt(expectedCreatedAt).getCreatedAt(); - - // Assert - assertEquals(expectedCreatedAt, actualCreatedAt); - } - - @Test - public void testGetSetUpdatedAt() { - // Arrange - Calendar expectedUpdatedAt = Calendar.getInstance(); - QueueInfo queueInfo = new QueueInfo(); - - // Act - Calendar actualUpdatedAt = queueInfo.setUpdatedAt(expectedUpdatedAt).getUpdatedAt(); - - // Assert - assertEquals(expectedUpdatedAt, actualUpdatedAt); - } - - @Test - public void testGetSetAccessedAt() { - // Arrange - Calendar expectedAccessedAt = Calendar.getInstance(); - QueueInfo queueInfo = new QueueInfo(); - - // Act - Calendar actualAccessedAt = queueInfo.setAccessedAt(expectedAccessedAt).getAccessedAt(); - - // Assert - assertEquals(expectedAccessedAt, actualAccessedAt); - } - - @Test - public void testGetSetUserMetadata() { - // Arrange - String expectedUserMetadata = "expectedUserMetaData"; - QueueInfo queueInfo = new QueueInfo(); - - // Act - String actualUserMetadata = queueInfo.setUserMetadata(expectedUserMetadata).getUserMetadata(); - - // Assert - assertEquals(expectedUserMetadata, actualUserMetadata); - } - - @Test - public void testGetSetSupportOrdering() { - // Arrange - Boolean expectedIsSupportOrdering = true; - QueueInfo queueInfo = new QueueInfo(); - - // Act - Boolean actualIsSupportOrdering = queueInfo.setSupportOrdering(expectedIsSupportOrdering).isSupportOrdering(); - - // Assert - assertEquals(expectedIsSupportOrdering, actualIsSupportOrdering); - } - - @Test - public void testGetSetAutoDeleteOnIdle() { - // Arrange - Duration expectedIsAutoDeleteOnIdle = createDuration(100); - QueueInfo queueInfo = new QueueInfo(); - - // Act - Duration actualIsAutoDeleteOnIdle = queueInfo.setAutoDeleteOnIdle(expectedIsAutoDeleteOnIdle) - .getAutoDeleteOnIdle(); - - // Assert - assertEquals(expectedIsAutoDeleteOnIdle, actualIsAutoDeleteOnIdle); - } - - @Test - public void testGetSetPartioningPolicy() { - // Arrange - PartitioningPolicy expectedPartitioningPolicy = PartitioningPolicy.NO_PARTITIONING; - QueueInfo queueInfo = new QueueInfo(); - - // Act - PartitioningPolicy actualPartitioningPolicy = queueInfo.setPartitioningPolicy(expectedPartitioningPolicy) - .getPartitioningPolicy(); - - // Assert - assertEquals(expectedPartitioningPolicy, actualPartitioningPolicy); - } - - @Test - public void testGetSetEntityAvailabilityStatus() { - // Arrange - EntityAvailabilityStatus expectedEntityAvailabilityStatus = EntityAvailabilityStatus.AVAILABLE; - QueueInfo queueInfo = new QueueInfo(); - - // Act - EntityAvailabilityStatus actualEntityAvailabilityStatus = queueInfo.setEntityAvailabilityStatus( - expectedEntityAvailabilityStatus).getEntityAvailabilityStatus(); - - // Assert - assertEquals(expectedEntityAvailabilityStatus, actualEntityAvailabilityStatus); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/SubscriptionInfoTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/SubscriptionInfoTest.java deleted file mode 100644 index c981cfa1c271d..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/SubscriptionInfoTest.java +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.models; - -import static org.junit.Assert.*; - -import java.util.Calendar; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.Duration; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityAvailabilityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.RuleDescription; - -public class SubscriptionInfoTest { - - private Duration createDuration(int milliSeconds) { - DatatypeFactory datatypeFactory; - try { - datatypeFactory = DatatypeFactory.newInstance(); - } - catch (DatatypeConfigurationException e) { - throw new RuntimeException(e); - } - return datatypeFactory.newDuration(milliSeconds); - } - - @Test - public void testGetSetLockDuration() { - // Arrange - Duration expectedLockDuration = createDuration(100); - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Duration actualLockDuration = SubscriptionInfo.setLockDuration(expectedLockDuration).getLockDuration(); - - // Assert - assertEquals(expectedLockDuration, actualLockDuration); - - } - - @Test - public void testGetSetRequiresSession() { - // Arrange - Boolean expectedRequiresSession = true; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Boolean actualRequiresSession = SubscriptionInfo.setRequiresSession(expectedRequiresSession) - .isRequiresSession(); - - // Assert - assertEquals(expectedRequiresSession, actualRequiresSession); - } - - @Test - public void testGetSetDefaultMessageTimeToLive() { - // Arrange - Duration expectedDefaultMessageTimeToLive = createDuration(100); - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Duration actualDefaultMessageTimeToLive = SubscriptionInfo.setDefaultMessageTimeToLive( - expectedDefaultMessageTimeToLive).getDefaultMessageTimeToLive(); - - // Assert - assertEquals(expectedDefaultMessageTimeToLive, actualDefaultMessageTimeToLive); - } - - @Test - public void testGetSetDeadLetteringOnMessageExpiration() { - // Arrange - Boolean expectedDeadLetteringOnMessageExpiration = true; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Boolean actualDeadLetteringOnMessageExpiration = SubscriptionInfo.setDeadLetteringOnMessageExpiration( - expectedDeadLetteringOnMessageExpiration).isDeadLetteringOnMessageExpiration(); - - // Assert - assertEquals(expectedDeadLetteringOnMessageExpiration, actualDeadLetteringOnMessageExpiration); - } - - @Test - public void testGetSetDeadLetteringOnFilterEvaluationExceptions() { - // Arrange - Boolean expectedDeadLetteringOnFilterEvaluationExceptions = true; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Boolean actualDeadLetteringOnFilterEvaluationExceptions = SubscriptionInfo - .setDeadLetteringOnFilterEvaluationExceptions(expectedDeadLetteringOnFilterEvaluationExceptions) - .isDeadLetteringOnFilterEvaluationExceptions(); - - // Assert - assertEquals(expectedDeadLetteringOnFilterEvaluationExceptions, actualDeadLetteringOnFilterEvaluationExceptions); - } - - @Test - public void testGetSetDefaultRuleDescription() { - // Arrange - RuleDescription expectedDefaultRuleDescription = new RuleDescription(); - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - RuleDescription actualDefaultRuleDescription = SubscriptionInfo.setDefaultRuleDescription( - expectedDefaultRuleDescription).getDefaultRuleDescription(); - - // Assert - assertEquals(expectedDefaultRuleDescription, actualDefaultRuleDescription); - } - - @Test - public void testGetSetMessageCount() { - // Arrange - Long expectedMessageCount = 1024L; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Long actualMessageCount = SubscriptionInfo.setMessageCount(expectedMessageCount).getMessageCount(); - - // Assert - assertEquals(expectedMessageCount, actualMessageCount); - } - - @Test - public void testGetSetMaxDeliveryCount() { - // Arrange - Integer expectedMaxDeliveryCount = 1024; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Integer actualMaxDeliveryCount = SubscriptionInfo.setMaxDeliveryCount(expectedMaxDeliveryCount) - .getMaxDeliveryCount(); - - // Assert - assertEquals(expectedMaxDeliveryCount, actualMaxDeliveryCount); - } - - @Test - public void testGetSetEnableBatchedOperations() { - // Arrange - Boolean expectedEnableBatchedOperations = true; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Boolean actualEnableBatchedOperations = SubscriptionInfo.setEnableBatchedOperations( - expectedEnableBatchedOperations).isEnableBatchedOperations(); - - // Assert - assertEquals(expectedEnableBatchedOperations, actualEnableBatchedOperations); - } - - @Test - public void testGetSetStatus() { - // Arrange - EntityStatus expectedEntityStatus = EntityStatus.ACTIVE; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - EntityStatus actualEntityStatus = SubscriptionInfo.setStatus(expectedEntityStatus).getStatus(); - - // Assert - assertEquals(expectedEntityStatus, actualEntityStatus); - } - - @Test - public void testGetSetCreatedAt() { - // Arrange - Calendar expectedCreatedAt = Calendar.getInstance(); - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Calendar actualCreatedAt = SubscriptionInfo.setCreatedAt(expectedCreatedAt).getCreatedAt(); - - // Assert - assertEquals(expectedCreatedAt, actualCreatedAt); - } - - @Test - public void testGetSetUpdatedAt() { - // Arrange - Calendar expectedUpdatedAt = Calendar.getInstance(); - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Calendar actualUpdatedAt = SubscriptionInfo.setUpdatedAt(expectedUpdatedAt).getUpdatedAt(); - - // Assert - assertEquals(expectedUpdatedAt, actualUpdatedAt); - } - - @Test - public void testGetSetAccessedAt() { - // Arrange - Calendar expectedAccessedAt = Calendar.getInstance(); - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Calendar actualAccessedAt = SubscriptionInfo.setAccessedAt(expectedAccessedAt).getAccessedAt(); - - // Assert - assertEquals(expectedAccessedAt, actualAccessedAt); - } - - @Test - public void testGetSetUserMetadata() { - // Arrange - String expectedUserMetadata = "expectedUserMetaData"; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - String actualUserMetadata = SubscriptionInfo.setUserMetadata(expectedUserMetadata).getUserMetadata(); - - // Assert - assertEquals(expectedUserMetadata, actualUserMetadata); - } - - @Test - public void testGetSetAutoDeleteOnIdle() { - // Arrange - Duration expectedIsAutoDeleteOnIdle = createDuration(100); - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - Duration actualIsAutoDeleteOnIdle = SubscriptionInfo.setAutoDeleteOnIdle(expectedIsAutoDeleteOnIdle) - .getAutoDeleteOnIdle(); - - // Assert - assertEquals(expectedIsAutoDeleteOnIdle, actualIsAutoDeleteOnIdle); - } - - @Test - public void testGetSetEntityAvailabilityStatus() { - // Arrange - EntityAvailabilityStatus expectedEntityAvailabilityStatus = EntityAvailabilityStatus.AVAILABLE; - SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); - - // Act - EntityAvailabilityStatus actualEntityAvailabilityStatus = SubscriptionInfo.setEntityAvailabilityStatus( - expectedEntityAvailabilityStatus).getEntityAvailabilityStatus(); - - // Assert - assertEquals(expectedEntityAvailabilityStatus, actualEntityAvailabilityStatus); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/TopicInfoTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/TopicInfoTest.java deleted file mode 100644 index 9c7e8e4d8ed07..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/TopicInfoTest.java +++ /dev/null @@ -1,292 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.serviceBus.models; - -import static org.junit.Assert.*; - -import java.util.Calendar; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.Duration; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityAvailabilityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.PartitioningPolicy; - -public class TopicInfoTest { - - private Duration createDuration(int milliSeconds) { - DatatypeFactory datatypeFactory; - try { - datatypeFactory = DatatypeFactory.newInstance(); - } - catch (DatatypeConfigurationException e) { - throw new RuntimeException(e); - } - return datatypeFactory.newDuration(milliSeconds); - } - - @Test - public void testGetSetDefaultMessageTimeToLive() { - // Arrange - Duration expectedDefaultMessageTimeToLive = createDuration(1024); - TopicInfo topicInfo = new TopicInfo(); - - // Act - Duration actualDefaultMessageTimeToLive = topicInfo.setDefaultMessageTimeToLive( - expectedDefaultMessageTimeToLive).getDefaultMessageTimeToLive(); - - // Assert - assertEquals(expectedDefaultMessageTimeToLive, actualDefaultMessageTimeToLive); - - } - - @Test - public void testGetSetMaxSizeInMegabytes() { - // Arrange - Long expectedMaxSizeInMegabytes = 1024L; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Long actualMaxSizeInMegabytes = topicInfo.setMaxSizeInMegabytes(expectedMaxSizeInMegabytes) - .getMaxSizeInMegabytes(); - - // Assert - assertEquals(expectedMaxSizeInMegabytes, actualMaxSizeInMegabytes); - - } - - @Test - public void testGetSetRequiresDuplicateDetection() { - // Arrange - Boolean expectedRequiresDuplicateDetection = true; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Boolean actualRequiresDuplicateDetection = topicInfo.setRequiresDuplicateDetection( - expectedRequiresDuplicateDetection).isRequiresDuplicateDetection(); - - // Assert - assertEquals(expectedRequiresDuplicateDetection, actualRequiresDuplicateDetection); - - } - - @Test - public void testGetSetDuplicateDetectionHistoryTimeWindow() { - // Arrange - Duration expectedDefaultMessageTimeToLive = createDuration(100); - TopicInfo topicInfo = new TopicInfo(); - - // Act - Duration actualDefaultMessageTimeToLive = topicInfo.setDefaultMessageTimeToLive( - expectedDefaultMessageTimeToLive).getDefaultMessageTimeToLive(); - - // Assert - assertEquals(expectedDefaultMessageTimeToLive, actualDefaultMessageTimeToLive); - } - - @Test - public void testGetSetEnableBatchedOperations() { - // Arrange - Boolean expectedEnableBatchedOperations = true; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Boolean actualEnableBatchedOperations = topicInfo.setEnableBatchedOperations(expectedEnableBatchedOperations) - .isEnableBatchedOperations(); - - // Assert - assertEquals(expectedEnableBatchedOperations, actualEnableBatchedOperations); - } - - @Test - public void testGetSetSizeInBytes() { - // Arrange - Long expectedSizeInBytes = 1024L; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Long actualSizeInBytes = topicInfo.setSizeInBytes(expectedSizeInBytes).getSizeInBytes(); - - // Assert - assertEquals(expectedSizeInBytes, actualSizeInBytes); - } - - @Test - public void testGetSetFilteringMessageBeforePublishing() { - // Arrange - Boolean expectedFilteringMessageBeforePublishing = true; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Boolean actualFilteringMessageBeforePublishing = topicInfo.setFilteringMessageBeforePublishing( - expectedFilteringMessageBeforePublishing).isFilteringMessageBeforePublishing(); - - // Assert - assertEquals(expectedFilteringMessageBeforePublishing, actualFilteringMessageBeforePublishing); - } - - @Test - public void testGetSetAnonymousAccessible() { - // Arrange - Boolean expectedAnonymousAccessible = true; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Boolean actualAnonymousAccessible = topicInfo.setAnonymousAccessible(expectedAnonymousAccessible) - .isAnonymousAccessible(); - - // Assert - assertEquals(expectedAnonymousAccessible, actualAnonymousAccessible); - } - - @Test - public void testGetSetStatus() { - // Arrange - EntityStatus expectedEntityStatus = EntityStatus.ACTIVE; - TopicInfo topicInfo = new TopicInfo(); - - // Act - EntityStatus actualEntityStatus = topicInfo.setStatus(expectedEntityStatus).getStatus(); - - // Assert - assertEquals(expectedEntityStatus, actualEntityStatus); - } - - @Test - public void testGetSetCreatedAt() { - // Arrange - Calendar expectedCreatedAt = Calendar.getInstance(); - TopicInfo topicInfo = new TopicInfo(); - - // Act - Calendar actualCreatedAt = topicInfo.setCreatedAt(expectedCreatedAt).getCreatedAt(); - - // Assert - assertEquals(expectedCreatedAt, actualCreatedAt); - } - - @Test - public void testGetSetUpdatedAt() { - // Arrange - Calendar expectedUpdatedAt = Calendar.getInstance(); - TopicInfo topicInfo = new TopicInfo(); - - // Act - Calendar actualUpdatedAt = topicInfo.setUpdatedAt(expectedUpdatedAt).getUpdatedAt(); - - // Assert - assertEquals(expectedUpdatedAt, actualUpdatedAt); - } - - @Test - public void testGetSetAccessedAt() { - // Arrange - Calendar expectedAccessedAt = Calendar.getInstance(); - TopicInfo topicInfo = new TopicInfo(); - - // Act - Calendar actualAccessedAt = topicInfo.setAccessedAt(expectedAccessedAt).getAccessedAt(); - - // Assert - assertEquals(expectedAccessedAt, actualAccessedAt); - } - - @Test - public void testGetSetUserMetadata() { - // Arrange - String expectedUserMetadata = "expectedUserMetaData"; - TopicInfo topicInfo = new TopicInfo(); - - // Act - String actualUserMetadata = topicInfo.setUserMetadata(expectedUserMetadata).getUserMetadata(); - - // Assert - assertEquals(expectedUserMetadata, actualUserMetadata); - } - - @Test - public void testGetSetSupportOrdering() { - // Arrange - Boolean expectedIsSupportOrdering = true; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Boolean actualIsSupportOrdering = topicInfo.setSupportOrdering(expectedIsSupportOrdering).isSupportOrdering(); - - // Assert - assertEquals(expectedIsSupportOrdering, actualIsSupportOrdering); - } - - @Test - public void testGetSetSubscriptionCount() { - // Arrange - Integer expectedSubscriptionCount = 1024; - TopicInfo topicInfo = new TopicInfo(); - - // Act - Integer actualSubscriptionCount = topicInfo.setSubscriptionCount(expectedSubscriptionCount) - .getSubscriptionCount(); - - // Assert - assertEquals(expectedSubscriptionCount, actualSubscriptionCount); - } - - @Test - public void testGetSetAutoDeleteOnIdle() { - // Arrange - Duration expectedIsAutoDeleteOnIdle = createDuration(100); - TopicInfo topicInfo = new TopicInfo(); - - // Act - Duration actualIsAutoDeleteOnIdle = topicInfo.setAutoDeleteOnIdle(expectedIsAutoDeleteOnIdle) - .getAutoDeleteOnIdle(); - - // Assert - assertEquals(expectedIsAutoDeleteOnIdle, actualIsAutoDeleteOnIdle); - } - - @Test - public void testGetSetPartioningPolicy() { - // Arrange - PartitioningPolicy expectedPartitioningPolicy = PartitioningPolicy.NO_PARTITIONING; - TopicInfo topicInfo = new TopicInfo(); - - // Act - PartitioningPolicy actualPartitioningPolicy = topicInfo.setPartitioningPolicy(expectedPartitioningPolicy) - .getPartitioningPolicy(); - - // Assert - assertEquals(expectedPartitioningPolicy, actualPartitioningPolicy); - } - - @Test - public void testGetSetEntityAvailabilityStatus() { - // Arrange - EntityAvailabilityStatus expectedEntityAvailabilityStatus = EntityAvailabilityStatus.AVAILABLE; - TopicInfo topicInfo = new TopicInfo(); - - // Act - EntityAvailabilityStatus actualEntityAvailabilityStatus = topicInfo.setEntityAvailabilityStatus( - expectedEntityAvailabilityStatus).getEntityAvailabilityStatus(); - - // Assert - assertEquals(expectedEntityAvailabilityStatus, actualEntityAvailabilityStatus); - } - -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/IntegrationTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/IntegrationTestBase.java deleted file mode 100644 index 94030b5188cfc..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/IntegrationTestBase.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table; - -import com.microsoft.windowsazure.services.core.Configuration; - -public abstract class IntegrationTestBase { - protected static Configuration createConfiguration() { - Configuration config = Configuration.getInstance(); - overrideWithEnv(config, TableConfiguration.ACCOUNT_NAME); - overrideWithEnv(config, TableConfiguration.ACCOUNT_KEY); - overrideWithEnv(config, TableConfiguration.URI); - return config; - } - - private static void overrideWithEnv(Configuration config, String key) { - String value = System.getenv(key); - if (value == null) - return; - - config.setProperty(key, value); - } - - protected static boolean isRunningWithEmulator(Configuration config) { - String accountName = "devstoreaccount1"; - String accountKey = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; - - return accountName.equals(config.getProperty(TableConfiguration.ACCOUNT_NAME)) - && accountKey.equals(config.getProperty(TableConfiguration.ACCOUNT_KEY)); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/TableServiceIntegrationTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/TableServiceIntegrationTest.java deleted file mode 100644 index c6a5a15564cc8..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/TableServiceIntegrationTest.java +++ /dev/null @@ -1,1279 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table; - -import static org.junit.Assert.*; - -import java.util.Date; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.core.ExponentialRetryPolicy; -import com.microsoft.windowsazure.services.core.RetryPolicyFilter; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceTimeoutException; -import com.microsoft.windowsazure.services.table.models.BatchOperations; -import com.microsoft.windowsazure.services.table.models.BatchResult; -import com.microsoft.windowsazure.services.table.models.BatchResult.DeleteEntity; -import com.microsoft.windowsazure.services.table.models.BatchResult.InsertEntity; -import com.microsoft.windowsazure.services.table.models.BatchResult.UpdateEntity; -import com.microsoft.windowsazure.services.table.models.DeleteEntityOptions; -import com.microsoft.windowsazure.services.table.models.EdmType; -import com.microsoft.windowsazure.services.table.models.Entity; -import com.microsoft.windowsazure.services.table.models.Filter; -import com.microsoft.windowsazure.services.table.models.GetEntityResult; -import com.microsoft.windowsazure.services.table.models.GetTableResult; -import com.microsoft.windowsazure.services.table.models.InsertEntityResult; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesOptions; -import com.microsoft.windowsazure.services.table.models.QueryEntitiesResult; -import com.microsoft.windowsazure.services.table.models.QueryTablesOptions; -import com.microsoft.windowsazure.services.table.models.QueryTablesResult; -import com.microsoft.windowsazure.services.table.models.ServiceProperties; -import com.microsoft.windowsazure.services.table.models.TableEntry; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.config.ClientConfig; - -public class TableServiceIntegrationTest extends IntegrationTestBase { - private static final String testTablesPrefix = "sdktest"; - private static final String createableTablesPrefix = "csdktest"; - private static String TEST_TABLE_1; - private static String TEST_TABLE_2; - private static String TEST_TABLE_3; - private static String TEST_TABLE_4; - private static String TEST_TABLE_5; - private static String TEST_TABLE_6; - private static String TEST_TABLE_7; - private static String TEST_TABLE_8; - private static String CREATABLE_TABLE_1; - private static String CREATABLE_TABLE_2; - //private static String CREATABLE_TABLE_3; - private static String[] creatableTables; - private static String[] testTables; - - @BeforeClass - public static void setup() throws Exception { - //System.setProperty("http.proxyHost", "127.0.0.1"); - //System.setProperty("http.proxyPort", "8888"); - - // Setup container names array (list of container names used by - // integration tests) - testTables = new String[10]; - int uniqueId = (new java.util.Random()).nextInt(100000); - for (int i = 0; i < testTables.length; i++) { - testTables[i] = String.format("%s%d%d", testTablesPrefix, uniqueId, i + 1); - } - - creatableTables = new String[10]; - for (int i = 0; i < creatableTables.length; i++) { - creatableTables[i] = String.format("%s%d%d", createableTablesPrefix, uniqueId, i + 1); - } - - TEST_TABLE_1 = testTables[0]; - TEST_TABLE_2 = testTables[1]; - TEST_TABLE_3 = testTables[2]; - TEST_TABLE_4 = testTables[3]; - TEST_TABLE_5 = testTables[4]; - TEST_TABLE_6 = testTables[5]; - TEST_TABLE_7 = testTables[6]; - TEST_TABLE_8 = testTables[7]; - - CREATABLE_TABLE_1 = creatableTables[0]; - CREATABLE_TABLE_2 = creatableTables[1]; - //CREATABLE_TABLE_3 = creatableTables[2]; - - // Create all test containers and their content - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - createTables(service, testTablesPrefix, testTables); - } - - @AfterClass - public static void cleanup() throws Exception { - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - deleteTables(service, testTablesPrefix, testTables); - deleteTables(service, createableTablesPrefix, creatableTables); - } - - private static void createTables(TableContract service, String prefix, String[] list) throws Exception { - // Retry creating every table as long as we get "409 - Table being deleted" error - service = service.withFilter(new RetryPolicyFilter(new ExponentialRetryPolicy(new int[] { 409 }))); - - Set containers = queryTables(service, prefix); - for (String item : list) { - if (!containers.contains(item)) { - service.createTable(item); - } - } - } - - private static void deleteTables(TableContract service, String prefix, String[] list) throws Exception { - Set containers = queryTables(service, prefix); - for (String item : list) { - if (containers.contains(item)) { - service.deleteTable(item); - } - } - } - - private static Set queryTables(TableContract service, String prefix) throws Exception { - HashSet result = new HashSet(); - QueryTablesResult list = service.queryTables(new QueryTablesOptions().setPrefix(prefix)); - for (TableEntry item : list.getTables()) { - result.add(item.getName()); - } - return result; - } - - @Test - public void getServicePropertiesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - // Don't run this test with emulator, as v1.6 doesn't support this method - if (isRunningWithEmulator(config)) { - return; - } - - // Act - ServiceProperties props = service.getServiceProperties().getValue(); - - // Assert - assertNotNull(props); - assertNotNull(props.getLogging()); - assertNotNull(props.getLogging().getRetentionPolicy()); - assertNotNull(props.getLogging().getVersion()); - assertNotNull(props.getMetrics().getRetentionPolicy()); - assertNotNull(props.getMetrics().getVersion()); - } - - @Test - public void setServicePropertiesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - // Don't run this test with emulator, as v1.6 doesn't support this method - if (isRunningWithEmulator(config)) { - return; - } - - // Act - ServiceProperties props = service.getServiceProperties().getValue(); - - props.getLogging().setRead(true); - service.setServiceProperties(props); - - props = service.getServiceProperties().getValue(); - - // Assert - assertNotNull(props); - assertNotNull(props.getLogging()); - assertNotNull(props.getLogging().getRetentionPolicy()); - assertNotNull(props.getLogging().getVersion()); - assertTrue(props.getLogging().isRead()); - assertNotNull(props.getMetrics().getRetentionPolicy()); - assertNotNull(props.getMetrics().getVersion()); - } - - @Test - public void createTablesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - // Act - Exception error; - try { - service.getTable(CREATABLE_TABLE_1); - error = null; - } - catch (Exception e) { - error = e; - } - service.createTable(CREATABLE_TABLE_1); - GetTableResult result = service.getTable(CREATABLE_TABLE_1); - - // Assert - assertNotNull(error); - assertNotNull(result); - } - - @Test - public void deleteTablesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - // Act - service.createTable(CREATABLE_TABLE_2); - GetTableResult result = service.getTable(CREATABLE_TABLE_2); - - service.deleteTable(CREATABLE_TABLE_2); - Exception error; - try { - service.getTable(CREATABLE_TABLE_2); - error = null; - } - catch (Exception e) { - error = e; - } - - // Assert - assertNotNull(error); - assertNotNull(result); - } - - @Test - public void queryTablesWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - // Act - QueryTablesResult result = service.queryTables(); - - // Assert - assertNotNull(result); - } - - @Test - public void queryTablesWithPrefixWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - // Act - QueryTablesResult result = service.queryTables(new QueryTablesOptions().setPrefix(testTablesPrefix)); - - // Assert - assertNotNull(result); - } - - @Test - public void getTableWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - // Act - GetTableResult result = service.getTable(TEST_TABLE_1); - - // Assert - assertNotNull(result); - } - - @Test - public void insertEntityWorks() throws Exception { - System.out.println("insertEntityWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - byte[] binaryData = new byte[] { 1, 2, 3, 4 }; - UUID uuid = UUID.randomUUID(); - Entity entity = new Entity().setPartitionKey("001").setRowKey("insertEntityWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()).setProperty("test6", EdmType.BINARY, binaryData) - .setProperty("test7", EdmType.GUID, uuid); - - // Act - InsertEntityResult result = service.insertEntity(TEST_TABLE_2, entity); - - // Assert - assertNotNull(result); - assertNotNull(result.getEntity()); - - assertEquals("001", result.getEntity().getPartitionKey()); - assertEquals("insertEntityWorks", result.getEntity().getRowKey()); - assertNotNull(result.getEntity().getTimestamp()); - assertNotNull(result.getEntity().getEtag()); - - assertNotNull(result.getEntity().getProperty("test")); - assertEquals(true, result.getEntity().getProperty("test").getValue()); - - assertNotNull(result.getEntity().getProperty("test2")); - assertEquals("value", result.getEntity().getProperty("test2").getValue()); - - assertNotNull(result.getEntity().getProperty("test3")); - assertEquals(3, result.getEntity().getProperty("test3").getValue()); - - assertNotNull(result.getEntity().getProperty("test4")); - assertEquals(12345678901L, result.getEntity().getProperty("test4").getValue()); - - assertNotNull(result.getEntity().getProperty("test5")); - assertTrue(result.getEntity().getProperty("test5").getValue() instanceof Date); - - assertNotNull(result.getEntity().getProperty("test6")); - assertTrue(result.getEntity().getProperty("test6").getValue() instanceof byte[]); - byte[] returnedBinaryData = (byte[]) result.getEntity().getProperty("test6").getValue(); - assertEquals(binaryData.length, returnedBinaryData.length); - for (int i = 0; i < binaryData.length; i++) { - assertEquals(binaryData[i], returnedBinaryData[i]); - } - - assertNotNull(result.getEntity().getProperty("test7")); - assertTrue(result.getEntity().getProperty("test7").getValue() instanceof UUID); - assertEquals(uuid.toString(), result.getEntity().getProperty("test7").getValue().toString()); - } - - @Test - public void insertEntityEscapeCharactersWorks() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - Entity entity = new Entity().setPartitionKey("001").setRowKey("insertEntityEscapeCharactersWorks") - .setProperty("test", EdmType.STRING, "\u0005").setProperty("test2", EdmType.STRING, "\u0011") - .setProperty("test3", EdmType.STRING, "\u0025").setProperty("test4", EdmType.STRING, "\uaaaa") - .setProperty("test5", EdmType.STRING, "\ub2e2").setProperty("test6", EdmType.STRING, " \ub2e2") - .setProperty("test7", EdmType.STRING, "ok \ub2e2"); - - // Act - InsertEntityResult result = service.insertEntity(TEST_TABLE_2, entity); - - // Assert - assertNotNull(result); - assertNotNull(result.getEntity()); - - assertEquals("001", result.getEntity().getPartitionKey()); - assertEquals("insertEntityEscapeCharactersWorks", result.getEntity().getRowKey()); - assertNotNull(result.getEntity().getTimestamp()); - assertNotNull(result.getEntity().getEtag()); - - assertNotNull(result.getEntity().getProperty("test")); - String actualTest1 = (String) result.getEntity().getProperty("test").getValue(); - assertEquals("", actualTest1); - - assertNotNull(result.getEntity().getProperty("test2")); - String actualTest2 = (String) result.getEntity().getProperty("test2").getValue(); - assertEquals("", actualTest2); - - assertNotNull(result.getEntity().getProperty("test3")); - String actualTest3 = (String) result.getEntity().getProperty("test3").getValue(); - assertEquals("%", actualTest3); - - assertNotNull(result.getEntity().getProperty("test4")); - String actualTest4 = (String) result.getEntity().getProperty("test4").getValue(); - assertEquals("\uaaaa", actualTest4); - - assertNotNull(result.getEntity().getProperty("test5")); - String actualTest5 = (String) result.getEntity().getProperty("test5").getValue(); - assertEquals("\ub2e2", actualTest5); - - assertNotNull(result.getEntity().getProperty("test6")); - String actualTest6 = (String) result.getEntity().getProperty("test6").getValue(); - assertEquals(" \ub2e2", actualTest6); - - assertNotNull(result.getEntity().getProperty("test7")); - String actualTest7 = (String) result.getEntity().getProperty("test7").getValue(); - assertEquals("ok \ub2e2", actualTest7); - - } - - @Test - public void insertEntityEscapeCharactersRoundTripsFromService() throws Exception { - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - - String partition = "001"; - String row = "insertEntityEscapeCharactersRoundTripsFromService"; - Entity insertedEntity = new Entity().setPartitionKey(partition).setRowKey(row) - .setProperty("test", EdmType.STRING, "\u0005") - .setProperty("test2", EdmType.STRING, "\u0011") - .setProperty("test3", EdmType.STRING, "\u0025") - .setProperty("test4", EdmType.STRING, "\uaaaa") - .setProperty("test5", EdmType.STRING, "\ub2e2") - .setProperty("test6", EdmType.STRING, " \ub2e2") - .setProperty("test7", EdmType.STRING, "ok \ub2e2") - .setProperty("test8", EdmType.STRING, "\uD840\uDC00") - ; - - service.insertEntity(TEST_TABLE_2, insertedEntity); - - GetEntityResult result = service.getEntity(TEST_TABLE_2, "001", "insertEntityEscapeCharactersRoundTripsFromService"); - assertNotNull(result); - - Entity entity = result.getEntity(); - - assertNotNull(entity.getProperty("test")); - String actualTest1 = (String) entity.getPropertyValue("test"); - assertEquals("", actualTest1); - - assertNotNull(result.getEntity().getProperty("test2")); - String actualTest2 = (String) result.getEntity().getPropertyValue("test2"); - assertEquals("", actualTest2); - - assertNotNull(result.getEntity().getProperty("test3")); - String actualTest3 = (String) result.getEntity().getPropertyValue("test3"); - assertEquals("%", actualTest3); - - assertNotNull(result.getEntity().getProperty("test4")); - String actualTest4 = (String) result.getEntity().getPropertyValue("test4"); - assertEquals("\uaaaa", actualTest4); - - assertNotNull(result.getEntity().getProperty("test5")); - String actualTest5 = (String) result.getEntity().getPropertyValue("test5"); - assertEquals("\ub2e2", actualTest5); - - assertNotNull(result.getEntity().getProperty("test6")); - String actualTest6 = (String) result.getEntity().getPropertyValue("test6"); - assertEquals(" \ub2e2", actualTest6); - - assertNotNull(result.getEntity().getProperty("test7")); - String actualTest7 = (String) result.getEntity().getPropertyValue("test7"); - assertEquals("ok \ub2e2", actualTest7); - - String actualTest8 = (String)entity.getPropertyValue("test8"); - assertEquals("\uD840\uDC00", actualTest8); - } - - - @Test - public void updateEntityWorks() throws Exception { - System.out.println("updateEntityWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity = new Entity().setPartitionKey("001").setRowKey("updateEntityWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - // Act - InsertEntityResult result = service.insertEntity(TEST_TABLE_2, entity); - result.getEntity().setProperty("test4", EdmType.INT32, 5); - service.updateEntity(TEST_TABLE_2, result.getEntity()); - - // Assert - } - - @Test - public void insertOrReplaceEntityWorks() throws Exception { - System.out.println("insertOrReplaceEntityWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity = new Entity().setPartitionKey("001").setRowKey("insertOrReplaceEntityWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - // Act - service.insertOrReplaceEntity(TEST_TABLE_2, entity); - entity.setProperty("test4", EdmType.INT32, 5); - entity.setProperty("test6", EdmType.INT32, 6); - service.insertOrReplaceEntity(TEST_TABLE_2, entity); - - // Assert - } - - @Test - public void insertOrMergeEntityWorks() throws Exception { - System.out.println("insertOrMergeEntityWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity = new Entity().setPartitionKey("001").setRowKey("insertOrMergeEntityWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - // Act - service.insertOrMergeEntity(TEST_TABLE_2, entity); - entity.setProperty("test4", EdmType.INT32, 5); - entity.setProperty("test6", EdmType.INT32, 6); - service.insertOrMergeEntity(TEST_TABLE_2, entity); - - // Assert - } - - @Test - public void mergeEntityWorks() throws Exception { - System.out.println("mergeEntityWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity = new Entity().setPartitionKey("001").setRowKey("mergeEntityWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - // Act - InsertEntityResult result = service.insertEntity(TEST_TABLE_2, entity); - - result.getEntity().setProperty("test4", EdmType.INT32, 5); - result.getEntity().setProperty("test6", EdmType.INT32, 6); - service.mergeEntity(TEST_TABLE_2, result.getEntity()); - - // Assert - } - - @Test - public void deleteEntityWorks() throws Exception { - System.out.println("deleteEntityWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity = new Entity().setPartitionKey("001").setRowKey("deleteEntityWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - // Act - InsertEntityResult result = service.insertEntity(TEST_TABLE_2, entity); - - service.deleteEntity(TEST_TABLE_2, result.getEntity().getPartitionKey(), result.getEntity().getRowKey()); - - // Assert - } - - @Test - public void deleteEntityTroublesomeKeyWorks() throws Exception { - System.out.println("deleteEntityTroublesomeKeyWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity1 = new Entity().setPartitionKey("001").setRowKey("key with spaces"); - Entity entity2 = new Entity().setPartitionKey("001").setRowKey("key'with'quotes"); - Entity entity3 = new Entity().setPartitionKey("001").setRowKey("keyWithUnicode \uB2E4"); - Entity entity4 = new Entity().setPartitionKey("001").setRowKey("key 'with'' \uB2E4"); - - // Act - InsertEntityResult result1 = service.insertEntity(TEST_TABLE_2, entity1); - InsertEntityResult result2 = service.insertEntity(TEST_TABLE_2, entity2); - InsertEntityResult result3 = service.insertEntity(TEST_TABLE_2, entity3); - InsertEntityResult result4 = service.insertEntity(TEST_TABLE_2, entity4); - - service.deleteEntity(TEST_TABLE_2, result1.getEntity().getPartitionKey(), result1.getEntity().getRowKey()); - service.deleteEntity(TEST_TABLE_2, result2.getEntity().getPartitionKey(), result2.getEntity().getRowKey()); - service.deleteEntity(TEST_TABLE_2, result3.getEntity().getPartitionKey(), result3.getEntity().getRowKey()); - service.deleteEntity(TEST_TABLE_2, result4.getEntity().getPartitionKey(), result4.getEntity().getRowKey()); - - // Assert - try { - service.getEntity(TEST_TABLE_2, result1.getEntity().getPartitionKey(), result1.getEntity().getRowKey()); - assertFalse("Expect an exception when getting an entity that does not exist", true); - } - catch (ServiceException e) { - assertEquals("expect getHttpStatusCode", 404, e.getHttpStatusCode()); - - } - - QueryEntitiesResult assertResult2 = service.queryEntities( - TEST_TABLE_2, - new QueryEntitiesOptions().setFilter(Filter.eq(Filter.propertyName("RowKey"), - Filter.constant("key'with'quotes")))); - - assertEquals(0, assertResult2.getEntities().size()); - - QueryEntitiesResult assertResult3 = service.queryEntities(TEST_TABLE_2); - for (Entity entity : assertResult3.getEntities()) { - assertFalse("Entity3 should be removed from the table", entity3.getRowKey().equals(entity.getRowKey())); - assertFalse("Entity4 should be removed from the table", entity4.getRowKey().equals(entity.getRowKey())); - } - } - - @Test - public void deleteEntityWithETagWorks() throws Exception { - System.out.println("deleteEntityWithETagWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity = new Entity().setPartitionKey("001").setRowKey("deleteEntityWithETagWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - // Act - InsertEntityResult result = service.insertEntity(TEST_TABLE_2, entity); - - service.deleteEntity(TEST_TABLE_2, result.getEntity().getPartitionKey(), result.getEntity().getRowKey(), - new DeleteEntityOptions().setEtag(result.getEntity().getEtag())); - - // Assert - } - - @Test - public void getEntityWorks() throws Exception { - System.out.println("getEntityWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - byte[] binaryData = new byte[] { 1, 2, 3, 4 }; - Entity entity = new Entity().setPartitionKey("001").setRowKey("getEntityWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()).setProperty("test6", EdmType.BINARY, binaryData); - - // Act - InsertEntityResult insertResult = service.insertEntity(TEST_TABLE_2, entity); - GetEntityResult result = service.getEntity(TEST_TABLE_2, insertResult.getEntity().getPartitionKey(), - insertResult.getEntity().getRowKey()); - - // Assert - assertNotNull(result); - assertNotNull(result.getEntity()); - - assertEquals("001", result.getEntity().getPartitionKey()); - assertEquals("getEntityWorks", result.getEntity().getRowKey()); - assertNotNull(result.getEntity().getTimestamp()); - assertNotNull(result.getEntity().getEtag()); - - assertNotNull(result.getEntity().getProperty("test")); - assertEquals(true, result.getEntity().getProperty("test").getValue()); - - assertNotNull(result.getEntity().getProperty("test2")); - assertEquals("value", result.getEntity().getProperty("test2").getValue()); - - assertNotNull(result.getEntity().getProperty("test3")); - assertEquals(3, result.getEntity().getProperty("test3").getValue()); - - assertNotNull(result.getEntity().getProperty("test4")); - assertEquals(12345678901L, result.getEntity().getProperty("test4").getValue()); - - assertNotNull(result.getEntity().getProperty("test5")); - assertTrue(result.getEntity().getProperty("test5").getValue() instanceof Date); - - assertNotNull(result.getEntity().getProperty("test6")); - assertTrue(result.getEntity().getProperty("test6").getValue() instanceof byte[]); - byte[] returnedBinaryData = (byte[]) result.getEntity().getProperty("test6").getValue(); - assertEquals(binaryData.length, returnedBinaryData.length); - for (int i = 0; i < binaryData.length; i++) { - assertEquals(binaryData[i], returnedBinaryData[i]); - } - } - - @Test - public void queryEntitiesWorks() throws Exception { - System.out.println("queryEntitiesWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - Entity entity = new Entity().setPartitionKey("001").setRowKey("queryEntitiesWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - // Act - service.insertEntity(TEST_TABLE_3, entity); - QueryEntitiesResult result = service.queryEntities(TEST_TABLE_3); - - // Assert - assertNotNull(result); - assertNotNull(result.getEntities()); - assertEquals(1, result.getEntities().size()); - - assertNotNull(result.getEntities().get(0)); - - assertEquals("001", result.getEntities().get(0).getPartitionKey()); - assertEquals("queryEntitiesWorks", result.getEntities().get(0).getRowKey()); - assertNotNull(result.getEntities().get(0).getTimestamp()); - assertNotNull(result.getEntities().get(0).getEtag()); - - assertNotNull(result.getEntities().get(0).getProperty("test")); - assertEquals(true, result.getEntities().get(0).getProperty("test").getValue()); - - assertNotNull(result.getEntities().get(0).getProperty("test2")); - assertEquals("value", result.getEntities().get(0).getProperty("test2").getValue()); - - assertNotNull(result.getEntities().get(0).getProperty("test3")); - assertEquals(3, result.getEntities().get(0).getProperty("test3").getValue()); - - assertNotNull(result.getEntities().get(0).getProperty("test4")); - assertEquals(12345678901L, result.getEntities().get(0).getProperty("test4").getValue()); - - assertNotNull(result.getEntities().get(0).getProperty("test5")); - assertTrue(result.getEntities().get(0).getProperty("test5").getValue() instanceof Date); - } - - @Test - public void queryEntitiesWithPaginationWorks() throws Exception { - System.out.println("queryEntitiesWithPaginationWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_4; - int numberOfEntries = 20; - for (int i = 0; i < numberOfEntries; i++) { - Entity entity = new Entity().setPartitionKey("001").setRowKey("queryEntitiesWithPaginationWorks-" + i) - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - service.insertEntity(table, entity); - } - - // Act - int entryCount = 0; - String nextPartitionKey = null; - String nextRowKey = null; - while (true) { - QueryEntitiesResult result = service.queryEntities(table, - new QueryEntitiesOptions().setNextPartitionKey(nextPartitionKey).setNextRowKey(nextRowKey)); - - entryCount += result.getEntities().size(); - - if (nextPartitionKey == null) - break; - - nextPartitionKey = result.getNextPartitionKey(); - nextRowKey = result.getNextRowKey(); - } - - // Assert - assertEquals(numberOfEntries, entryCount); - } - - @Test - public void queryEntitiesWithFilterWorks() throws Exception { - System.out.println("queryEntitiesWithFilterWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_5; - int numberOfEntries = 5; - Entity[] entities = new Entity[numberOfEntries]; - for (int i = 0; i < numberOfEntries; i++) { - entities[i] = new Entity().setPartitionKey("001").setRowKey("queryEntitiesWithFilterWorks-" + i) - .setProperty("test", EdmType.BOOLEAN, (i % 2 == 0)) - .setProperty("test2", EdmType.STRING, "'value'" + i).setProperty("test3", EdmType.INT32, i) - .setProperty("test4", EdmType.INT64, 12345678901L + i) - .setProperty("test5", EdmType.DATETIME, new Date(i * 1000)) - .setProperty("test6", EdmType.GUID, UUID.randomUUID()); - - service.insertEntity(table, entities[i]); - } - - { - // Act - QueryEntitiesResult result = service.queryEntities( - table, - new QueryEntitiesOptions().setFilter(Filter.eq(Filter.propertyName("RowKey"), - Filter.constant("queryEntitiesWithFilterWorks-3")))); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntities().size()); - assertEquals("queryEntitiesWithFilterWorks-3", result.getEntities().get(0).getRowKey()); - } - - { - // Act - QueryEntitiesResult result = service.queryEntities(table, new QueryEntitiesOptions().setFilter(Filter - .queryString("RowKey eq 'queryEntitiesWithFilterWorks-3'"))); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntities().size()); - assertEquals("queryEntitiesWithFilterWorks-3", result.getEntities().get(0).getRowKey()); - } - - { - // Act - QueryEntitiesResult result = service - .queryEntities( - table, - new QueryEntitiesOptions().setFilter(Filter.eq(Filter.propertyName("test"), - Filter.constant(true)))); - - // Assert - assertNotNull(result); - assertEquals(3, result.getEntities().size()); - } - - { - // Act - QueryEntitiesResult result = service.queryEntities( - table, - new QueryEntitiesOptions().setFilter(Filter.eq(Filter.propertyName("test2"), - Filter.constant("'value'3")))); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntities().size()); - assertEquals("queryEntitiesWithFilterWorks-3", result.getEntities().get(0).getRowKey()); - } - - { - // Act - QueryEntitiesResult result = service.queryEntities( - table, - new QueryEntitiesOptions().setFilter(Filter.eq(Filter.propertyName("test4"), - Filter.constant(12345678903L)))); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntities().size()); - assertEquals("queryEntitiesWithFilterWorks-2", result.getEntities().get(0).getRowKey()); - } - - { - // Act - QueryEntitiesResult result = service.queryEntities( - table, - new QueryEntitiesOptions().setFilter(Filter.eq(Filter.propertyName("test5"), - Filter.constant(new Date(3000))))); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntities().size()); - assertEquals("queryEntitiesWithFilterWorks-3", result.getEntities().get(0).getRowKey()); - } - - { - // Act - QueryEntitiesResult result = service.queryEntities( - table, - new QueryEntitiesOptions().setFilter(Filter.eq(Filter.propertyName("test6"), - Filter.constant(entities[3].getPropertyValue("test6"))))); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntities().size()); - assertEquals("queryEntitiesWithFilterWorks-3", result.getEntities().get(0).getRowKey()); - } - } - - @Test - public void batchInsertWorks() throws Exception { - System.out.println("batchInsertWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_6; - String partitionKey = "001"; - - // Act - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchInsertWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - BatchResult result = service.batch(new BatchOperations().addInsertEntity(table, entity)); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntries().size()); - assertEquals(InsertEntity.class, result.getEntries().get(0).getClass()); - } - - @Test - public void batchUpdateWorks() throws Exception { - System.out.println("batchUpdateWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_6; - String partitionKey = "001"; - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchUpdateWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - entity = service.insertEntity(table, entity).getEntity(); - - // Act - entity.setProperty("test", EdmType.BOOLEAN, false); - BatchResult result = service.batch(new BatchOperations().addUpdateEntity(table, entity)); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntries().size()); - assertEquals(UpdateEntity.class, result.getEntries().get(0).getClass()); - } - - @Test - public void batchMergeWorks() throws Exception { - System.out.println("batchMergeWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_6; - String partitionKey = "001"; - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchMergeWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - entity = service.insertEntity(table, entity).getEntity(); - - // Act - BatchResult result = service.batch(new BatchOperations().addMergeEntity(table, entity)); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntries().size()); - assertEquals(UpdateEntity.class, result.getEntries().get(0).getClass()); - } - - @Test - public void batchInsertOrReplaceWorks() throws Exception { - System.out.println("batchInsertOrReplaceWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_6; - String partitionKey = "001"; - - // Act - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchInsertOrReplaceWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - BatchResult result = service.batch(new BatchOperations().addInsertOrReplaceEntity(table, entity)); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntries().size()); - assertEquals(UpdateEntity.class, result.getEntries().get(0).getClass()); - } - - @Test - public void batchInsertOrMergeWorks() throws Exception { - System.out.println("batchInsertOrMergeWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_6; - String partitionKey = "001"; - - // Act - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchInsertOrMergeWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - BatchResult result = service.batch(new BatchOperations().addInsertOrMergeEntity(table, entity)); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntries().size()); - assertEquals(UpdateEntity.class, result.getEntries().get(0).getClass()); - } - - @Test - public void batchDeleteWorks() throws Exception { - System.out.println("batchDeleteWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_6; - String partitionKey = "001"; - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchDeleteWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - entity = service.insertEntity(table, entity).getEntity(); - - // Act - BatchResult result = service.batch(new BatchOperations().addDeleteEntity(table, entity.getPartitionKey(), - entity.getRowKey(), entity.getEtag())); - - // Assert - assertNotNull(result); - assertEquals(1, result.getEntries().size()); - assertEquals(DeleteEntity.class, result.getEntries().get(0).getClass()); - } - - @Test - public void batchLotsOfInsertsWorks() throws Exception { - System.out.println("batchMultipleWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_7; - String partitionKey = "001"; - int insertCount = 100; - - // Act - BatchOperations batchOperations = new BatchOperations(); - for (int i = 0; i < insertCount; i++) { - - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchWorks-" + i) - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - batchOperations.addInsertEntity(table, entity); - } - BatchResult result = service.batch(batchOperations); - - // Assert - assertNotNull(result); - assertEquals(insertCount, result.getEntries().size()); - for (int i = 0; i < insertCount; i++) { - assertEquals(InsertEntity.class, result.getEntries().get(i).getClass()); - - Entity entity = ((InsertEntity) result.getEntries().get(i)).getEntity(); - - assertEquals("001", entity.getPartitionKey()); - assertEquals("batchWorks-" + i, entity.getRowKey()); - assertNotNull(entity.getTimestamp()); - assertNotNull(entity.getEtag()); - - assertNotNull(entity.getProperty("test")); - assertEquals(true, entity.getProperty("test").getValue()); - - assertNotNull(entity.getProperty("test2")); - assertEquals("value", entity.getProperty("test2").getValue()); - - assertNotNull(entity.getProperty("test3")); - assertEquals(3, entity.getProperty("test3").getValue()); - - assertNotNull(entity.getProperty("test4")); - assertEquals(12345678901L, entity.getProperty("test4").getValue()); - - assertNotNull(entity.getProperty("test5")); - assertTrue(entity.getProperty("test5").getValue() instanceof Date); - } - } - - @Test - public void batchAllOperationsTogetherWorks() throws Exception { - System.out.println("batchAllOperationsWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_8; - String partitionKey = "001"; - - // Insert a few entities to allow updating them in batch - Entity entity1 = new Entity().setPartitionKey(partitionKey).setRowKey("batchAllOperationsWorks-" + 1) - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - entity1 = service.insertEntity(table, entity1).getEntity(); - - Entity entity2 = new Entity().setPartitionKey(partitionKey).setRowKey("batchAllOperationsWorks-" + 2) - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - entity2 = service.insertEntity(table, entity2).getEntity(); - - Entity entity3 = new Entity().setPartitionKey(partitionKey).setRowKey("batchAllOperationsWorks-" + 3) - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - entity3 = service.insertEntity(table, entity3).getEntity(); - - Entity entity4 = new Entity().setPartitionKey(partitionKey).setRowKey("batchAllOperationsWorks-" + 4) - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - - entity4 = service.insertEntity(table, entity4).getEntity(); - - // Act - BatchOperations batchOperations = new BatchOperations(); - - Entity entity = new Entity().setPartitionKey(partitionKey).setRowKey("batchAllOperationsWorks") - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - batchOperations.addInsertEntity(table, entity); - - batchOperations.addDeleteEntity(table, entity1.getPartitionKey(), entity1.getRowKey(), entity1.getEtag()); - - batchOperations.addUpdateEntity(table, entity2.setProperty("test", EdmType.INT32, 5)); - batchOperations.addMergeEntity(table, entity3.setProperty("test", EdmType.INT32, 5)); - batchOperations.addInsertOrReplaceEntity(table, entity4.setProperty("test", EdmType.INT32, 5)); - - Entity entity5 = new Entity().setPartitionKey(partitionKey).setRowKey("batchAllOperationsWorks-" + 5) - .setProperty("test", EdmType.BOOLEAN, true).setProperty("test2", EdmType.STRING, "value") - .setProperty("test3", EdmType.INT32, 3).setProperty("test4", EdmType.INT64, 12345678901L) - .setProperty("test5", EdmType.DATETIME, new Date()); - batchOperations.addInsertOrMergeEntity(table, entity5); - - BatchResult result = service.batch(batchOperations); - - // Assert - assertNotNull(result); - assertEquals(batchOperations.getOperations().size(), result.getEntries().size()); - assertEquals(InsertEntity.class, result.getEntries().get(0).getClass()); - assertEquals(DeleteEntity.class, result.getEntries().get(1).getClass()); - assertEquals(UpdateEntity.class, result.getEntries().get(2).getClass()); - assertEquals(UpdateEntity.class, result.getEntries().get(3).getClass()); - assertEquals(UpdateEntity.class, result.getEntries().get(4).getClass()); - assertEquals(UpdateEntity.class, result.getEntries().get(5).getClass()); - } - - @Test - public void batchNegativeWorks() throws Exception { - System.out.println("batchNegativeWorks()"); - - // Arrange - Configuration config = createConfiguration(); - TableContract service = TableService.create(config); - String table = TEST_TABLE_8; - String partitionKey = "001"; - - // Insert an entity the modify it outside of the batch - Entity entity1 = new Entity().setPartitionKey(partitionKey).setRowKey("batchNegativeWorks1") - .setProperty("test", EdmType.INT32, 1); - Entity entity2 = new Entity().setPartitionKey(partitionKey).setRowKey("batchNegativeWorks2") - .setProperty("test", EdmType.INT32, 2); - Entity entity3 = new Entity().setPartitionKey(partitionKey).setRowKey("batchNegativeWorks3") - .setProperty("test", EdmType.INT32, 3); - - entity1 = service.insertEntity(table, entity1).getEntity(); - entity2 = service.insertEntity(table, entity2).getEntity(); - entity2.setProperty("test", EdmType.INT32, -2); - service.updateEntity(table, entity2); - - // Act - BatchOperations batchOperations = new BatchOperations(); - - // The entity1 still has the original etag from the first submit, - // so this update should fail, because another update was already made. - entity1.setProperty("test", EdmType.INT32, 3); - batchOperations.addDeleteEntity(table, entity1.getPartitionKey(), entity1.getRowKey(), entity1.getEtag()); - batchOperations.addUpdateEntity(table, entity2); - batchOperations.addInsertEntity(table, entity3); - - BatchResult result = service.batch(batchOperations); - - // Assert - assertNotNull(result); - assertEquals(batchOperations.getOperations().size(), result.getEntries().size()); - assertNull("First result should be null", result.getEntries().get(0)); - assertNotNull("Second result should not be null", result.getEntries().get(1)); - assertEquals("Second result type", com.microsoft.windowsazure.services.table.models.BatchResult.Error.class, - result.getEntries().get(1).getClass()); - com.microsoft.windowsazure.services.table.models.BatchResult.Error error = (com.microsoft.windowsazure.services.table.models.BatchResult.Error) result - .getEntries().get(1); - assertEquals("Second result status code", 412, error.getError().getHttpStatusCode()); - assertNull("Third result should be null", result.getEntries().get(2)); - } - - @Test - public void settingTimeoutWorks() throws Exception { - Configuration config = createConfiguration(); - - // Set timeout to very short to force failure - config.setProperty(Configuration.PROPERTY_CONNECT_TIMEOUT, new Integer(1)); - config.setProperty(Configuration.PROPERTY_READ_TIMEOUT, new Integer(1)); - - TableContract service = TableService.create(config); - - try { - service.queryTables(); - fail("Exception should have been thrown"); - } - catch (ServiceTimeoutException ex) { - // No need to assert, test is if correct assertion type is thrown. - } - catch (Exception ex) { - fail("unexpected exception was thrown"); - } - finally { - // Clean up timeouts, they interfere with other tests otherwise - config.getProperties().remove(Configuration.PROPERTY_CONNECT_TIMEOUT); - config.getProperties().remove(Configuration.PROPERTY_READ_TIMEOUT); - } - } - - @Test - public void settingTimeoutFromStringWorks() throws Exception { - Configuration config = createConfiguration(); - - // Set timeout to very short to force failure - config.setProperty(Configuration.PROPERTY_CONNECT_TIMEOUT, "1"); - config.setProperty(Configuration.PROPERTY_READ_TIMEOUT, "1"); - - TableContract service = TableService.create(config); - - try { - service.queryTables(); - fail("Exception should have been thrown"); - } - catch (ServiceTimeoutException ex) { - // No need to assert, test is if correct assertion type is thrown. - } - catch (Exception ex) { - fail("unexpected exception was thrown"); - } - finally { - // Clean up timeouts, they interfere with other tests otherwise - config.getProperties().remove(Configuration.PROPERTY_CONNECT_TIMEOUT); - config.getProperties().remove(Configuration.PROPERTY_READ_TIMEOUT); - } - } - - @Test - public void settingTimeoutPrefixedFromConfigWorks() throws Exception { - Configuration config = createConfiguration(); - - TableContract service = TableService.create("testprefix", config); - - // Use reflection to pull the state out of the service. - Client channel = (Client) readField(service, "service", "channel"); - Integer connTimeout = (Integer) channel.getProperties().get(ClientConfig.PROPERTY_CONNECT_TIMEOUT); - Integer readTimeout = (Integer) channel.getProperties().get(ClientConfig.PROPERTY_READ_TIMEOUT); - - assertEquals(3, connTimeout.intValue()); - assertEquals(7, readTimeout.intValue()); - } - - private Object readField(Object target, String... fieldNames) throws NoSuchFieldException, IllegalAccessException { - Object value = target; - for (String fieldName : fieldNames) { - java.lang.reflect.Field field = value.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - value = field.get(value); - } - return value; - } - - @Test - public void prefixedTimeoutsGetLoaded() throws Exception { - Configuration config = createConfiguration(); - - assertEquals("3", config.getProperty("testprefix." + Configuration.PROPERTY_CONNECT_TIMEOUT)); - assertEquals("7", config.getProperty("testprefix." + Configuration.PROPERTY_READ_TIMEOUT)); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableBatchOperationTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableBatchOperationTests.java deleted file mode 100644 index 55c230921a3f8..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableBatchOperationTests.java +++ /dev/null @@ -1,760 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import static org.junit.Assert.*; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.Random; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -public class TableBatchOperationTests extends TableTestBase { - @Test - public void batchDelete() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - - // insert entity - class1 ref = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - batch.delete(ref); - - ArrayList delResults = tClient.execute(testSuiteTableName, batch); - for (TableResult r : delResults) { - Assert.assertEquals(r.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - try { - tClient.execute(testSuiteTableName, batch); - fail(); - } - catch (StorageException ex) { - Assert.assertEquals(ex.getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - } - } - - @Test - public void batchDeleteFail() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - - // Insert entity to delete - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - - class1 updatedEntity = generateRandomEnitity("jxscl_odata"); - updatedEntity.setPartitionKey(baseEntity.getPartitionKey()); - updatedEntity.setRowKey(baseEntity.getRowKey()); - updatedEntity.setEtag(baseEntity.getEtag()); - tClient.execute(testSuiteTableName, TableOperation.replace(updatedEntity)); - - // add delete to fail - batch.delete(baseEntity); - - try { - @SuppressWarnings("unused") - ArrayList results = tClient.execute(testSuiteTableName, batch); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Precondition Failed"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The update condition specified in the request was not satisfied.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "UpdateConditionNotSatisfied"); - } - } - - @Test - public void batchEmptyQuery() throws StorageException { - // insert entity - class1 ref = generateRandomEnitity("jxscl_odata"); - - TableBatchOperation batch = new TableBatchOperation(); - batch.retrieve(ref.getPartitionKey(), ref.getRowKey(), ref.getClass()); - - ArrayList results = tClient.execute(testSuiteTableName, batch); - - Assert.assertEquals(results.size(), 1); - Assert.assertNull(results.get(0).getResult()); - Assert.assertEquals(results.get(0).getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - } - - @Test - public void batchInsertFail() throws StorageException { - // insert entity - class1 ref = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - try { - TableBatchOperation batch = new TableBatchOperation(); - batch.insert(ref); - tClient.execute(testSuiteTableName, batch); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Conflict"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The specified entity already exists")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "EntityAlreadyExists"); - } - } - - @Test - public void batchLockToPartitionKey() throws StorageException { - try { - TableBatchOperation batch = new TableBatchOperation(); - batch.insert(generateRandomEnitity("jxscl_odata")); - batch.insert(generateRandomEnitity("jxscl_odata2")); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "All entities in a given batch must have the same partition key."); - } - } - - @Test - public void batchMergeFail() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - addInsertBatch(batch); - - // Insert entity to merge - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - - class1 updatedEntity = generateRandomEnitity("jxscl_odata"); - updatedEntity.setPartitionKey(baseEntity.getPartitionKey()); - updatedEntity.setRowKey(baseEntity.getRowKey()); - updatedEntity.setEtag(baseEntity.getEtag()); - tClient.execute(testSuiteTableName, TableOperation.replace(updatedEntity)); - - // add merge to fail - addMergeToBatch(baseEntity, batch); - - try { - @SuppressWarnings("unused") - ArrayList results = tClient.execute(testSuiteTableName, batch); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Precondition Failed"); - String errorAfterSemiColon = ex.getExtendedErrorInformation().getErrorMessage(); - errorAfterSemiColon = errorAfterSemiColon.substring(errorAfterSemiColon.indexOf(":") + 1); - Assert.assertTrue(errorAfterSemiColon - .startsWith("The update condition specified in the request was not satisfied.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "UpdateConditionNotSatisfied"); - } - } - - @Test - public void batchMultiQueryShouldThrow() throws StorageException { - class1 ref = generateRandomEnitity("jxscl_odata"); - class1 ref2 = generateRandomEnitity("jxscl_odata"); - - try { - TableBatchOperation batch = new TableBatchOperation(); - batch.retrieve(ref.getPartitionKey(), ref.getRowKey(), ref.getClass()); - batch.retrieve(ref2.getPartitionKey(), ref2.getRowKey(), ref2.getClass()); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), - "A batch transaction with a retrieve operation cannot contain any other operations."); - } - } - - @Test - public void batchAddNullShouldThrow() throws StorageException { - try { - TableBatchOperation batch = new TableBatchOperation(); - batch.add(null); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "element"); - } - } - - @Test - public void batchRetrieveWithNullResolver() throws StorageException { - try { - TableBatchOperation batch = new TableBatchOperation(); - batch.retrieve("foo", "blah", (EntityResolver) null); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "Query requires a valid class type or resolver."); - } - } - - @Test - public void batchOver100Entities() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - try { - for (int m = 0; m < 101; m++) { - batch.insert(generateRandomEnitity("jxscl_odata")); - } - - tClient.execute(testSuiteTableName, batch); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Bad Request"); - String errorAfterSemiColon = ex.getExtendedErrorInformation().getErrorMessage(); - errorAfterSemiColon = errorAfterSemiColon.substring(errorAfterSemiColon.indexOf(":") + 1); - Assert.assertTrue(errorAfterSemiColon.startsWith("One of the request inputs is not valid.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "InvalidInput"); - } - } - - @Test - public void batchQuery() throws StorageException { - // insert entity - class1 ref = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableBatchOperation batch = new TableBatchOperation(); - - batch.retrieve(ref.getPartitionKey(), ref.getRowKey(), ref.getClass()); - - ArrayList results = tClient.execute(testSuiteTableName, batch); - Assert.assertEquals(results.size(), 1); - - Assert.assertEquals(results.get(0).getHttpStatusCode(), HttpURLConnection.HTTP_OK); - class1 retrievedRef = results.get(0).getResultAsType(); - - Assert.assertEquals(ref.getA(), retrievedRef.getA()); - Assert.assertEquals(ref.getB(), retrievedRef.getB()); - Assert.assertEquals(ref.getC(), retrievedRef.getC()); - Assert.assertTrue(Arrays.equals(ref.getD(), retrievedRef.getD())); - - tClient.execute(testSuiteTableName, TableOperation.delete(ref)); - } - - @Test - public void batchQueryAndOneMoreOperationShouldThrow() throws StorageException { - class1 ref2 = generateRandomEnitity("jxscl_odata"); - - try { - TableBatchOperation batch = new TableBatchOperation(); - batch.insert(generateRandomEnitity("jxscl_odata")); - batch.retrieve(ref2.getPartitionKey(), ref2.getRowKey(), ref2.getClass()); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), - "A batch transaction with a retrieve operation cannot contain any other operations."); - } - - try { - TableBatchOperation batch = new TableBatchOperation(); - batch.retrieve(ref2.getPartitionKey(), ref2.getRowKey(), ref2.getClass()); - batch.insert(generateRandomEnitity("jxscl_odata")); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), - "A batch transaction with a retrieve operation cannot contain any other operations."); - } - } - - @Test - public void batchReplaceFail() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - - // Insert entity to merge - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - - class1 updatedEntity = generateRandomEnitity("jxscl_odata"); - updatedEntity.setPartitionKey(baseEntity.getPartitionKey()); - updatedEntity.setRowKey(baseEntity.getRowKey()); - updatedEntity.setEtag(baseEntity.getEtag()); - tClient.execute(testSuiteTableName, TableOperation.replace(updatedEntity)); - - // add merge to fail - addReplaceToBatch(baseEntity, batch); - - try { - @SuppressWarnings("unused") - ArrayList results = tClient.execute(testSuiteTableName, batch); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Precondition Failed"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The update condition specified in the request was not satisfied.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "UpdateConditionNotSatisfied"); - } - } - - @Test - public void batchInsertEntityOver1MB() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - class1 bigEnt = new class1(); - - bigEnt.setA("foo_A"); - bigEnt.setB("foo_B"); - bigEnt.setC("foo_C"); - // 1mb right here - bigEnt.setD(new byte[1024 * 1024]); - bigEnt.setPartitionKey("jxscl_odata"); - bigEnt.setRowKey(UUID.randomUUID().toString()); - - batch.insert(bigEnt); - - for (int m = 0; m < 3; m++) { - class1 ref = new class1(); - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - batch.insert(ref); - } - - try { - tClient.execute(testSuiteTableName, batch); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Bad Request"); - String errorAfterSemiColon = ex.getExtendedErrorInformation().getErrorMessage(); - errorAfterSemiColon = errorAfterSemiColon.substring(errorAfterSemiColon.indexOf(":") + 1); - Assert.assertTrue(errorAfterSemiColon.startsWith("The entity is larger than allowed by the Table Service.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "EntityTooLarge"); - } - } - - @Test - public void batchInsertEntityWithPropertyMoreThan255chars() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - DynamicTableEntity bigEnt = new DynamicTableEntity(); - - String propName = ""; - for (int m = 0; m < 255; m++) { - propName.concat(Integer.toString(m % 9)); - } - - bigEnt.getProperties().put(propName, new EntityProperty("test")); - bigEnt.setPartitionKey("jxscl_odata"); - bigEnt.setRowKey(UUID.randomUUID().toString()); - - batch.insert(bigEnt); - - for (int m = 0; m < 3; m++) { - class1 ref = new class1(); - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - batch.insert(ref); - } - - try { - tClient.execute(testSuiteTableName, batch); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Bad Request"); - String errorAfterSemiColon = ex.getExtendedErrorInformation().getErrorMessage(); - errorAfterSemiColon = errorAfterSemiColon.substring(errorAfterSemiColon.indexOf(":") + 1); - Assert.assertTrue(errorAfterSemiColon.startsWith("One of the request inputs is not valid.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "InvalidInput"); - } - } - - @Test - public void batchSizeOver4mb() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - byte[] datArr = new byte[1024 * 128]; - Random rand = new Random(); - rand.nextBytes(datArr); - - // Each entity is approx 128kb, meaning ~32 entities will result in a request over 4mb. - try { - for (int m = 0; m < 32; m++) { - class1 ref = new class1(); - - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(datArr); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - batch.insert(ref); - } - - tClient.execute(testSuiteTableName, batch); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Bad Request"); - String errorAfterSemiColon = ex.getExtendedErrorInformation().getErrorMessage(); - Assert.assertTrue(errorAfterSemiColon - .startsWith("The content length for the requested operation has exceeded the limit.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "ContentLengthExceeded"); - } - } - - @Test - public void batchWithAllOperations() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - // insert - addInsertBatch(batch); - - { - // insert entity to delete - class1 delRef = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(delRef)); - batch.delete(delRef); - } - - { - // Insert entity to replace - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addReplaceToBatch(baseEntity, batch); - } - - { - // Insert entity to insert or replace - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addInsertOrReplaceToBatch(baseEntity, batch); - } - - { - // Insert entity to merge - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addMergeToBatch(baseEntity, batch); - } - - { - // Insert entity to merge, no pre-esisting entity - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addInsertOrMergeToBatch(baseEntity, batch); - } - - ArrayList results = tClient.execute(testSuiteTableName, batch); - Assert.assertEquals(results.size(), 6); - - Iterator iter = results.iterator(); - - // insert - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - - // delete - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // replace - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // insert or replace - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // merge - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // insert or merge - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - } - - @Test - public void batchInsert() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - - // Add 3 inserts - for (int m = 0; m < 3; m++) { - addInsertBatch(batch); - } - - // insert entity - class1 ref = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - batch.delete(ref); - - ArrayList results = tClient.execute(testSuiteTableName, batch); - Assert.assertEquals(results.size(), 4); - - Iterator iter = results.iterator(); - - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - - // delete - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - @Test - public void batchMerge() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - addInsertBatch(batch); - - // insert entity to delete - class1 delRef = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(delRef)); - batch.delete(delRef); - - // Insert entity to merge - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addMergeToBatch(baseEntity, batch); - - ArrayList results = tClient.execute(testSuiteTableName, batch); - Assert.assertEquals(results.size(), 3); - - Iterator iter = results.iterator(); - - // insert - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - - // delete - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // merge - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - @Test - public void batchReplace() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - addInsertBatch(batch); - - // insert entity to delete - class1 delRef = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(delRef)); - batch.delete(delRef); - - // Insert entity to replace - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addReplaceToBatch(baseEntity, batch); - - ArrayList results = tClient.execute(testSuiteTableName, batch); - Assert.assertEquals(results.size(), 3); - - Iterator iter = results.iterator(); - - // insert - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - - // delete - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // replace - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - @Test - public void batchInsertOrMerge() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - addInsertBatch(batch); - - // insert entity to delete - class1 delRef = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(delRef)); - batch.delete(delRef); - - // Insert entity to merge - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addInsertOrMergeToBatch(baseEntity, batch); - - ArrayList results = tClient.execute(testSuiteTableName, batch); - Assert.assertEquals(results.size(), 3); - - Iterator iter = results.iterator(); - - // insert - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - - // delete - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // merge - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - @Test - public void batchInsertOrReplace() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - addInsertBatch(batch); - - // insert entity to delete - class1 delRef = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(delRef)); - batch.delete(delRef); - - // Insert entity to replace - class1 baseEntity = generateRandomEnitity("jxscl_odata"); - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - addInsertOrReplaceToBatch(baseEntity, batch); - - ArrayList results = tClient.execute(testSuiteTableName, batch); - Assert.assertEquals(results.size(), 3); - - Iterator iter = results.iterator(); - - // insert - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - - // delete - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // replace - Assert.assertEquals(iter.next().getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - - @Test - public void emptyBatch() throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - - try { - tClient.execute(testSuiteTableName, batch); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "Cannot Execute an empty batch operation"); - } - } - - @Test - public void insertBatch1() throws StorageException { - insertAndDeleteBatchWithX(1); - } - - @Test - public void insertBatch10() throws StorageException { - insertAndDeleteBatchWithX(10); - } - - @Test - public void insertBatch100() throws StorageException { - insertAndDeleteBatchWithX(100); - } - - @Test - public void upsertBatch1() throws StorageException { - upsertAndDeleteBatchWithX(1); - } - - @Test - public void upsertBatch10() throws StorageException { - upsertAndDeleteBatchWithX(10); - } - - @Test - public void upsertBatch100() throws StorageException { - upsertAndDeleteBatchWithX(100); - } - - private class1 addInsertBatch(TableBatchOperation batch) { - class1 ref = generateRandomEnitity("jxscl_odata"); - batch.insert(ref); - return ref; - } - - private class2 addInsertOrMergeToBatch(class1 baseEntity, TableBatchOperation batch) { - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - batch.insertOrMerge(secondEntity); - return secondEntity; - } - - private class2 addInsertOrReplaceToBatch(class1 baseEntity, TableBatchOperation batch) { - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - batch.insertOrReplace(secondEntity); - return secondEntity; - } - - private class2 addMergeToBatch(class1 baseEntity, TableBatchOperation batch) { - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - batch.merge(secondEntity); - return secondEntity; - } - - private class2 addReplaceToBatch(class1 baseEntity, TableBatchOperation batch) { - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - batch.replace(secondEntity); - return secondEntity; - } - - private void insertAndDeleteBatchWithX(int x) throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - for (int m = 0; m < x; m++) { - addInsertBatch(batch); - } - - TableBatchOperation delBatch = new TableBatchOperation(); - ArrayList results = tClient.execute(testSuiteTableName, batch); - for (TableResult r : results) { - Assert.assertEquals(r.getHttpStatusCode(), HttpURLConnection.HTTP_CREATED); - delBatch.delete((class1) r.getResult()); - } - - ArrayList delResults = tClient.execute(testSuiteTableName, delBatch); - for (TableResult r : delResults) { - Assert.assertEquals(r.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - } - - private void upsertAndDeleteBatchWithX(int x) throws StorageException { - TableBatchOperation batch = new TableBatchOperation(); - for (int m = 0; m < x; m++) { - addInsertOrMergeToBatch(generateRandomEnitity("jxscl_odata"), batch); - } - - TableBatchOperation delBatch = new TableBatchOperation(); - ArrayList results = tClient.execute(testSuiteTableName, batch); - for (TableResult r : results) { - Assert.assertEquals(r.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - delBatch.delete((class2) r.getResult()); - } - - ArrayList delResults = tClient.execute(testSuiteTableName, delBatch); - for (TableResult r : delResults) { - Assert.assertEquals(r.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableClientTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableClientTests.java deleted file mode 100644 index cb2891409164e..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableClientTests.java +++ /dev/null @@ -1,707 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.EnumSet; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.AuthenticationScheme; -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.RetryExponentialRetry; -import com.microsoft.windowsazure.services.core.storage.RetryLinearRetry; -import com.microsoft.windowsazure.services.core.storage.RetryPolicy; -import com.microsoft.windowsazure.services.core.storage.RetryResult; -import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Table Client Tests - */ -public class TableClientTests extends TableTestBase { - @Test - public void listTablesSegmented() throws IOException, URISyntaxException, StorageException { - String tableBaseName = generateRandomTableName(); - - ArrayList tables = new ArrayList(); - for (int m = 0; m < 20; m++) { - String name = String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(m)); - CloudTable table = tClient.getTableReference(name); - table.create(); - tables.add(name); - } - - try { - int currTable = 0; - ResultSegment segment1 = tClient.listTablesSegmented(tableBaseName, 5, null, null, null); - Assert.assertEquals(5, segment1.getLength()); - for (String s : segment1.getResults()) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - - ResultSegment segment2 = tClient.listTablesSegmented(tableBaseName, 5, - segment1.getContinuationToken(), null, null); - Assert.assertEquals(5, segment2.getLength()); - for (String s : segment2.getResults()) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - - ResultSegment segment3 = tClient.listTablesSegmented(tableBaseName, 5, - segment2.getContinuationToken(), null, null); - Assert.assertEquals(5, segment3.getLength()); - for (String s : segment3.getResults()) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - } - finally { - for (String s : tables) { - CloudTable table = tClient.getTableReference(s); - table.delete(); - } - } - } - - @Test - public void listTablesSegmentedNoPrefix() throws IOException, URISyntaxException, StorageException { - String tableBaseName = generateRandomTableName(); - ArrayList tables = new ArrayList(); - for (int m = 0; m < 20; m++) { - String name = String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(m)); - CloudTable table = tClient.getTableReference(name); - table.create(); - tables.add(name); - } - - try { - int currTable = 0; - ResultSegment segment1 = tClient.listTablesSegmented(null, 5, null, null, null); - Assert.assertEquals(5, segment1.getLength()); - for (String s : segment1.getResults()) { - if (s.startsWith(tableBaseName)) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - } - - ResultSegment segment2 = tClient.listTablesSegmented(null, 5, segment1.getContinuationToken(), - null, null); - Assert.assertEquals(5, segment2.getLength()); - for (String s : segment2.getResults()) { - if (s.startsWith(tableBaseName)) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - } - - ResultSegment segment3 = tClient.listTablesSegmented(null, 5, segment2.getContinuationToken(), - null, null); - Assert.assertEquals(5, segment3.getLength()); - for (String s : segment3.getResults()) { - if (s.startsWith(tableBaseName)) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - - } - } - finally { - for (String s : tables) { - CloudTable table = tClient.getTableReference(s); - table.delete(); - } - } - } - - @Test - public void listTablesWithIterator() throws IOException, URISyntaxException, StorageException { - String tableBaseName = generateRandomTableName(); - ArrayList tables = new ArrayList(); - for (int m = 0; m < 20; m++) { - String name = String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(m)); - CloudTable table = tClient.getTableReference(name); - table.create(); - tables.add(name); - } - - try { - // With prefix - int currTable = 0; - Iterable listTables = tClient.listTables(tableBaseName, null, null); - for (String s : listTables) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - - Assert.assertEquals(20, currTable); - // Second Iteration - currTable = 0; - for (String s : listTables) { - Assert.assertEquals(s, - String.format("%s%s", tableBaseName, new DecimalFormat("#0000").format(currTable))); - currTable++; - } - Assert.assertEquals(20, currTable); - - // Without prefix - currTable = 0; - Iterable listTablesNoPrefix = tClient.listTables(); - for (String s : listTablesNoPrefix) { - if (s.startsWith(tableBaseName)) { - currTable++; - } - } - - Assert.assertEquals(20, currTable); - currTable = 0; - for (String s : listTablesNoPrefix) { - if (s.startsWith(tableBaseName)) { - currTable++; - } - } - - Assert.assertEquals(20, currTable); - } - finally { - for (String s : tables) { - CloudTable table = tClient.getTableReference(s); - table.delete(); - } - } - } - - @Test - public void tableCreateAndAttemptCreateOnceExists() throws StorageException, URISyntaxException { - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - try { - table.create(); - Assert.assertTrue(table.exists()); - - // Should fail as it already exists - try { - table.create(); - fail(); - } - catch (StorageException ex) { - Assert.assertEquals(ex.getErrorCode(), "TableAlreadyExists"); - } - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - @Test - public void tableCreateExistsAndDelete() throws StorageException, URISyntaxException { - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - try { - Assert.assertTrue(table.createIfNotExist()); - Assert.assertTrue(table.exists()); - Assert.assertTrue(table.deleteIfExists()); - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - @Test - public void tableCreateIfNotExists() throws StorageException, URISyntaxException { - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - try { - Assert.assertTrue(table.createIfNotExist()); - Assert.assertTrue(table.exists()); - Assert.assertFalse(table.createIfNotExist()); - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - @Test - public void tableDeleteIfExists() throws StorageException, URISyntaxException { - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - - Assert.assertFalse(table.deleteIfExists()); - - table.create(); - Assert.assertTrue(table.exists()); - Assert.assertTrue(table.deleteIfExists()); - Assert.assertFalse(table.deleteIfExists()); - } - - @Test - public void tableDeleteWhenExistAndNotExists() throws StorageException, URISyntaxException { - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - - try { - // Should fail as it doesnt already exists - try { - table.delete(); - fail(); - } - catch (StorageException ex) { - Assert.assertEquals(ex.getMessage(), "Not Found"); - } - - table.create(); - Assert.assertTrue(table.exists()); - table.delete(); - Assert.assertFalse(table.exists()); - } - finally { - table.deleteIfExists(); - } - } - - @Test - public void tableDoesTableExist() throws StorageException, URISyntaxException { - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - - try { - Assert.assertFalse(table.exists()); - Assert.assertTrue(table.createIfNotExist()); - Assert.assertTrue(table.exists()); - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - @Test - public void tableGetSetPermissionTest() throws StorageException, URISyntaxException { - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - table.create(); - - TablePermissions expectedPermissions; - TablePermissions testPermissions; - - try { - // Test new permissions. - expectedPermissions = new TablePermissions(); - testPermissions = table.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - - // Test setting empty permissions. - table.uploadPermissions(expectedPermissions); - testPermissions = table.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - - // Add a policy, check setting and getting. - SharedAccessTablePolicy policy1 = new SharedAccessTablePolicy(); - Calendar now = GregorianCalendar.getInstance(); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 10); - policy1.setSharedAccessExpiryTime(now.getTime()); - - policy1.setPermissions(EnumSet.of(SharedAccessTablePermissions.ADD, SharedAccessTablePermissions.QUERY, - SharedAccessTablePermissions.UPDATE, SharedAccessTablePermissions.DELETE)); - expectedPermissions.getSharedAccessPolicies().put(UUID.randomUUID().toString(), policy1); - - table.uploadPermissions(expectedPermissions); - testPermissions = table.downloadPermissions(); - assertTablePermissionsEqual(expectedPermissions, testPermissions); - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - static void assertTablePermissionsEqual(TablePermissions expected, TablePermissions actual) { - HashMap expectedPolicies = expected.getSharedAccessPolicies(); - HashMap actualPolicies = actual.getSharedAccessPolicies(); - Assert.assertEquals("SharedAccessPolicies.Count", expectedPolicies.size(), actualPolicies.size()); - for (String name : expectedPolicies.keySet()) { - Assert.assertTrue("Key" + name + " doesn't exist", actualPolicies.containsKey(name)); - SharedAccessTablePolicy expectedPolicy = expectedPolicies.get(name); - SharedAccessTablePolicy actualPolicy = actualPolicies.get(name); - Assert.assertEquals("Policy: " + name + "\tPermissions\n", expectedPolicy.getPermissions().toString(), - actualPolicy.getPermissions().toString()); - Assert.assertEquals("Policy: " + name + "\tStartDate\n", expectedPolicy.getSharedAccessStartTime() - .toString(), actualPolicy.getSharedAccessStartTime().toString()); - Assert.assertEquals("Policy: " + name + "\tExpireDate\n", expectedPolicy.getSharedAccessExpiryTime() - .toString(), actualPolicy.getSharedAccessExpiryTime().toString()); - - } - - } - - @Test - public void testTableSASFromIdentifier() throws StorageException, URISyntaxException, InvalidKeyException { - String name = generateRandomTableName(); - CloudTable table = tClient.getTableReference(name); - table.create(); - - try { - TablePermissions expectedPermissions = new TablePermissions(); - String identifier = UUID.randomUUID().toString(); - // Add a policy, check setting and getting. - SharedAccessTablePolicy policy1 = new SharedAccessTablePolicy(); - Calendar now = GregorianCalendar.getInstance(); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 10); - policy1.setSharedAccessExpiryTime(now.getTime()); - - policy1.setPermissions(EnumSet.of(SharedAccessTablePermissions.ADD, SharedAccessTablePermissions.QUERY, - SharedAccessTablePermissions.UPDATE, SharedAccessTablePermissions.DELETE)); - expectedPermissions.getSharedAccessPolicies().put(identifier, policy1); - - table.uploadPermissions(expectedPermissions); - - // Insert 500 entities in Batches to query - for (int i = 0; i < 5; i++) { - TableBatchOperation batch = new TableBatchOperation(); - - for (int j = 0; j < 100; j++) { - class1 ent = generateRandomEnitity("javatables_batch_" + Integer.toString(i)); - ent.setRowKey(String.format("%06d", j)); - batch.insert(ent); - } - - tClient.execute(name, batch); - } - - CloudTableClient tableClientFromIdentifierSAS = getTableForSas(table, null, identifier, null, null, null, - null); - - { - class1 randEnt = TableTestBase.generateRandomEnitity(null); - TableQuery query = TableQuery.from(name, class1.class).where( - String.format("(PartitionKey eq '%s') and (RowKey ge '%s')", "javatables_batch_1", "000050")); - - int count = 0; - - for (class1 ent : tableClientFromIdentifierSAS.execute(query)) { - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), randEnt.getB()); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertEquals(ent.getPartitionKey(), "javatables_batch_1"); - Assert.assertEquals(ent.getRowKey(), String.format("%06d", count + 50)); - count++; - } - - Assert.assertEquals(count, 50); - } - - { - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("jxscl_odata"); - baseEntity.setRowKey(UUID.randomUUID().toString()); - - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - // Insert or merge Entity - ENTITY DOES NOT EXIST NOW. - TableResult insertResult = tableClientFromIdentifierSAS.execute(name, - TableOperation.insertOrMerge(baseEntity)); - - Assert.assertEquals(insertResult.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // Insert or replace Entity - ENTITY EXISTS -> WILL REPLACE - tableClientFromIdentifierSAS.execute(name, TableOperation.insertOrMerge(secondEntity)); - - // Retrieve entity - TableResult queryResult = tableClientFromIdentifierSAS.execute(name, TableOperation.retrieve( - baseEntity.getPartitionKey(), baseEntity.getRowKey(), DynamicTableEntity.class)); - - DynamicTableEntity retrievedEntity = queryResult. getResultAsType(); - - Assert.assertNotNull("Property A", retrievedEntity.getProperties().get("A")); - Assert.assertEquals(baseEntity.getA(), retrievedEntity.getProperties().get("A").getValueAsString()); - - Assert.assertNotNull("Property B", retrievedEntity.getProperties().get("B")); - Assert.assertEquals(baseEntity.getB(), retrievedEntity.getProperties().get("B").getValueAsString()); - - Assert.assertNotNull("Property C", retrievedEntity.getProperties().get("C")); - Assert.assertEquals(baseEntity.getC(), retrievedEntity.getProperties().get("C").getValueAsString()); - - Assert.assertNotNull("Property D", retrievedEntity.getProperties().get("D")); - Assert.assertTrue(Arrays.equals(baseEntity.getD(), retrievedEntity.getProperties().get("D") - .getValueAsByteArray())); - - // Validate New properties exist - Assert.assertNotNull("Property L", retrievedEntity.getProperties().get("L")); - Assert.assertEquals(secondEntity.getL(), retrievedEntity.getProperties().get("L").getValueAsString()); - - Assert.assertNotNull("Property M", retrievedEntity.getProperties().get("M")); - Assert.assertEquals(secondEntity.getM(), retrievedEntity.getProperties().get("M").getValueAsString()); - - Assert.assertNotNull("Property N", retrievedEntity.getProperties().get("N")); - Assert.assertEquals(secondEntity.getN(), retrievedEntity.getProperties().get("N").getValueAsString()); - - Assert.assertNotNull("Property O", retrievedEntity.getProperties().get("O")); - Assert.assertEquals(secondEntity.getO(), retrievedEntity.getProperties().get("O").getValueAsString()); - } - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - @Test - public void testTableSASFromPermission() throws StorageException, URISyntaxException, InvalidKeyException { - String name = generateRandomTableName(); - CloudTable table = tClient.getTableReference(name); - table.create(); - - try { - TablePermissions expectedPermissions = new TablePermissions(); - String identifier = UUID.randomUUID().toString(); - // Add a policy, check setting and getting. - SharedAccessTablePolicy policy1 = new SharedAccessTablePolicy(); - Calendar now = GregorianCalendar.getInstance(); - now.add(Calendar.MINUTE, -10); - policy1.setSharedAccessStartTime(now.getTime()); - now.add(Calendar.MINUTE, 30); - policy1.setSharedAccessExpiryTime(now.getTime()); - - policy1.setPermissions(EnumSet.of(SharedAccessTablePermissions.ADD, SharedAccessTablePermissions.QUERY, - SharedAccessTablePermissions.UPDATE, SharedAccessTablePermissions.DELETE)); - expectedPermissions.getSharedAccessPolicies().put(identifier, policy1); - - table.uploadPermissions(expectedPermissions); - - // Insert 500 entities in Batches to query - for (int i = 0; i < 5; i++) { - TableBatchOperation batch = new TableBatchOperation(); - - for (int j = 0; j < 100; j++) { - class1 ent = generateRandomEnitity("javatables_batch_" + Integer.toString(i)); - ent.setRowKey(String.format("%06d", j)); - batch.insert(ent); - } - - tClient.execute(name, batch); - } - - CloudTableClient tableClientFromPermission = getTableForSas(table, policy1, null, "javatables_batch_0", - "0", "javatables_batch_9", "9"); - CloudTableClient tableClientFromPermissionJustPks = getTableForSas(table, policy1, null, - "javatables_batch_0", null, "javatables_batch_9", null); - - { - TableBatchOperation batchFromSAS = new TableBatchOperation(); - - for (int j = 1000; j < 1010; j++) { - class1 ent = generateRandomEnitity("javatables_batch_" + Integer.toString(0)); - ent.setRowKey(String.format("%06d", j)); - batchFromSAS.insert(ent); - } - - tableClientFromPermission.execute(name, batchFromSAS); - - class1 randEnt = TableTestBase.generateRandomEnitity(null); - TableQuery query = TableQuery.from(name, class1.class).where( - String.format("(PartitionKey eq '%s') and (RowKey ge '%s')", "javatables_batch_1", "000050")); - - int count = 0; - - for (class1 ent : tableClientFromPermission.execute(query)) { - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), randEnt.getB()); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertEquals(ent.getPartitionKey(), "javatables_batch_1"); - Assert.assertEquals(ent.getRowKey(), String.format("%06d", count + 50)); - count++; - } - - Assert.assertEquals(count, 50); - - count = 0; - - for (class1 ent : tableClientFromPermissionJustPks.execute(query)) { - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), randEnt.getB()); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertEquals(ent.getPartitionKey(), "javatables_batch_1"); - Assert.assertEquals(ent.getRowKey(), String.format("%06d", count + 50)); - count++; - } - - Assert.assertEquals(count, 50); - } - - { - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("javatables_batch_0" + UUID.randomUUID().toString()); - baseEntity.setRowKey("0" + UUID.randomUUID().toString()); - - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - TableResult insertResult = tableClientFromPermission.execute(name, - TableOperation.insertOrMerge(baseEntity)); - - // Insert or merge Entity - ENTITY DOES NOT EXIST NOW. - - Assert.assertEquals(insertResult.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - - // Insert or replace Entity - ENTITY EXISTS -> WILL REPLACE - tableClientFromPermission.execute(name, TableOperation.insertOrMerge(secondEntity)); - - // Retrieve entity - TableResult queryResult = tableClientFromPermission.execute(name, TableOperation.retrieve( - baseEntity.getPartitionKey(), baseEntity.getRowKey(), DynamicTableEntity.class)); - - DynamicTableEntity retrievedEntity = queryResult. getResultAsType(); - - Assert.assertNotNull("Property A", retrievedEntity.getProperties().get("A")); - Assert.assertEquals(baseEntity.getA(), retrievedEntity.getProperties().get("A").getValueAsString()); - - Assert.assertNotNull("Property B", retrievedEntity.getProperties().get("B")); - Assert.assertEquals(baseEntity.getB(), retrievedEntity.getProperties().get("B").getValueAsString()); - - Assert.assertNotNull("Property C", retrievedEntity.getProperties().get("C")); - Assert.assertEquals(baseEntity.getC(), retrievedEntity.getProperties().get("C").getValueAsString()); - - Assert.assertNotNull("Property D", retrievedEntity.getProperties().get("D")); - Assert.assertTrue(Arrays.equals(baseEntity.getD(), retrievedEntity.getProperties().get("D") - .getValueAsByteArray())); - - // Validate New properties exist - Assert.assertNotNull("Property L", retrievedEntity.getProperties().get("L")); - Assert.assertEquals(secondEntity.getL(), retrievedEntity.getProperties().get("L").getValueAsString()); - - Assert.assertNotNull("Property M", retrievedEntity.getProperties().get("M")); - Assert.assertEquals(secondEntity.getM(), retrievedEntity.getProperties().get("M").getValueAsString()); - - Assert.assertNotNull("Property N", retrievedEntity.getProperties().get("N")); - Assert.assertEquals(secondEntity.getN(), retrievedEntity.getProperties().get("N").getValueAsString()); - - Assert.assertNotNull("Property O", retrievedEntity.getProperties().get("O")); - Assert.assertEquals(secondEntity.getO(), retrievedEntity.getProperties().get("O").getValueAsString()); - } - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - @Test - public void tableCreateAndAttemptCreateOnceExistsSharedKeyLite() throws StorageException, URISyntaxException { - tClient.setAuthenticationScheme(AuthenticationScheme.SHAREDKEYLITE); - String tableName = generateRandomTableName(); - CloudTable table = tClient.getTableReference(tableName); - try { - table.create(); - Assert.assertTrue(table.exists()); - - // Should fail as it already exists - try { - table.create(); - fail(); - } - catch (StorageException ex) { - Assert.assertEquals(ex.getErrorCode(), "TableAlreadyExists"); - } - } - finally { - // cleanup - table.deleteIfExists(); - } - } - - private CloudTableClient getTableForSas(CloudTable table, SharedAccessTablePolicy policy, String accessIdentifier, - String startPk, String startRk, String endPk, String endRk) throws InvalidKeyException, StorageException { - String sasString = table - .generateSharedAccessSignature(policy, accessIdentifier, startPk, startRk, endPk, endRk); - return new CloudTableClient(tClient.getEndpoint(), new StorageCredentialsSharedAccessSignature(sasString)); - } - - @Test - public void VerifyBackoffTimeOverflow() { - RetryExponentialRetry exponentialRetry = new RetryExponentialRetry(4000, 100000); - VerifyBackoffTimeOverflow(exponentialRetry, 100000); - - RetryLinearRetry linearRetry = new RetryLinearRetry(4000, 100000); - VerifyBackoffTimeOverflow(linearRetry, 100000); - } - - private void VerifyBackoffTimeOverflow(RetryPolicy retryPolicy, int maxAttempts) { - Exception e = new Exception(); - OperationContext context = new OperationContext(); - int previousRetryInterval = 1000; // larger than zero to ensure we never get zero back - - for (int i = 0; i < maxAttempts; i++) { - RetryResult result = retryPolicy.shouldRetry(i, HttpURLConnection.HTTP_INTERNAL_ERROR, e, context); - int retryInterval = result.getBackOffIntervalInMs(); - Assert.assertTrue(String.format("Attempt: '%d'", i), result.isShouldRetry()); - Assert.assertTrue(String.format("Retry Interval: '%d', Previous Retry Interval: '%d', Attempt: '%d'", - retryInterval, previousRetryInterval, i), retryInterval >= previousRetryInterval); - previousRetryInterval = retryInterval; - } - - Assert.assertFalse(retryPolicy.shouldRetry(maxAttempts, HttpURLConnection.HTTP_INTERNAL_ERROR, e, context) - .isShouldRetry()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableEscapingTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableEscapingTests.java deleted file mode 100644 index c09011a908258..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableEscapingTests.java +++ /dev/null @@ -1,257 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Table Escaping Tests - */ -public class TableEscapingTests extends TableTestBase { - @Test - public void emptyString() throws StorageException { - doEscapeTest("", false, true); - } - - @Test - public void emptyStringBatch() throws StorageException { - doEscapeTest("", true, true); - } - - @Test - public void randomChars() throws StorageException { - doEscapeTest("!$'\"()*+,;=", false); - } - - @Test - public void randomCharsBatch() throws StorageException { - doEscapeTest("!$'\"()*+,;=", true); - } - - @Test - @Ignore - public void percent25() throws StorageException { - // Disabled Until Double Percent decoding issue is fixed for single entity operations - // doEscapeTest("foo%25", false, true); - } - - @Test - public void percent25Batch() throws StorageException { - doEscapeTest("foo%25", true, true); - } - - @Test - public void regularPKInQuery() throws StorageException { - doQueryEscapeTest("data"); - } - - @Test - public void specialChars() throws StorageException { - doEscapeTest("\\ // @ ? ", false); - doEscapeTest("", false); - doEscapeTest("
", false); - doEscapeTest("!<", false); - doEscapeTest("", false); - doEscapeTest("", false); - doEscapeTest("
", false); - doEscapeTest("!<", false); - doEscapeTest(" query = TableQuery.from(testSuiteTableName, class1.class).where( - String.format("(PartitionKey eq '%s') and (A eq '%s')", ref.getPartitionKey(), data)); - - int count = 0; - - for (class1 ent : tClient.execute(query)) { - count++; - Assert.assertEquals(ent.getA(), ref.getA()); - Assert.assertEquals(ent.getB(), ref.getB()); - Assert.assertEquals(ent.getC(), ref.getC()); - Assert.assertEquals(ent.getPartitionKey(), ref.getPartitionKey()); - Assert.assertEquals(ent.getRowKey(), ref.getRowKey()); - } - - Assert.assertEquals(count, 1); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableOperationTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableOperationTests.java deleted file mode 100644 index cb11cfbfe12df..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableOperationTests.java +++ /dev/null @@ -1,599 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import static org.junit.Assert.*; - -import java.net.HttpURLConnection; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Table Operation Tests - */ -public class TableOperationTests extends TableTestBase { - @Test - public void delete() throws StorageException { - class1 ref = new class1(); - - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - TableOperation op = TableOperation.insert(ref); - - tClient.execute(testSuiteTableName, op); - tClient.execute(testSuiteTableName, TableOperation.delete(ref)); - - TableResult res2 = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), class1.class)); - - Assert.assertTrue(res2.getResult() == null); - } - - @Test - public void deleteFail() throws StorageException { - class1 ref = new class1(); - - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - String oldEtag = ref.getEtag(); - - // update entity - ref.setA("updated"); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - ref.setEtag(oldEtag); - - try { - tClient.execute(testSuiteTableName, TableOperation.delete(ref)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Precondition Failed"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The update condition specified in the request was not satisfied.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "UpdateConditionNotSatisfied"); - } - - TableResult res2 = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), class1.class)); - - ref = res2.getResultAsType(); - // actually delete it - tClient.execute(testSuiteTableName, TableOperation.delete(ref)); - - // now try to delete it and fail - try { - tClient.execute(testSuiteTableName, TableOperation.delete(ref)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Not Found"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The specified resource does not exist.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "ResourceNotFound"); - } - } - - @Test - public void emptyRetrieve() throws StorageException { - class1 ref = new class1(); - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), class1.class)); - - Assert.assertNull(res.getResult()); - Assert.assertEquals(res.getHttpStatusCode(), HttpURLConnection.HTTP_NOT_FOUND); - } - - @Test - public void insertOrMerge() throws StorageException { - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("jxscl_odata"); - baseEntity.setRowKey(UUID.randomUUID().toString()); - - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - // Insert or merge Entity - ENTITY DOES NOT EXIST NOW. - TableResult insertResult = tClient.execute(testSuiteTableName, TableOperation.insertOrMerge(baseEntity)); - - Assert.assertEquals(insertResult.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - Assert.assertNotNull(insertResult.getEtag()); - - // Insert or replace Entity - ENTITY EXISTS -> WILL REPLACE - tClient.execute(testSuiteTableName, TableOperation.insertOrMerge(secondEntity)); - - // Retrieve entity - TableResult queryResult = tClient - .execute(testSuiteTableName, TableOperation.retrieve(baseEntity.getPartitionKey(), - baseEntity.getRowKey(), DynamicTableEntity.class)); - - DynamicTableEntity retrievedEntity = queryResult. getResultAsType(); - - Assert.assertNotNull("Property A", retrievedEntity.getProperties().get("A")); - Assert.assertEquals(baseEntity.getA(), retrievedEntity.getProperties().get("A").getValueAsString()); - - Assert.assertNotNull("Property B", retrievedEntity.getProperties().get("B")); - Assert.assertEquals(baseEntity.getB(), retrievedEntity.getProperties().get("B").getValueAsString()); - - Assert.assertNotNull("Property C", retrievedEntity.getProperties().get("C")); - Assert.assertEquals(baseEntity.getC(), retrievedEntity.getProperties().get("C").getValueAsString()); - - Assert.assertNotNull("Property D", retrievedEntity.getProperties().get("D")); - Assert.assertTrue(Arrays.equals(baseEntity.getD(), retrievedEntity.getProperties().get("D") - .getValueAsByteArray())); - - // Validate New properties exist - Assert.assertNotNull("Property L", retrievedEntity.getProperties().get("L")); - Assert.assertEquals(secondEntity.getL(), retrievedEntity.getProperties().get("L").getValueAsString()); - - Assert.assertNotNull("Property M", retrievedEntity.getProperties().get("M")); - Assert.assertEquals(secondEntity.getM(), retrievedEntity.getProperties().get("M").getValueAsString()); - - Assert.assertNotNull("Property N", retrievedEntity.getProperties().get("N")); - Assert.assertEquals(secondEntity.getN(), retrievedEntity.getProperties().get("N").getValueAsString()); - - Assert.assertNotNull("Property O", retrievedEntity.getProperties().get("O")); - Assert.assertEquals(secondEntity.getO(), retrievedEntity.getProperties().get("O").getValueAsString()); - } - - @Test - public void insertOrReplace() throws StorageException { - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("jxscl_odata"); - baseEntity.setRowKey(UUID.randomUUID().toString()); - - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - // Insert or replace Entity - ENTITY DOES NOT EXIST NOW. - TableResult insertResult = tClient.execute(testSuiteTableName, TableOperation.insertOrReplace(baseEntity)); - - Assert.assertEquals(insertResult.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - Assert.assertNotNull(insertResult.getEtag()); - - // Insert or replace Entity - ENTITY EXISTS -> WILL REPLACE - tClient.execute(testSuiteTableName, TableOperation.insertOrReplace(secondEntity)); - - // Retrieve entity - TableResult queryResult = tClient - .execute(testSuiteTableName, TableOperation.retrieve(baseEntity.getPartitionKey(), - baseEntity.getRowKey(), DynamicTableEntity.class)); - - DynamicTableEntity retrievedEntity = queryResult.getResultAsType(); - - // Validate old properties dont exist - Assert.assertTrue(retrievedEntity.getProperties().get("A") == null); - Assert.assertTrue(retrievedEntity.getProperties().get("B") == null); - Assert.assertTrue(retrievedEntity.getProperties().get("C") == null); - Assert.assertTrue(retrievedEntity.getProperties().get("D") == null); - - // Validate New properties exist - Assert.assertNotNull("Property L", retrievedEntity.getProperties().get("L")); - Assert.assertEquals(secondEntity.getL(), retrievedEntity.getProperties().get("L").getValueAsString()); - - Assert.assertNotNull("Property M", retrievedEntity.getProperties().get("M")); - Assert.assertEquals(secondEntity.getM(), retrievedEntity.getProperties().get("M").getValueAsString()); - - Assert.assertNotNull("Property N", retrievedEntity.getProperties().get("N")); - Assert.assertEquals(secondEntity.getN(), retrievedEntity.getProperties().get("N").getValueAsString()); - - Assert.assertNotNull("Property O", retrievedEntity.getProperties().get("O")); - Assert.assertEquals(secondEntity.getO(), retrievedEntity.getProperties().get("O").getValueAsString()); - } - - @Test - public void merge() throws StorageException { - // Insert base entity - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("jxscl_odata"); - baseEntity.setRowKey(UUID.randomUUID().toString()); - - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - - TableResult mergeResult = tClient.execute(testSuiteTableName, TableOperation.merge(secondEntity)); - - Assert.assertEquals(mergeResult.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - Assert.assertNotNull(mergeResult.getEtag()); - - TableResult res2 = tClient.execute(testSuiteTableName, TableOperation.retrieve(secondEntity.getPartitionKey(), - secondEntity.getRowKey(), DynamicTableEntity.class)); - DynamicTableEntity mergedEntity = (DynamicTableEntity) res2.getResult(); - - Assert.assertNotNull("Property A", mergedEntity.getProperties().get("A")); - Assert.assertEquals(baseEntity.getA(), mergedEntity.getProperties().get("A").getValueAsString()); - - Assert.assertNotNull("Property B", mergedEntity.getProperties().get("B")); - Assert.assertEquals(baseEntity.getB(), mergedEntity.getProperties().get("B").getValueAsString()); - - Assert.assertNotNull("Property C", mergedEntity.getProperties().get("C")); - Assert.assertEquals(baseEntity.getC(), mergedEntity.getProperties().get("C").getValueAsString()); - - Assert.assertNotNull("Property D", mergedEntity.getProperties().get("D")); - Assert.assertTrue(Arrays.equals(baseEntity.getD(), mergedEntity.getProperties().get("D").getValueAsByteArray())); - - Assert.assertNotNull("Property L", mergedEntity.getProperties().get("L")); - Assert.assertEquals(secondEntity.getL(), mergedEntity.getProperties().get("L").getValueAsString()); - - Assert.assertNotNull("Property M", mergedEntity.getProperties().get("M")); - Assert.assertEquals(secondEntity.getM(), mergedEntity.getProperties().get("M").getValueAsString()); - - Assert.assertNotNull("Property N", mergedEntity.getProperties().get("N")); - Assert.assertEquals(secondEntity.getN(), mergedEntity.getProperties().get("N").getValueAsString()); - - Assert.assertNotNull("Property O", mergedEntity.getProperties().get("O")); - Assert.assertEquals(secondEntity.getO(), mergedEntity.getProperties().get("O").getValueAsString()); - } - - @Test - public void mergeFail() throws StorageException { - // Insert base entity - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("jxscl_odata"); - baseEntity.setRowKey(UUID.randomUUID().toString()); - - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - - class2 secondEntity = new class2(); - secondEntity.setL("foo_L"); - secondEntity.setM("foo_M"); - secondEntity.setN("foo_N"); - secondEntity.setO("foo_O"); - secondEntity.setPartitionKey(baseEntity.getPartitionKey()); - secondEntity.setRowKey(baseEntity.getRowKey()); - secondEntity.setEtag(baseEntity.getEtag()); - String oldEtag = baseEntity.getEtag(); - - tClient.execute(testSuiteTableName, TableOperation.merge(secondEntity)); - - secondEntity.setEtag(oldEtag); - secondEntity.setL("updated"); - try { - tClient.execute(testSuiteTableName, TableOperation.merge(secondEntity)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Precondition Failed"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The update condition specified in the request was not satisfied.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "UpdateConditionNotSatisfied"); - } - - // delete entity - TableResult queryResult = tClient - .execute(testSuiteTableName, TableOperation.retrieve(baseEntity.getPartitionKey(), - baseEntity.getRowKey(), DynamicTableEntity.class)); - - DynamicTableEntity retrievedEntity = queryResult.getResultAsType(); - tClient.execute(testSuiteTableName, TableOperation.delete(retrievedEntity)); - - try { - tClient.execute(testSuiteTableName, TableOperation.merge(secondEntity)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Not Found"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The specified resource does not exist.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "ResourceNotFound"); - } - } - - @Test - public void retrieveWithoutResolver() throws StorageException { - class1 ref = new class1(); - - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), class1.class)); - - @SuppressWarnings("unused") - class1 retrievedEnt = res.getResultAsType(); - - Assert.assertEquals(((class1) res.getResult()).getA(), ref.getA()); - } - - @Test - public void retrieveWithResolver() throws StorageException { - class1 ref = new class1(); - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - TableOperation op = TableOperation.insert(ref); - - tClient.execute(testSuiteTableName, op); - - TableResult res4 = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), new EntityResolver() { - @Override - public String resolve(String partitionKey, String rowKey, Date timeStamp, - HashMap properties, String etag) { - return properties.get("A").getValueAsString(); - } - })); - - Assert.assertEquals(res4.getResult().toString(), ref.getA()); - } - - @Test - public void retrieveWithNullResolver() throws StorageException { - try { - TableOperation.retrieve("foo", "blah", (EntityResolver) null); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "Query requires a valid class type or resolver."); - } - } - - @Test - public void insertFail() throws StorageException { - class1 ref = new class1(); - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - TableOperation op = TableOperation.insert(ref); - - tClient.execute(testSuiteTableName, op); - try { - tClient.execute(testSuiteTableName, op); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Conflict"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The specified entity already exists")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "EntityAlreadyExists"); - } - } - - @Test - public void replace() throws StorageException { - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("jxscl_odata"); - baseEntity.setRowKey(UUID.randomUUID().toString()); - - // Insert entity - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - - TableResult queryResult = tClient - .execute(testSuiteTableName, TableOperation.retrieve(baseEntity.getPartitionKey(), - baseEntity.getRowKey(), DynamicTableEntity.class)); - // Retrieve entity - DynamicTableEntity retrievedEntity = queryResult. getResultAsType(); - Assert.assertNotNull("Property D", retrievedEntity.getProperties().get("D")); - Assert.assertTrue(Arrays.equals(baseEntity.getD(), retrievedEntity.getProperties().get("D") - .getValueAsByteArray())); - - // Remove property and update - retrievedEntity.getProperties().remove("D"); - - TableResult replaceResult = tClient.execute(testSuiteTableName, TableOperation.replace(retrievedEntity)); - - Assert.assertEquals(replaceResult.getHttpStatusCode(), HttpURLConnection.HTTP_NO_CONTENT); - Assert.assertNotNull(replaceResult.getEtag()); - - // Retrieve Entity - queryResult = tClient - .execute(testSuiteTableName, TableOperation.retrieve(baseEntity.getPartitionKey(), - baseEntity.getRowKey(), DynamicTableEntity.class)); - - retrievedEntity = queryResult. getResultAsType(); - - // Validate - Assert.assertNotNull("Property A", retrievedEntity.getProperties().get("A")); - Assert.assertEquals(baseEntity.getA(), retrievedEntity.getProperties().get("A").getValueAsString()); - - Assert.assertNotNull("Property B", retrievedEntity.getProperties().get("B")); - Assert.assertEquals(baseEntity.getB(), retrievedEntity.getProperties().get("B").getValueAsString()); - - Assert.assertNotNull("Property C", retrievedEntity.getProperties().get("C")); - Assert.assertEquals(baseEntity.getC(), retrievedEntity.getProperties().get("C").getValueAsString()); - - Assert.assertTrue(retrievedEntity.getProperties().get("D") == null); - } - - @Test - public void replaceFail() throws StorageException { - class1 baseEntity = new class1(); - baseEntity.setA("foo_A"); - baseEntity.setB("foo_B"); - baseEntity.setC("foo_C"); - baseEntity.setD(new byte[] { 0, 1, 2 }); - baseEntity.setPartitionKey("jxscl_odata"); - baseEntity.setRowKey(UUID.randomUUID().toString()); - - // Insert entity - tClient.execute(testSuiteTableName, TableOperation.insert(baseEntity)); - - String oldEtag = baseEntity.getEtag(); - - TableResult queryResult = tClient - .execute(testSuiteTableName, TableOperation.retrieve(baseEntity.getPartitionKey(), - baseEntity.getRowKey(), DynamicTableEntity.class)); - - // Retrieve entity - DynamicTableEntity retrievedEntity = queryResult. getResultAsType(); - Assert.assertNotNull("Property D", retrievedEntity.getProperties().get("D")); - Assert.assertTrue(Arrays.equals(baseEntity.getD(), retrievedEntity.getProperties().get("D") - .getValueAsByteArray())); - - // Remove property and update - retrievedEntity.getProperties().remove("D"); - - tClient.execute(testSuiteTableName, TableOperation.replace(retrievedEntity)); - - retrievedEntity.setEtag(oldEtag); - - try { - tClient.execute(testSuiteTableName, TableOperation.replace(retrievedEntity)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Precondition Failed"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The update condition specified in the request was not satisfied.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "UpdateConditionNotSatisfied"); - } - - // delete entity - queryResult = tClient - .execute(testSuiteTableName, TableOperation.retrieve(baseEntity.getPartitionKey(), - baseEntity.getRowKey(), DynamicTableEntity.class)); - - tClient.execute(testSuiteTableName, TableOperation.delete((DynamicTableEntity) queryResult.getResultAsType())); - - try { - tClient.execute(testSuiteTableName, TableOperation.replace(retrievedEntity)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Not Found"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The specified resource does not exist.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "ResourceNotFound"); - } - } - - @Test - public void insertEntityOver1MB() throws StorageException { - class1 ref = new class1(); - - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - // 1mb right here - ref.setD(new byte[1024 * 1024]); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - try { - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Bad Request"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("The entity is larger than allowed by the Table Service.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "EntityTooLarge"); - } - } - - @Test - public void insertEntityWithPropertyMoreThan255chars() throws StorageException { - DynamicTableEntity ref = new DynamicTableEntity(); - - String propName = ""; - for (int m = 0; m < 255; m++) { - propName.concat(Integer.toString(m % 9)); - } - - ref.getProperties().put(propName, new EntityProperty("test")); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - try { - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Bad Request"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("One of the request inputs is not valid.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "InvalidInput"); - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableQueryTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableQueryTests.java deleted file mode 100644 index d8818dddc09c2..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableQueryTests.java +++ /dev/null @@ -1,470 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.OperationContext; -import com.microsoft.windowsazure.services.core.storage.ResponseReceivedEvent; -import com.microsoft.windowsazure.services.core.storage.ResultSegment; -import com.microsoft.windowsazure.services.core.storage.StorageEvent; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.table.client.TableQuery.QueryComparisons; - -/** - * Table Query Tests - */ -public class TableQueryTests extends TableTestBase { - @BeforeClass - public static void setup() throws URISyntaxException, StorageException, InvalidKeyException { - TableTestBase.setup(); - - // Insert 500 entities in Batches to query - for (int i = 0; i < 5; i++) { - TableBatchOperation batch = new TableBatchOperation(); - - for (int j = 0; j < 100; j++) { - class1 ent = generateRandomEnitity("javatables_batch_" + Integer.toString(i)); - ent.setRowKey(String.format("%06d", j)); - batch.insert(ent); - } - - tClient.execute(testSuiteTableName, batch); - } - } - - @Test - public void tableQueryIterateTwice() { - // Create entity to check against - class1 randEnt = TableTestBase.generateRandomEnitity(null); - - final Iterable result = tClient.execute(TableQuery.from(testSuiteTableName, - DynamicTableEntity.class).take(50)); - - ArrayList firstIteration = new ArrayList(); - ArrayList secondIteration = new ArrayList(); - - // Validate results - for (DynamicTableEntity ent : result) { - Assert.assertEquals(ent.getProperties().size(), 4); - Assert.assertEquals(ent.getProperties().get("A").getValueAsString(), randEnt.getA()); - Assert.assertEquals(ent.getProperties().get("B").getValueAsString(), randEnt.getB()); - Assert.assertEquals(ent.getProperties().get("C").getValueAsString(), randEnt.getC()); - Assert.assertTrue(Arrays.equals(ent.getProperties().get("D").getValueAsByteArray(), randEnt.getD())); - firstIteration.add(ent); - } - - // Validate results - for (DynamicTableEntity ent : result) { - Assert.assertEquals(ent.getProperties().size(), 4); - Assert.assertEquals(ent.getProperties().get("A").getValueAsString(), randEnt.getA()); - Assert.assertEquals(ent.getProperties().get("B").getValueAsString(), randEnt.getB()); - Assert.assertEquals(ent.getProperties().get("C").getValueAsString(), randEnt.getC()); - Assert.assertTrue(Arrays.equals(ent.getProperties().get("D").getValueAsByteArray(), randEnt.getD())); - secondIteration.add(ent); - } - - Assert.assertEquals(firstIteration.size(), secondIteration.size()); - for (int m = 0; m < firstIteration.size(); m++) { - Assert.assertEquals(firstIteration.get(m).getPartitionKey(), secondIteration.get(m).getPartitionKey()); - Assert.assertEquals(firstIteration.get(m).getRowKey(), secondIteration.get(m).getRowKey()); - Assert.assertEquals(firstIteration.get(m).getProperties().size(), secondIteration.get(m).getProperties() - .size()); - Assert.assertEquals(firstIteration.get(m).getProperties().get("A").getValueAsString(), - secondIteration.get(m).getProperties().get("A").getValueAsString()); - Assert.assertEquals(firstIteration.get(m).getProperties().get("B").getValueAsString(), - secondIteration.get(m).getProperties().get("B").getValueAsString()); - Assert.assertEquals(firstIteration.get(m).getProperties().get("C").getValueAsString(), - secondIteration.get(m).getProperties().get("C").getValueAsString()); - Assert.assertTrue(Arrays.equals(firstIteration.get(m).getProperties().get("D").getValueAsByteArray(), - secondIteration.get(m).getProperties().get("D").getValueAsByteArray())); - } - } - - @Test - public void tableQueryWithDynamicEntity() { - // Create entity to check against - class1 randEnt = TableTestBase.generateRandomEnitity(null); - - final Iterable result = tClient.execute(TableQuery.from(testSuiteTableName, - DynamicTableEntity.class)); - - // Validate results - for (DynamicTableEntity ent : result) { - Assert.assertEquals(ent.getProperties().size(), 4); - Assert.assertEquals(ent.getProperties().get("A").getValueAsString(), randEnt.getA()); - Assert.assertEquals(ent.getProperties().get("B").getValueAsString(), randEnt.getB()); - Assert.assertEquals(ent.getProperties().get("C").getValueAsString(), randEnt.getC()); - Assert.assertTrue(Arrays.equals(ent.getProperties().get("D").getValueAsByteArray(), randEnt.getD())); - } - } - - @Test - public void tableQueryWithProjection() { - // Create entity to check against - class1 randEnt = TableTestBase.generateRandomEnitity(null); - final Iterable result = tClient.execute(TableQuery.from(testSuiteTableName, class1.class).select( - new String[] { "A", "C" })); - - // Validate results - for (class1 ent : result) { - // Validate core properties were sent. - Assert.assertNotNull(ent.getPartitionKey()); - Assert.assertNotNull(ent.getRowKey()); - Assert.assertNotNull(ent.getTimestamp()); - - // Validate correct columsn returned. - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), null); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertEquals(ent.getD(), null); - } - } - - @Test - public void ensureSelectOnlySendsReservedColumnsOnce() { - OperationContext opContext = new OperationContext(); - opContext.getResponseReceivedEventHandler().addListener(new StorageEvent() { - - @Override - public void eventOccurred(ResponseReceivedEvent eventArg) { - HttpURLConnection conn = (HttpURLConnection) eventArg.getConnectionObject(); - - String urlString = conn.getURL().toString(); - - Assert.assertEquals(urlString.indexOf("PartitionKey"), urlString.lastIndexOf("PartitionKey")); - Assert.assertEquals(urlString.indexOf("RowKey"), urlString.lastIndexOf("RowKey")); - Assert.assertEquals(urlString.indexOf("Timestamp"), urlString.lastIndexOf("Timestamp")); - } - }); - - final Iterable result = tClient.execute( - TableQuery.from(testSuiteTableName, class1.class).select( - new String[] { "PartitionKey", "RowKey", "Timestamp" }), null, opContext); - - // Validate results - for (class1 ent : result) { - Assert.assertEquals(ent.getA(), null); - Assert.assertEquals(ent.getB(), null); - Assert.assertEquals(ent.getC(), null); - Assert.assertEquals(ent.getD(), null); - } - } - - @Test - public void tableQueryWithReflection() { - // Create entity to check against - class1 randEnt = TableTestBase.generateRandomEnitity(null); - - final Iterable result = tClient.execute(TableQuery.from(testSuiteTableName, class1.class)); - - // Validate results - for (class1 ent : result) { - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), randEnt.getB()); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertTrue(Arrays.equals(ent.getD(), randEnt.getD())); - } - } - - @Test - public void tableQueryWithResolver() { - // Create entity to check against - class1 randEnt = TableTestBase.generateRandomEnitity(null); - - final Iterable result = tClient.execute(TableQuery.from(testSuiteTableName, TableServiceEntity.class), - new EntityResolver() { - @Override - public class1 resolve(String partitionKey, String rowKey, Date timeStamp, - HashMap properties, String etag) { - Assert.assertEquals(properties.size(), 4); - class1 ref = new class1(); - ref.setA(properties.get("A").getValueAsString()); - ref.setB(properties.get("B").getValueAsString()); - ref.setC(properties.get("C").getValueAsString()); - ref.setD(properties.get("D").getValueAsByteArray()); - return ref; - } - }); - - // Validate results - for (class1 ent : result) { - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), randEnt.getB()); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertTrue(Arrays.equals(ent.getD(), randEnt.getD())); - } - } - - @Test - public void tableQueryWithTake() throws IOException, URISyntaxException, StorageException { - // Create entity to check against - class1 randEnt = TableTestBase.generateRandomEnitity(null); - final ResultSegment result = tClient.executeSegmented(TableQuery.from(testSuiteTableName, class1.class) - .select(new String[] { "A", "C" }).take(25), null); - - int count = 0; - // Validate results - for (class1 ent : result.getResults()) { - count++; - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), null); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertEquals(ent.getD(), null); - } - - Assert.assertEquals(count, 25); - } - - @Test - public void tableQueryWithFilter() throws StorageException { - class1 randEnt = TableTestBase.generateRandomEnitity(null); - TableQuery query = TableQuery.from(testSuiteTableName, class1.class).where( - String.format("(PartitionKey eq '%s') and (RowKey ge '%s')", "javatables_batch_1", "000050")); - - int count = 0; - - for (class1 ent : tClient.execute(query)) { - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), randEnt.getB()); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertEquals(ent.getPartitionKey(), "javatables_batch_1"); - Assert.assertEquals(ent.getRowKey(), String.format("%06d", count + 50)); - count++; - } - - Assert.assertEquals(count, 50); - } - - @Test - public void tableQueryWithContinuation() throws StorageException { - class1 randEnt = TableTestBase.generateRandomEnitity(null); - TableQuery query = TableQuery.from(testSuiteTableName, class1.class) - .where(String.format("(PartitionKey ge '%s') and (RowKey ge '%s')", "javatables_batch_1", "000050")) - .take(25); - - // take will cause the query to return 25 at a time - - int count = 0; - int pk = 1; - for (class1 ent : tClient.execute(query)) { - Assert.assertEquals(ent.getA(), randEnt.getA()); - Assert.assertEquals(ent.getB(), randEnt.getB()); - Assert.assertEquals(ent.getC(), randEnt.getC()); - Assert.assertEquals(ent.getPartitionKey(), "javatables_batch_" + Integer.toString(pk)); - Assert.assertEquals(ent.getRowKey(), String.format("%06d", count % 50 + 50)); - count++; - - if (count % 50 == 0) { - pk++; - } - } - - Assert.assertEquals(count, 200); - } - - @Test - public void testQueryWithNullClassType() throws StorageException { - try { - TableQuery.from(testSuiteTableName, null); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "Query requires a valid class type."); - } - } - - @Test - public void testQueryWithInvalidTakeCount() throws StorageException { - try { - TableQuery.from(testSuiteTableName, TableServiceEntity.class).take(0); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "Take count must be positive and greater than 0."); - } - - try { - TableQuery.from(testSuiteTableName, TableServiceEntity.class).take(-1); - } - catch (IllegalArgumentException ex) { - Assert.assertEquals(ex.getMessage(), "Take count must be positive and greater than 0."); - } - } - - @Test - public void tableInvalidQuery() throws StorageException, IOException, URISyntaxException { - TableQuery query = TableQuery.from(testSuiteTableName, class1.class).where( - String.format("(PartitionKey ) and (RowKey ge '%s')", "javatables_batch_1", "000050")); - try { - tClient.executeSegmented(query, null); - fail(); - } - catch (TableServiceException ex) { - Assert.assertEquals(ex.getMessage(), "Bad Request"); - Assert.assertTrue(ex.getExtendedErrorInformation().getErrorMessage() - .startsWith("One of the request inputs is not valid.")); - Assert.assertEquals(ex.getExtendedErrorInformation().getErrorCode(), "InvalidInput"); - } - } - - @Test - public void testQueryOnSupportedTypes() throws StorageException, InterruptedException { - // Setup - TableBatchOperation batch = new TableBatchOperation(); - String pk = UUID.randomUUID().toString(); - - ComplexEntity middleRef = null; - - for (int j = 0; j < 100; j++) { - ComplexEntity ent = new ComplexEntity(); - ent.setPartitionKey(pk); - ent.setRowKey(String.format("%04d", j)); - ent.setBinary(new Byte[] { 0x01, 0x02, (byte) j }); - ent.setBinaryPrimitive(new byte[] { 0x01, 0x02, (byte) j }); - ent.setBool(j % 2 == 0 ? true : false); - ent.setBoolPrimitive(j % 2 == 0 ? true : false); - ent.setDateTime(new Date()); - ent.setDouble(j + ((double) j) / 100); - ent.setDoublePrimitive(j + ((double) j) / 100); - ent.setInt32(j); - ent.setInt64((long) j); - ent.setIntegerPrimitive(j); - ent.setLongPrimitive(j); - ent.setGuid(UUID.randomUUID()); - ent.setString(String.format("%04d", j)); - - // Add delay to make times unique - Thread.sleep(100); - batch.insert(ent); - if (j == 50) { - middleRef = ent; - } - } - - tClient.execute(testSuiteTableName, batch); - - try { - // 1. Filter on String - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("String", QueryComparisons.GREATER_THAN_OR_EQUAL, "0050"), 50); - - // 2. Filter on UUID - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("Guid", QueryComparisons.EQUAL, middleRef.getGuid()), 1); - - // 3. Filter on Long - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("Int64", QueryComparisons.GREATER_THAN_OR_EQUAL, - middleRef.getInt64()), 50); - - executeQueryAndAssertResults(TableQuery.generateFilterCondition("LongPrimitive", - QueryComparisons.GREATER_THAN_OR_EQUAL, middleRef.getInt64()), 50); - - // 4. Filter on Double - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("Double", QueryComparisons.GREATER_THAN_OR_EQUAL, - middleRef.getDouble()), 50); - - executeQueryAndAssertResults(TableQuery.generateFilterCondition("DoublePrimitive", - QueryComparisons.GREATER_THAN_OR_EQUAL, middleRef.getDouble()), 50); - - // 5. Filter on Integer - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("Int32", QueryComparisons.GREATER_THAN_OR_EQUAL, - middleRef.getInt32()), 50); - - executeQueryAndAssertResults(TableQuery.generateFilterCondition("IntegerPrimitive", - QueryComparisons.GREATER_THAN_OR_EQUAL, middleRef.getInt32()), 50); - - // 6. Filter on Date - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("DateTime", QueryComparisons.GREATER_THAN_OR_EQUAL, - middleRef.getDateTime()), 50); - - // 7. Filter on Boolean - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("Bool", QueryComparisons.EQUAL, middleRef.getBool()), 50); - - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("BoolPrimitive", QueryComparisons.EQUAL, middleRef.getBool()), - 50); - - // 8. Filter on Binary - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("Binary", QueryComparisons.EQUAL, middleRef.getBinary()), 1); - - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("BinaryPrimitive", QueryComparisons.EQUAL, - middleRef.getBinaryPrimitive()), 1); - - // 9. Filter on Binary GTE - executeQueryAndAssertResults( - TableQuery.generateFilterCondition("Binary", QueryComparisons.GREATER_THAN_OR_EQUAL, - middleRef.getBinary()), 50); - - executeQueryAndAssertResults(TableQuery.generateFilterCondition("BinaryPrimitive", - QueryComparisons.GREATER_THAN_OR_EQUAL, middleRef.getBinaryPrimitive()), 50); - - // 10. Complex Filter on Binary GTE - executeQueryAndAssertResults(TableQuery.combineFilters( - TableQuery.generateFilterCondition(TableConstants.PARTITION_KEY, QueryComparisons.EQUAL, - middleRef.getPartitionKey()), - TableQuery.Operators.AND, - TableQuery.generateFilterCondition("Binary", QueryComparisons.GREATER_THAN_OR_EQUAL, - middleRef.getBinary())), 50); - - executeQueryAndAssertResults(TableQuery.generateFilterCondition("BinaryPrimitive", - QueryComparisons.GREATER_THAN_OR_EQUAL, middleRef.getBinaryPrimitive()), 50); - - } - finally { - // cleanup - TableBatchOperation delBatch = new TableBatchOperation(); - TableQuery query = TableQuery.from(testSuiteTableName, ComplexEntity.class).where( - String.format("PartitionKey eq '%s'", pk)); - - for (ComplexEntity e : tClient.execute(query)) { - delBatch.delete(e); - } - - tClient.execute(testSuiteTableName, delBatch); - } - } - - private void executeQueryAndAssertResults(String filter, int expectedResults) { - int count = 0; - TableQuery query = TableQuery.from(testSuiteTableName, ComplexEntity.class).where(filter); - for (@SuppressWarnings("unused") - ComplexEntity e : tClient.execute(query)) { - count++; - } - - Assert.assertEquals(expectedResults, count); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableSerializerTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableSerializerTests.java deleted file mode 100644 index 9370879504af6..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableSerializerTests.java +++ /dev/null @@ -1,288 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.storage.StorageException; - -/** - * Table Serializer Tests - */ -public class TableSerializerTests extends TableTestBase { - @Test - public void testComplexEntityInsert() throws IOException, URISyntaxException, StorageException { - ComplexEntity ref = new ComplexEntity(); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - ref.populateEntity(); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ComplexEntity retrievedComplexRef = res.getResultAsType(); - ref.assertEquality(retrievedComplexRef); - } - - @Test - public void testIgnoreAnnotation() throws IOException, URISyntaxException, StorageException { - // Ignore On Getter - IgnoreOnGetter ignoreGetter = new IgnoreOnGetter(); - ignoreGetter.setPartitionKey("jxscl_odata"); - ignoreGetter.setRowKey(UUID.randomUUID().toString()); - ignoreGetter.setIgnoreString("ignore data"); - - tClient.execute(testSuiteTableName, TableOperation.insert(ignoreGetter)); - - TableResult res = tClient - .execute(testSuiteTableName, TableOperation.retrieve(ignoreGetter.getPartitionKey(), - ignoreGetter.getRowKey(), IgnoreOnGetter.class)); - - IgnoreOnGetter retrievedIgnoreG = res.getResultAsType(); - Assert.assertEquals(retrievedIgnoreG.getIgnoreString(), null); - - // Ignore On Setter - IgnoreOnSetter ignoreSetter = new IgnoreOnSetter(); - ignoreSetter.setPartitionKey("jxscl_odata"); - ignoreSetter.setRowKey(UUID.randomUUID().toString()); - ignoreSetter.setIgnoreString("ignore data"); - - tClient.execute(testSuiteTableName, TableOperation.insert(ignoreSetter)); - - res = tClient - .execute(testSuiteTableName, TableOperation.retrieve(ignoreSetter.getPartitionKey(), - ignoreSetter.getRowKey(), IgnoreOnSetter.class)); - - IgnoreOnSetter retrievedIgnoreS = res.getResultAsType(); - Assert.assertEquals(retrievedIgnoreS.getIgnoreString(), null); - - // Ignore On Getter AndSetter - IgnoreOnGetterAndSetter ignoreGetterSetter = new IgnoreOnGetterAndSetter(); - ignoreGetterSetter.setPartitionKey("jxscl_odata"); - ignoreGetterSetter.setRowKey(UUID.randomUUID().toString()); - ignoreGetterSetter.setIgnoreString("ignore data"); - - tClient.execute(testSuiteTableName, TableOperation.insert(ignoreGetterSetter)); - - res = tClient.execute(testSuiteTableName, TableOperation.retrieve(ignoreGetterSetter.getPartitionKey(), - ignoreGetterSetter.getRowKey(), IgnoreOnGetterAndSetter.class)); - - IgnoreOnGetterAndSetter retrievedIgnoreGS = res.getResultAsType(); - Assert.assertEquals(retrievedIgnoreGS.getIgnoreString(), null); - } - - @Test - public void testNulls() throws IOException, URISyntaxException, StorageException { - ComplexEntity ref = new ComplexEntity(); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - ref.populateEntity(); - - // Binary object - ref.setBinary(null); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - ref = res.getResultAsType(); - - Assert.assertNull("Binary should be null", ref.getBinary()); - - // Bool - ref.setBool(null); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ref = res.getResultAsType(); - - Assert.assertNull("Bool should be null", ref.getBool()); - - // Date - ref.setDateTime(null); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ref = res.getResultAsType(); - - Assert.assertNull("Date should be null", ref.getDateTime()); - - // Double - ref.setDouble(null); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ref = res.getResultAsType(); - - Assert.assertNull("Double should be null", ref.getDouble()); - - // UUID - ref.setGuid(null); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ref = res.getResultAsType(); - - Assert.assertNull("UUID should be null", ref.getGuid()); - - // Int32 - ref.setInt32(null); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ref = res.getResultAsType(); - - Assert.assertNull("Int32 should be null", ref.getInt32()); - - // Int64 - ref.setInt64(null); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ref = res.getResultAsType(); - - Assert.assertNull("Int64 should be null", ref.getInt64()); - - // String - ref.setString(null); - tClient.execute(testSuiteTableName, TableOperation.replace(ref)); - - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ref = res.getResultAsType(); - - Assert.assertNull("String should be null", ref.getString()); - } - - @Test - public void testStoreAsAnnotation() throws IOException, URISyntaxException, StorageException { - StoreAsEntity ref = new StoreAsEntity(); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - ref.setStoreAsString("StoreAsOverride Data"); - ref.populateEntity(); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), StoreAsEntity.class)); - - StoreAsEntity retrievedStoreAsRef = res.getResultAsType(); - Assert.assertEquals(retrievedStoreAsRef.getStoreAsString(), ref.getStoreAsString()); - - // Same query with a class without the storeAs annotation - res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), ComplexEntity.class)); - - ComplexEntity retrievedComplexRef = res.getResultAsType(); - Assert.assertEquals(retrievedComplexRef.getString(), ref.getStoreAsString()); - - tClient.execute(testSuiteTableName, TableOperation.delete(retrievedComplexRef)); - } - - @Test - public void testInvalidStoreAsAnnotation() throws IOException, URISyntaxException, StorageException { - InvalidStoreAsEntity ref = new InvalidStoreAsEntity(); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - ref.setStoreAsString("StoreAsOverride Data"); - ref.populateEntity(); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), InvalidStoreAsEntity.class)); - - InvalidStoreAsEntity retrievedStoreAsRef = res.getResultAsType(); - Assert.assertEquals(retrievedStoreAsRef.getStoreAsString(), null); - } - - @Test - public void whitespaceTest() throws StorageException { - class1 ref = new class1(); - - ref.setA("B "); - ref.setB(" A "); - ref.setC(" "); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), class1.class)); - - Assert.assertEquals(((class1) res.getResult()).getA(), ref.getA()); - } - - @Test - public void whitespaceOnEmptyKeysTest() throws StorageException { - class1 ref = new class1(); - - ref.setA("B "); - ref.setB(" A "); - ref.setC(" "); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey(""); - ref.setRowKey(""); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), class1.class)); - - Assert.assertEquals(((class1) res.getResult()).getA(), ref.getA()); - } - - @Test - public void newLineTest() throws StorageException { - class1 ref = new class1(); - - ref.setA("B "); - ref.setB(" A "); - ref.setC("\r\n"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey("jxscl_odata"); - ref.setRowKey(UUID.randomUUID().toString()); - - tClient.execute(testSuiteTableName, TableOperation.insert(ref)); - - TableResult res = tClient.execute(testSuiteTableName, - TableOperation.retrieve(ref.getPartitionKey(), ref.getRowKey(), class1.class)); - - Assert.assertEquals(((class1) res.getResult()).getA(), ref.getA()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableTestBase.java deleted file mode 100644 index 32f9a19837e64..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/client/TableTestBase.java +++ /dev/null @@ -1,614 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.client; - -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.util.Arrays; -import java.util.Date; -import java.util.UUID; - -import junit.framework.Assert; - -import org.junit.AfterClass; -import org.junit.BeforeClass; - -import com.microsoft.windowsazure.services.blob.client.CloudBlobClient; -import com.microsoft.windowsazure.services.core.storage.AuthenticationScheme; -import com.microsoft.windowsazure.services.core.storage.CloudStorageAccount; -import com.microsoft.windowsazure.services.core.storage.StorageException; -import com.microsoft.windowsazure.services.queue.client.CloudQueueClient; - -/** - * Table Test Base - */ -public class TableTestBase { - public static boolean USE_DEV_FABRIC = false; - public static final String CLOUD_ACCOUNT_HTTP = "DefaultEndpointsProtocol=http;AccountName=[ACCOUNT NAME];AccountKey=[ACCOUNT KEY]"; - public static final String CLOUD_ACCOUNT_HTTPS = "DefaultEndpointsProtocol=https;AccountName=[ACCOUNT NAME];AccountKey=[ACCOUNT KEY]"; - - public static class class1 extends TableServiceEntity { - public String A; - - public String B; - - public String C; - - public byte[] D; - - public class1() { - // empty ctor - } - - public synchronized String getA() { - return this.A; - } - - public synchronized String getB() { - return this.B; - } - - public synchronized String getC() { - return this.C; - } - - public synchronized byte[] getD() { - return this.D; - } - - public synchronized void setA(final String a) { - this.A = a; - } - - public synchronized void setB(final String b) { - this.B = b; - } - - public synchronized void setC(final String c) { - this.C = c; - } - - public synchronized void setD(final byte[] d) { - this.D = d; - } - } - - public class class2 extends TableServiceEntity { - private String L; - private String M; - - private String N; - - private String O; - - /** - * @return the l - */ - public String getL() { - return this.L; - } - - /** - * @return the m - */ - public String getM() { - return this.M; - } - - /** - * @return the n - */ - public String getN() { - return this.N; - } - - /** - * @return the o - */ - public String getO() { - return this.O; - } - - /** - * @param l - * the l to set - */ - public void setL(String l) { - this.L = l; - } - - /** - * @param m - * the m to set - */ - public void setM(String m) { - this.M = m; - } - - /** - * @param n - * the n to set - */ - public void setN(String n) { - this.N = n; - } - - /** - * @param o - * the o to set - */ - public void setO(String o) { - this.O = o; - } - } - - public static class ComplexEntity extends TableServiceEntity { - private Date dateTime = null; - private Boolean Bool = null; - private boolean BoolPrimitive = false; - private Byte[] Binary = null; - private byte[] binaryPrimitive = null; - private double DoublePrimitive = -1; - private Double Double = null; - private UUID Guid = null; - private int IntegerPrimitive = -1; - private Integer Int32 = null; - private long LongPrimitive = -1L; - private Long Int64 = null; - private String String = null; - - public ComplexEntity() { - // Empty Ctor - } - - public void assertEquality(ComplexEntity other) { - Assert.assertEquals(this.getPartitionKey(), other.getPartitionKey()); - Assert.assertEquals(this.getRowKey(), other.getRowKey()); - - Assert.assertEquals(this.getDateTime().toString(), other.getDateTime().toString()); - - Assert.assertEquals(this.getGuid(), other.getGuid()); - Assert.assertEquals(this.getString(), other.getString()); - - Assert.assertEquals(this.getDouble(), other.getDouble(), 1.0e-10); - Assert.assertEquals(this.getDoublePrimitive(), other.getDoublePrimitive(), 1.0e-10); - Assert.assertEquals(this.getInt32(), other.getInt32()); - Assert.assertEquals(this.getIntegerPrimitive(), other.getIntegerPrimitive()); - Assert.assertEquals(this.getBool(), other.getBool()); - Assert.assertEquals(this.getBoolPrimitive(), other.getBoolPrimitive()); - Assert.assertEquals(this.getInt64(), other.getInt64()); - Assert.assertEquals(this.getIntegerPrimitive(), other.getIntegerPrimitive()); - Assert.assertTrue(Arrays.equals(this.getBinary(), other.getBinary())); - Assert.assertTrue(Arrays.equals(this.getBinaryPrimitive(), other.getBinaryPrimitive())); - } - - protected void assertDateApproxEquals(Date expected, Date actual, int deltaInMs) { - if (expected == null || actual == null) { - Assert.assertEquals(expected, actual); - } - else { - long diffInMilliseconds = Math.abs(expected.getTime() - actual.getTime()); - if (diffInMilliseconds > deltaInMs) { - Assert.assertEquals(expected, actual); - } - } - } - - /** - * @return the binary - */ - public Byte[] getBinary() { - return this.Binary; - } - - /** - * @return the binaryPrimitive - */ - public byte[] getBinaryPrimitive() { - return this.binaryPrimitive; - } - - /** - * @return the bool - */ - public Boolean getBool() { - return this.Bool; - } - - /** - * @return the bool - */ - public boolean getBoolPrimitive() { - return this.BoolPrimitive; - } - - /** - * @return the dateTime - */ - public Date getDateTime() { - return this.dateTime; - } - - /** - * @return the double - */ - public Double getDouble() { - return this.Double; - } - - /** - * @return the doublePrimitive - */ - public double getDoublePrimitive() { - return this.DoublePrimitive; - } - - /** - * @return the guid - */ - public UUID getGuid() { - return this.Guid; - } - - /** - * @return the int32 - */ - public Integer getInt32() { - return this.Int32; - } - - /** - * @return the int64 - */ - public Long getInt64() { - return this.Int64; - } - - /** - * @return the integerPrimitive - */ - public int getIntegerPrimitive() { - return this.IntegerPrimitive; - } - - /** - * @return the longPrimitive - */ - public long getLongPrimitive() { - return this.LongPrimitive; - } - - /** - * @return the string - */ - public String getString() { - return this.String; - } - - public void populateEntity() { - this.setBinary(new Byte[] { 1, 2, 3, 4 }); - this.setBinaryPrimitive(new byte[] { 1, 2, 3, 4 }); - this.setBool(true); - this.setBoolPrimitive(true); - this.setDateTime(new Date()); - this.setDouble(2342.2342); - this.setDoublePrimitive(2349879.2342); - this.setInt32(2342); - this.setInt64((long) 87987987); - this.setIntegerPrimitive(2342); - this.setLongPrimitive(87987987); - this.setGuid(UUID.randomUUID()); - this.setString("foo"); - } - - /** - * @param binary - * the binary to set - */ - public void setBinary(final Byte[] binary) { - this.Binary = binary; - } - - /** - * @param binaryPrimitive - * the binaryPrimitive to set - */ - public void setBinaryPrimitive(byte[] binaryPrimitive) { - this.binaryPrimitive = binaryPrimitive; - } - - /** - * @param bool - * the bool to set - */ - public void setBool(final Boolean bool) { - this.Bool = bool; - } - - /** - * @param boolPrimitive - * the boolPrimitive to set - */ - public void setBoolPrimitive(boolean boolPrimitive) { - this.BoolPrimitive = boolPrimitive; - } - - /** - * @param dateTime - * the dateTime to set - */ - public void setDateTime(final Date dateTime) { - this.dateTime = dateTime; - } - - /** - * @param d - * the double to set - */ - public void setDouble(final Double d) { - this.Double = d; - } - - /** - * @param doublePrimitive - * the doublePrimitive to set - */ - public void setDoublePrimitive(double doublePrimitive) { - this.DoublePrimitive = doublePrimitive; - } - - /** - * @param guid - * the guid to set - */ - public void setGuid(final UUID guid) { - this.Guid = guid; - } - - /** - * @param int32 - * the int32 to set - */ - public void setInt32(final Integer int32) { - this.Int32 = int32; - } - - /** - * @param int64 - * the int64 to set - */ - public void setInt64(final Long int64) { - this.Int64 = int64; - } - - /** - * @param integerPrimitive - * the integerPrimitive to set - */ - public void setIntegerPrimitive(int integerPrimitive) { - this.IntegerPrimitive = integerPrimitive; - } - - /** - * @param longPrimitive - * the longPrimitive to set - */ - public void setLongPrimitive(long longPrimitive) { - this.LongPrimitive = longPrimitive; - } - - /** - * @param string - * the string to set - */ - public void setString(final String string) { - this.String = string; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(java.lang.String.format("%s:%s\n", "PK", this.getPartitionKey())); - builder.append(java.lang.String.format("%s:%s\n", "RK", this.getRowKey())); - builder.append(java.lang.String.format("%s:%s\n", "Timestamp", this.getTimestamp())); - builder.append(java.lang.String.format("%s:%s\n", "etag", this.getEtag())); - - builder.append(java.lang.String.format("%s:%s\n", "DateTime", this.getDateTime())); - builder.append(java.lang.String.format("%s:%s\n", "Bool", this.getBool())); - builder.append(java.lang.String.format("%s:%s\n", "Binary", this.getBinary())); - builder.append(java.lang.String.format("%s:%s\n", "Double", this.getDouble())); - builder.append(java.lang.String.format("%s:%s\n", "Guid", this.getGuid())); - builder.append(java.lang.String.format("%s:%s\n", "Int32", this.getInt32())); - builder.append(java.lang.String.format("%s:%s\n", "Int64", this.getInt64())); - builder.append(java.lang.String.format("%s:%s\n", "String", this.getString())); - - return builder.toString(); - } - } - - public static class IgnoreOnGetter extends class1 { - private String tString = null; - - /** - * @return the string - */ - @Ignore - public String getIgnoreString() { - return this.tString; - } - - /** - * @param string - * the string to set - */ - - public void setIgnoreString(final String string) { - this.tString = string; - } - } - - public static class IgnoreOnGetterAndSetter extends class1 { - private String tString = null; - - /** - * @return the string - */ - @Ignore - public String getIgnoreString() { - return this.tString; - } - - /** - * @param string - * the string to set - */ - @Ignore - public void setIgnoreString(final String string) { - this.tString = string; - } - } - - public static class IgnoreOnSetter extends class1 { - private String tString = null; - - /** - * @return the string - */ - public String getIgnoreString() { - return this.tString; - } - - /** - * @param string - * the string to set - */ - @Ignore - public void setIgnoreString(final String string) { - this.tString = string; - } - } - - public static class StoreAsEntity extends ComplexEntity { - private String storeAsString = null; - - /** - * @return the string - */ - @StoreAs(name = "String") - public String getStoreAsString() { - return this.storeAsString; - } - - /** - * @param string - * the string to set - */ - @StoreAs(name = "String") - public void setStoreAsString(final String string) { - this.storeAsString = string; - } - } - - public static class InvalidStoreAsEntity extends ComplexEntity { - private String storeAsString = null; - - /** - * @return the string - */ - @StoreAs(name = "PartitionKey") - public String getStoreAsString() { - return this.storeAsString; - } - - /** - * @param string - * the string to set - */ - @StoreAs(name = "PartitionKey") - public void setStoreAsString(final String string) { - this.storeAsString = string; - } - } - - public static class TableEnt extends TableServiceEntity { - String TableName; - - /** - * @return the tableName - */ - public String getTableName() { - return this.TableName; - } - - /** - * @param tableName - * the tableName to set - */ - public void setTableName(String tableName) { - this.TableName = tableName; - } - } - - protected static CloudStorageAccount httpAcc; - protected static CloudBlobClient bClient; - protected static CloudQueueClient qClient; - protected static CloudTableClient tClient; - protected static String testSuiteTableName = generateRandomTableName(); - - public static class1 generateRandomEnitity(String pk) { - class1 ref = new class1(); - - ref.setA("foo_A"); - ref.setB("foo_B"); - ref.setC("foo_C"); - ref.setD(new byte[] { 0, 1, 2 }); - ref.setPartitionKey(pk); - ref.setRowKey(UUID.randomUUID().toString()); - return ref; - } - - @BeforeClass - public static void setup() throws URISyntaxException, StorageException, InvalidKeyException { - if (USE_DEV_FABRIC) { - httpAcc = CloudStorageAccount.getDevelopmentStorageAccount(); - } - else { - String cloudAccount = CLOUD_ACCOUNT_HTTP; - cloudAccount = cloudAccount.replace("[ACCOUNT NAME]", System.getenv("table.accountName")); - cloudAccount = cloudAccount.replace("[ACCOUNT KEY]", System.getenv("table.accountKey")); - - httpAcc = CloudStorageAccount.parse(cloudAccount); - } - - bClient = httpAcc.createCloudBlobClient(); - tClient = httpAcc.createCloudTableClient(); - qClient = httpAcc.createCloudQueueClient(); - testSuiteTableName = generateRandomTableName(); - tClient.setAuthenticationScheme(AuthenticationScheme.SHAREDKEYFULL); - CloudTable table = tClient.getTableReference(testSuiteTableName); - table.create(); - } - - @AfterClass - public static void teardown() throws StorageException, URISyntaxException { - CloudTable table = tClient.getTableReference(testSuiteTableName); - table.delete(); - } - - protected static String generateRandomTableName() { - String tableName = "table" + UUID.randomUUID().toString(); - return tableName.replace("-", ""); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/implementation/AtomReaderWriterTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/implementation/AtomReaderWriterTests.java deleted file mode 100644 index 03e5e11400522..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/implementation/AtomReaderWriterTests.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.List; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ISO8601DateConverter; -import com.microsoft.windowsazure.services.core.utils.DefaultDateFactory; -import com.microsoft.windowsazure.services.table.IntegrationTestBase; -import com.microsoft.windowsazure.services.table.models.TableEntry; - -public class AtomReaderWriterTests extends IntegrationTestBase { - @Test - public void parseTableEntriesWorks() throws Exception { - // Arrange - AtomReaderWriter atom = new AtomReaderWriter(new DefaultXMLStreamFactory(), new DefaultDateFactory(), - new ISO8601DateConverter(), new DefaultEdmValueConverter(new ISO8601DateConverter())); - String feed = "\r\n" - + "\r\n" - + " Tables\r\n" - + " http://rpaquaytest.table.core.windows.net/Tables\r\n" - + " 2012-01-10T21:23:30Z\r\n" - + " \r\n" - + " \r\n" - + " http://rpaquaytest.table.core.windows.net/Tables('sdktest1')\r\n" - + " \r\n" - + " 2012-01-10T21:23:30Z\r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " sdktest1\r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " http://rpaquaytest.table.core.windows.net/Tables('sdktest10')\r\n" - + " \r\n" - + " 2012-01-10T21:23:30Z\r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" + " \r\n" - + " sdktest10\r\n" + " \r\n" - + " \r\n" + " \r\n" + "\r\n"; - InputStream stream = new ByteArrayInputStream(feed.getBytes("UTF-8")); - - // Act - List entries = atom.parseTableEntries(stream); - - // Assert - assertNotNull(entries); - assertEquals(2, entries.size()); - assertEquals("sdktest1", entries.get(0).getName()); - assertEquals("sdktest10", entries.get(1).getName()); - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/implementation/MimeMultipartTests.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/implementation/MimeMultipartTests.java deleted file mode 100644 index 13f20b528b5b0..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/table/implementation/MimeMultipartTests.java +++ /dev/null @@ -1,336 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.services.table.implementation; - -import static org.junit.Assert.*; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.StringReader; - -import javax.activation.DataSource; -import javax.mail.BodyPart; -import javax.mail.MessagingException; -import javax.mail.MultipartDataSource; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMultipart; -import javax.mail.util.ByteArrayDataSource; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.table.IntegrationTestBase; - -public class MimeMultipartTests extends IntegrationTestBase { - @Test - public void parseMimeWorks() throws Exception { - //@formatter:off - String s = "--batchresponse_dc0fea8c-ed83-4aa8-ac9b-bf56a2d46dfb \r\n" - + "Content-Type: multipart/mixed; boundary=changesetresponse_8a28b620-b4bb-458c-a177-0959fb14c977\r\n" - + "\r\n" - + "--changesetresponse_8a28b620-b4bb-458c-a177-0959fb14c977\r\n" - + "Content-Type: application/http\r\n" - + "Content-Transfer-Encoding: binary\r\n" - + "\r\n" - + "HTTP/1.1 201 Created\r\n" - + "Content-ID: 1\r\n" - + "Content-Type: application/atom+xml;charset=utf-8\r\n" - + "Cache-Control: no-cache\r\n" - + "ETag: W/\"datetime'2009-04-30T20%3A44%3A09.5789464Z'\"\r\n" - + "Location: http://myaccount.tables.core.windows.net/Blogs(PartitionKey='Channel_19',RowKey='1')\r\n" - + "DataServiceVersion: 1.0;\r\n" - + "\r\n" - + "\r\n" - + "\r\n" - + " http://myaccount.tables.core.windows.net/Blogs(PartitionKey='Channel_19',RowKey='1')\r\n" - + " \r\n" - + " 2009-04-30T20:44:09Z\r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " Channel_19\r\n" - + " 1\r\n" - + " 2009-04-30T20:44:09.5789464Z\r\n" - + " .Net...\r\n" - + " 9\r\n" - + " \r\n" - + " \r\n" - + "\r\n" - + "\r\n" - + "--changesetresponse_8a28b620-b4bb-458c-a177-0959fb14c977\r\n" - + "Content-Type: application/http\r\n" - + "Content-Transfer-Encoding: binary\r\n" - + "\r\n" - + "HTTP/1.1 201 Created\r\n" - + "Content-ID: 2\r\n" - + "Content-Type: application/atom+xml;charset=utf-8\r\n" - + "Cache-Control: no-cache\r\n" - + "ETag: W/\"datetime'2009-04-30T20%3A44%3A09.5789464Z'\"\r\n" - + "Location: http://myaccount.tables.core.windows.net/Blogs(PartitionKey='Channel_19',RowKey='2')\r\n" - + "DataServiceVersion: 1.0;\r\n" - + "\r\n" - + "\r\n" - + "\r\n" - + " http://myaccount.tables.core.windows.net/Blogs(PartitionKey='Channel_19',RowKey='2')\r\n" - + " \r\n" - + " 2009-04-30T20:44:09Z\r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " \r\n" - + " Channel_19\r\n" - + " 2\r\n" - + " 2009-04-30T20:44:09.5789464Z\r\n" - + " Azure...\r\n" - + " 9\r\n" - + " \r\n" - + " \r\n" - + "\r\n" - + "\r\n" - + "--changesetresponse_8a28b620-b4bb-458c-a177-0959fb14c977\r\n" - + "Content-Type: application/http\r\n" - + "Content-Transfer-Encoding: binary\r\n" - + "\r\n" - + "HTTP/1.1 204 No Content\r\n" - + "Content-ID: 3\r\n" - + "Cache-Control: no-cache\r\n" - + "ETag: W/\"datetime'2009-04-30T20%3A44%3A10.0019041Z'\"\r\n" - + "DataServiceVersion: 1.0;\r\n" - + "\r\n" - + "--changesetresponse_8a28b620-b4bb-458c-a177-0959fb14c977\r\n" - + "Content-Type: application/http\r\n" - + "Content-Transfer-Encoding: binary\r\n" - + "\r\n" - + "HTTP/1.1 204 No Content\r\n" - + "Content-ID: 4\r\n" - + "Cache-Control: no-cache\r\n" - + "DataServiceVersion: 1.0;\r\n" - + "\r\n" - + "--changesetresponse_8a28b620-b4bb-458c-a177-0959fb14c977--\r\n" - + "--batchresponse_4c637ba4-b2f8-40f8-8856-c2d10d163a83--\r\n"; - //@formatter:on - - DataSource ds = new ByteArrayDataSource(s, - "multipart/mixed; boundary=batchresponse_dc0fea8c-ed83-4aa8-ac9b-bf56a2d46dfb"); - MimeMultipart m = new MimeMultipart(ds); - - assertEquals(1, m.getCount()); - assertTrue(m.getBodyPart(0) instanceof MimeBodyPart); - - MimeBodyPart part = (MimeBodyPart) m.getBodyPart(0); - String contentType = part.getHeader("Content-Type", ":"); - assertEquals("multipart/mixed; boundary=changesetresponse_8a28b620-b4bb-458c-a177-0959fb14c977", contentType); - - DataSource ds2 = new ByteArrayDataSource(part.getInputStream(), contentType); - MimeMultipart m2 = new MimeMultipart(ds2); - - assertEquals(4, m2.getCount()); - } - - @Test - public void buildMimeWorks() throws Exception { - //@formatter:off - String changeset1 = "POST http://myaccount.tables.core.windows.net/Blogs HTTP/1.1\r\n" + - "Content-ID: 1\r\n" + - "Content-Type: application/atom+xml;type=entry\r\n" + - "Content-Length: ###\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - " \r\n" + - " <updated>2009-04-30T20:45:13.7155321Z</updated>\r\n" + - " <author>\r\n" + - " <name />\r\n" + - " </author>\r\n" + - " <id />\r\n" + - " <content type=\"application/xml\">\r\n" + - " <m:properties>\r\n" + - " <d:PartitionKey>Channel_19</d:PartitionKey>\r\n" + - " <d:RowKey>1</d:RowKey>\r\n" + - " <d:Timestamp m:type=\"Edm.DateTime\">0001-01-01T00:00:00</d:Timestamp>\r\n" + - " <d:Rating m:type=\"Edm.Int32\">9</d:Rating>\r\n" + - " <d:Text>.NET...</d:Title>\r\n" + - " </m:properties>\r\n" + - " </content>\r\n" + - "</entry>"; - //@formatter:on - - // - // Build inner list of change sets - // - - MimeMultipart changeSets = new MimeMultipart(new SetBoundaryMultipartDataSource( - "changeset_8a28b620-b4bb-458c-a177-0959fb14c977")); - - MimeBodyPart cs1 = new MimeBodyPart(); - cs1.setContent(changeset1, "application/http"); - changeSets.addBodyPart(cs1); - - MimeBodyPart cs2 = new MimeBodyPart(); - cs2.setContent(changeset1, "application/http"); - changeSets.addBodyPart(cs2); - - // - // Build outer "batch" body part - // - MimeBodyPart batchbody = new MimeBodyPart(); - batchbody.setContent(changeSets); - - // - // Build outer "batch" multipart - // - MimeMultipart batch = new MimeMultipart(new SetBoundaryMultipartDataSource( - "batch_a1e9d677-b28b-435e-a89e-87e6a768a431")); - batch.addBodyPart(batchbody); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - batch.writeTo(stream); - - String result = stream.toString("UTF-8"); - //@formatter:off - String expectedResult = - "--batch_a1e9d677-b28b-435e-a89e-87e6a768a431\r\n" + - "\r\n" + - "--changeset_8a28b620-b4bb-458c-a177-0959fb14c977\r\n" + - "\r\n" + - "POST http://myaccount.tables.core.windows.net/Blogs HTTP/1.1\r\n" + - "Content-ID: 1\r\n" + - "Content-Type: application/atom+xml;type=entry\r\n" + - "Content-Length: ###\r\n" + - "\r\n" + - "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n" + - "<entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" xmlns=\"http://www.w3.org/2005/Atom\">\r\n" + - " <title />\r\n" + - " <updated>2009-04-30T20:45:13.7155321Z</updated>\r\n" + - " <author>\r\n" + - " <name />\r\n" + - " </author>\r\n" + - " <id />\r\n" + - " <content type=\"application/xml\">\r\n" + - " <m:properties>\r\n" + - " <d:PartitionKey>Channel_19</d:PartitionKey>\r\n" + - " <d:RowKey>1</d:RowKey>\r\n" + - " <d:Timestamp m:type=\"Edm.DateTime\">0001-01-01T00:00:00</d:Timestamp>\r\n" + - " <d:Rating m:type=\"Edm.Int32\">9</d:Rating>\r\n" + - " <d:Text>.NET...</d:Title>\r\n" + - " </m:properties>\r\n" + - " </content>\r\n" + - "</entry>\r\n" + - "--changeset_8a28b620-b4bb-458c-a177-0959fb14c977\r\n" + - "\r\n" + - "POST http://myaccount.tables.core.windows.net/Blogs HTTP/1.1\r\n" + - "Content-ID: 1\r\n" + - "Content-Type: application/atom+xml;type=entry\r\n" + - "Content-Length: ###\r\n" + - "\r\n" + - "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n" + - "<entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" xmlns=\"http://www.w3.org/2005/Atom\">\r\n" + - " <title />\r\n" + - " <updated>2009-04-30T20:45:13.7155321Z</updated>\r\n" + - " <author>\r\n" + - " <name />\r\n" + - " </author>\r\n" + - " <id />\r\n" + - " <content type=\"application/xml\">\r\n" + - " <m:properties>\r\n" + - " <d:PartitionKey>Channel_19</d:PartitionKey>\r\n" + - " <d:RowKey>1</d:RowKey>\r\n" + - " <d:Timestamp m:type=\"Edm.DateTime\">0001-01-01T00:00:00</d:Timestamp>\r\n" + - " <d:Rating m:type=\"Edm.Int32\">9</d:Rating>\r\n" + - " <d:Text>.NET...</d:Title>\r\n" + - " </m:properties>\r\n" + - " </content>\r\n" + - "</entry>\r\n" + - "--changeset_8a28b620-b4bb-458c-a177-0959fb14c977--\r\n" + - "\r\n" + - "--batch_a1e9d677-b28b-435e-a89e-87e6a768a431--\r\n"; - //@formatter:on - StringReader reader1 = new StringReader(result); - StringReader reader2 = new StringReader(expectedResult); - - for (int i = 0;; i++) { - int ch1 = reader1.read(); - int ch2 = reader2.read(); - if (ch1 == -1) { - assertEquals(-1, ch2); - break; - } - if (ch2 == -1) { - assertEquals(-1, ch1); - break; - } - - if (ch1 != ch2) { - int min1 = Math.max(0, i - 20); - int max1 = Math.min(result.length(), i + 20); - - int min2 = Math.max(0, i - 20); - int max2 = Math.min(expectedResult.length(), i + 20); - - String closeBy1 = result.substring(min1, max1); - String closeBy2 = expectedResult.substring(min2, max2); - - assertEquals("Message content are no equal starting at position " + i, closeBy2, closeBy1); - } - } - } - - private class SetBoundaryMultipartDataSource implements MultipartDataSource { - - private final String boundary; - - public SetBoundaryMultipartDataSource(String boundary) { - this.boundary = boundary; - } - - @Override - public String getContentType() { - return "multipart/mixed; boundary=" + boundary; - } - - @Override - public InputStream getInputStream() throws IOException { - return null; - } - - @Override - public String getName() { - return null; - } - - @Override - public OutputStream getOutputStream() throws IOException { - return null; - } - - @Override - public int getCount() { - return 0; - } - - @Override - public BodyPart getBodyPart(int index) throws MessagingException { - return null; - } - } -} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java b/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java deleted file mode 100644 index 6245cedfce676..0000000000000 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright Microsoft Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.microsoft.windowsazure.utils; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.net.SocketTimeoutException; - -import org.junit.Test; - -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.ServiceTimeoutException; -import com.microsoft.windowsazure.services.core.utils.ServiceExceptionFactory; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; - -public class ServiceExceptionFactoryTest { - @Test - public void serviceNameAndMessageAndCauseAppearInException() { - // Arrange - ClientResponse response = new ClientResponse(404, null, new ByteArrayInputStream(new byte[0]), null); - UniformInterfaceException cause = new UniformInterfaceException(response); - - // Act - ServiceException exception = ServiceExceptionFactory.process("testing", new ServiceException("this is a test", - cause)); - - // Assert - assertNotNull(exception); - assertEquals("testing", exception.getServiceName()); - assertEquals("this is a test", exception.getMessage()); - assertEquals(cause, exception.getCause()); - } - - @Test - public void httpStatusCodeAndReasonPhraseAppearInException() { - // Arrange - ClientResponse response = new ClientResponse(404, null, new ByteArrayInputStream(new byte[0]), null); - UniformInterfaceException cause = new UniformInterfaceException(response); - - // Act - ServiceException exception = ServiceExceptionFactory.process("testing", new ServiceException("this is a test", - cause)); - - // Assert - assertNotNull(exception); - assertEquals(404, exception.getHttpStatusCode()); - assertEquals("Not Found", exception.getHttpReasonPhrase()); - } - - @Test - public void informationWillPassUpIfServiceExceptionIsRootCauseOfClientHandlerExceptions() { - // Arrange - ClientResponse response = new ClientResponse(503, null, new ByteArrayInputStream(new byte[0]), null); - UniformInterfaceException rootCause = new UniformInterfaceException(response); - ServiceException originalDescription = ServiceExceptionFactory.process("underlying", new ServiceException( - rootCause)); - ClientHandlerException wrappingException = new ClientHandlerException(originalDescription); - - // Act - ServiceException exception = ServiceExceptionFactory.process("actual", new ServiceException(wrappingException)); - - // Assert - assertEquals(503, exception.getHttpStatusCode()); - assertEquals("underlying", exception.getServiceName()); - } - - @Test - public void socketTimeoutWillPassUpIfInsideClientHandlerException() { - String expectedMessage = "connect timeout"; - SocketTimeoutException rootCause = new SocketTimeoutException(expectedMessage); - ClientHandlerException wrappingException = new ClientHandlerException(rootCause); - - ServiceException exception = ServiceExceptionFactory - .process("testing", new ServiceException(wrappingException)); - - assertSame(ServiceTimeoutException.class, exception.getClass()); - assertEquals(expectedMessage, exception.getMessage()); - assertEquals("testing", exception.getServiceName()); - } -} diff --git a/microsoft-azure-api/src/test/resources/NewFile.xml b/microsoft-azure-api/src/test/resources/NewFile.xml deleted file mode 100644 index 71989d321de16..0000000000000 --- a/microsoft-azure-api/src/test/resources/NewFile.xml +++ /dev/null @@ -1,4 +0,0 @@ -<entry xmlns="http://www.w3.org/2005/Atom"> -<content type="application/xml"> -<ns2:QueueDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"> -</ns2:QueueDescription></content></entry> diff --git a/parent/pom.xml b/parent/pom.xml new file mode 100644 index 0000000000000..c6ff5f73a05ed --- /dev/null +++ b/parent/pom.xml @@ -0,0 +1,300 @@ +<!-- + Copyright Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.microsoft.windowsazure</groupId> + <version>0.5.0</version> + <artifactId>microsoft-azure-api-bom</artifactId> + </parent> + + <artifactId>microsoft-azure-api-parent</artifactId> + <packaging>pom</packaging> + + <name>Microsoft Azure Client API Parent</name> + <description>API for Microsoft Azure Clients</description> + <url>https://github.com/Azure/azure-sdk-for-java</url> + + <licenses> + <license> + <name>The Apache Software License, Version 2.0</name> + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> + <distribution>repo</distribution> + </license> + </licenses> + + <scm> + <url>scm:git:https://github.com/Azure/azure-sdk-for-java</url> + <connection>scm:git:git://github.com/Azure/azure-sdk-for-java.git</connection> + </scm> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <legal><![CDATA[[INFO] Any downloads listed may be third party software. Microsoft grants you no rights for third party software.]]></legal> + </properties> + + <developers> + <developer> + <id>microsoft</id> + <name>Microsoft</name> + </developer> + </developers> + + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.3.1</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <version>2.2.7</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + <version>1.4.5</version> + </dependency> + <dependency> + <groupId>javax.inject</groupId> + <artifactId>javax.inject</artifactId> + <version>1</version> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-client</artifactId> + <version>1.13</version> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-json</artifactId> + <version>1.13</version> + </dependency> + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.1.1</version> + </dependency> + + <!-- Test dependencies --> + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-all</artifactId> + <version>1.3</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <version>1.9.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcprov-jdk16</artifactId> + <version>1.46</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>info.cukes</groupId> + <artifactId>cucumber-java</artifactId> + <version>1.1.5</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>info.cukes</groupId> + <artifactId>cucumber-junit</artifactId> + <version>1.1.5</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.11</version> + <scope>test</scope> + </dependency> + </dependencies> + </dependencyManagement> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-help-plugin</artifactId> + <version>2.1.1</version> + <executions> + <execution> + <phase>validate</phase> + <goals> + <goal>evaluate</goal> + </goals> + <configuration> + <expression>legal</expression> + </configuration> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <source>1.6</source> + <target>1.6</target> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.8</version> + <configuration> + <excludePackageNames>*.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage</excludePackageNames> + <bottom><![CDATA[<code>/** +<br/>* Copyright Microsoft Corporation +<br/>* +<br/>* Licensed under the Apache License, Version 2.0 (the "License"); +<br/>* you may not use this file except in compliance with the License. +<br/>* You may obtain a copy of the License at +<br/>* http://www.apache.org/licenses/LICENSE-2.0 +<br/>* +<br/>* Unless required by applicable law or agreed to in writing, software +<br/>* distributed under the License is distributed on an "AS IS" BASIS, +<br/>* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +<br/>* See the License for the specific language governing permissions and +<br/>* limitations under the License. +<br/>*/</code>]]></bottom> + </configuration> + </plugin> + + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>findbugs-maven-plugin</artifactId> + <version>2.3.2</version> + <configuration> + <xmlOutput>true</xmlOutput> + <findbugsXmlOutput>true</findbugsXmlOutput> + <findbugsXmlWithMessages>true</findbugsXmlWithMessages> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-checkstyle-plugin</artifactId> + <version>2.11</version> + <executions> + <execution> + <id>validate</id> + <phase>validate</phase> + <configuration> + <configLocation>src/config/checkstyle.xml</configLocation> + <encoding>UTF-8</encoding> + <consoleOutput>true</consoleOutput> + <failsOnError>true</failsOnError> + <failOnViolation>true</failOnViolation> + <linkXRef>false</linkXRef> + </configuration> + <goals> + <goal>check</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + <pluginManagement> + <plugins> + <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-help-plugin</artifactId> + <versionRange>[2.1.1,)</versionRange> + <goals> + <goal>evaluate</goal> + </goals> + </pluginExecutionFilter> + <action> + <ignore></ignore> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-resources-plugin</artifactId> + <version>2.4.3</version> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <version>2.12</version> + <configuration> + <includes> + <include>**/Test*.java</include> + <include>**/*Test.java</include> + <include>**/*Tests.java</include> + <include>**/*TestCase.java</include> + </includes> + </configuration> + </plugin> + </plugins> + </pluginManagement> + </build> + <reporting> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>emma-maven-plugin</artifactId> + <version>1.0-alpha-3</version> + <inherited>true</inherited> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>surefire-report-maven-plugin</artifactId> + <version>2.0-beta-1</version> + <inherited>true</inherited> + </plugin> + </plugins> + </reporting> + <modules> + <module>../core</module> + <module>../core-test</module> + <module>../management</module> + <module>../management-compute</module> + <module>../management-sql</module> + <module>../management-storage</module> + <module>../management-network</module> + <module>../management-websites</module> + <module>../media</module> + <module>../serviceBus</module> + <module>../serviceRuntime</module> + <module>../tracing-util</module> + </modules> +</project> diff --git a/microsoft-azure-api/src/config/checkstyle.xml b/parent/src/config/checkstyle.xml similarity index 82% rename from microsoft-azure-api/src/config/checkstyle.xml rename to parent/src/config/checkstyle.xml index 58a40f4ac43a8..face53f8f4fa1 100644 --- a/microsoft-azure-api/src/config/checkstyle.xml +++ b/parent/src/config/checkstyle.xml @@ -31,6 +31,12 @@ --> <module name="Checker"> + <module name="SuppressionCommentFilter"> + <property name="offCommentFormat" value="CSOFF\: ([\w\|]+)"/> + <property name="onCommentFormat" value="CSON\: ([\w\|]+)"/> + <property name="checkFormat" value="$1"/> + </module> + <!-- If you set the basedir property below, then all reported file names will be relative to the specified directory. See @@ -42,7 +48,7 @@ <!-- Checks that each Java package has a Javadoc file used for commenting. --> <!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage --> <module name="JavadocPackage"> - <property name="allowLegacy" value="true"/> + <property name="allowLegacy" value="true"/> </module> <!-- Checks whether files end with a new line. --> @@ -58,7 +64,9 @@ <!-- See http://checkstyle.sf.net/config_misc.html#Translation --> <module name="Translation"/> - <module name="FileLength"/> + <!-- Removed on 20/01/2014 + Justification: generated code. + <module name="FileLength"/> --> <!-- Following interprets the header file as regular expressions. --> <!-- <module name="RegexpHeader"/> --> @@ -143,7 +151,11 @@ <property name="max" value="160" /> </module> --> - <module name="MethodLength"/> + <!-- Removed on 20/01/2014 + Justification: a lot of the code is generated. + As such, method length is not a true representation + of complexity / etc issues. + <module name="MethodLength"/> --> <module name="ParameterNumber"/> @@ -169,8 +181,11 @@ <!-- Checks for blocks. You know, those {}'s --> <!-- See http://checkstyle.sf.net/config_blocks.html --> <module name="AvoidNestedBlocks"/> - <module name="EmptyBlock"/> - <module name="LeftCurly"/> + <!-- Removed on 12/04/2014: + Justification: 1.x.x candidate. Not necessary for now. + <module name="EmptyBlock"/> + --> + <module name="LeftCurly" /> <module name="NeedBraces"/> <!-- Removed on 11/02/2012: @@ -182,8 +197,12 @@ <!-- Checks for common coding problems --> <!-- See http://checkstyle.sf.net/config_coding.html --> - <module name="AvoidInlineConditionals"/> - <module name="DoubleCheckedLocking"/> <!-- MY FAVOURITE --> + <!-- Removed on 14/1/2014: + Justification: The Azure SDK coding guidelines + are that inline conditionals can actually make the + code more readable. + <module name="AvoidInlineConditionals"/> --> + <module name="EmptyStatement"/> <module name="EqualsHashCode"/> <!-- Removed on 11/02/2012: @@ -195,15 +214,18 @@ <module name="IllegalInstantiation"/> <module name="InnerAssignment"/> - <module name="MagicNumber"> - <!-- Updated on 01/23/2013: --> - <!-- Added ignore list, to keep enums from triggering violations --> - <property name="ignoreNumbers" value="0, 1, 2, 3, 4, 5, 6, 7, 8"/> - </module> + + <!-- Updated on 03/17/2014: --> + <!-- Added ignore. Code is generated so magic numbers are not a largish issue. --> + <!-- <module name="MagicNumber" /> --> <module name="MissingSwitchDefault"/> - <module name="RedundantThrows"/> - <module name="SimplifyBooleanExpression"/> - <module name="SimplifyBooleanReturn"/> + <module name="RedundantThrows"> + <property name="allowUnchecked" value="true"/> + <property name="allowSubclasses" value="true"/> + <property name="suppressLoadErrors" value="true"/> + </module> + <!-- <module name="SimplifyBooleanExpression"/> --> + <!-- <module name="SimplifyBooleanReturn"/> --> <!-- Checks for class design --> <!-- See http://checkstyle.sf.net/config_design.html --> @@ -232,7 +254,10 @@ <module name="FinalParameters"/> --> + <!-- Removed on 12/04/2014: + Justification: TODO comments are fine in a 0.x.x version <module name="TodoComment"/> + --> <module name="UpperEll"/> </module> diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000000000..fc3902d333305 --- /dev/null +++ b/pom.xml @@ -0,0 +1,53 @@ +<!-- + Copyright Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>com.microsoft.windowsazure</groupId> + <artifactId>microsoft-azure-api-bom</artifactId> + <version>0.5.0</version> + <packaging>pom</packaging> + + <name>Microsoft Azure Client API</name> + <description>API for Microsoft Azure Clients</description> + <url>https://github.com/Azure/azure-sdk-for-java</url> + + <licenses> + <license> + <name>The Apache Software License, Version 2.0</name> + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> + <distribution>repo</distribution> + </license> + </licenses> + + <scm> + <url>scm:git:https://github.com/Azure/azure-sdk-for-java</url> + <connection>scm:git:git://github.com/Azure/azure-sdk-for-java.git</connection> + </scm> + + <properties> + <projectVersion>0.5.0</projectVersion> + </properties> + + <developers> + <developer> + <id>microsoft</id> + <name>Microsoft</name> + </developer> + </developers> + <modules> + <module>parent</module> + </modules> +</project> diff --git a/serviceBus/pom.xml b/serviceBus/pom.xml new file mode 100644 index 0000000000000..baa0b74d40f94 --- /dev/null +++ b/serviceBus/pom.xml @@ -0,0 +1,292 @@ +<!-- + Copyright Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.microsoft.windowsazure</groupId> + <artifactId>microsoft-azure-api-parent</artifactId> + <version>0.5.0</version> + <relativePath>../parent/pom.xml</relativePath> + </parent> + + <artifactId>microsoft-azure-api-servicebus</artifactId> + <packaging>jar</packaging> + + <name>Microsoft Azure Service Bus Client API</name> + <description>Microsoft Azure Service Bus SDK Clients</description> + <url>https://github.com/Azure/azure-sdk-for-java</url> + + <licenses> + <license> + <name>The Apache Software License, Version 2.0</name> + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> + <distribution>repo</distribution> + </license> + </licenses> + + <scm> + <url>scm:git:https://github.com/Azure/azure-sdk-for-java</url> + <connection>scm:git:git://github.com/Azure/azure-sdk-for-java.git</connection> + </scm> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <legal><![CDATA[[INFO] Any downloads listed may be third party software. Microsoft grants you no rights for third party software.]]></legal> + </properties> + + <developers> + <developer> + <id>microsoft</id> + <name>Microsoft</name> + </developer> + </developers> + + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>microsoft-azure-api-core</artifactId> + <version>0.5.0</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + </dependency> + <dependency> + <groupId>javax.inject</groupId> + <artifactId>javax.inject</artifactId> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-client</artifactId> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-json</artifactId> + </dependency> + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </dependency> + + <!-- Test dependencies --> + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-all</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcprov-jdk16</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-help-plugin</artifactId> + <version>2.1.1</version> + <executions> + <execution> + <phase>validate</phase> + <goals> + <goal>evaluate</goal> + </goals> + <configuration> + <expression>legal</expression> + </configuration> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <source>1.6</source> + <target>1.6</target> + </configuration> + </plugin> + <plugin> + <groupId>org.jvnet.jaxb2.maven2</groupId> + <artifactId>maven-jaxb2-plugin</artifactId> + <version>0.8.3</version> + <executions> + <execution> + <id>serviceBus</id> + <phase>generate-sources</phase> + <goals> + <goal>generate</goal> + </goals> + <configuration> + <generateDirectory>target/generated-sources/xjc</generateDirectory> + <schemaDirectory>src/main/resources/serviceBus</schemaDirectory> + <schemaIncludes> + <include>servicebus-atom.xsd</include> + </schemaIncludes> + <generatePackage>com.microsoft.windowsazure.services.servicebus.implementation</generatePackage> + <removeOldOutput>false</removeOldOutput> + <forceRegenerate>true</forceRegenerate> + </configuration> + </execution> + <execution> + <id>management</id> + <phase>generate-sources</phase> + <goals> + <goal>generate</goal> + </goals> + <configuration> + <generateDirectory>target/generated-sources/xjc</generateDirectory> + <schemaDirectory>src/main/resources/management/</schemaDirectory> + <schemaIncludes> + <include>schemas.microsoft.com.windowsazure.xsd</include> + </schemaIncludes> + <generatePackage>com.microsoft.windowsazure.services.management.implementation</generatePackage> + <removeOldOutput>false</removeOldOutput> + <forceRegenerate>true</forceRegenerate> + </configuration> + </execution> + </executions> + <configuration> + <extension>true</extension> + <debug>true</debug> + <verbose>true</verbose> + <plugins> + <plugin> + <groupId>org.jvnet.jaxb2_commons</groupId> + <artifactId>jaxb2-basics</artifactId> + <version>0.6.4</version> + </plugin> + <plugin> + <groupId>org.jvnet.jaxb2_commons</groupId> + <artifactId>jaxb2-basics-annotate</artifactId> + <version>0.6.4</version> + </plugin> + </plugins> + + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.8</version> + <configuration> + <excludePackageNames>*.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage</excludePackageNames> + <bottom><![CDATA[<code>/** +<br/>* Copyright Microsoft Corporation +<br/>* +<br/>* Licensed under the Apache License, Version 2.0 (the "License"); +<br/>* you may not use this file except in compliance with the License. +<br/>* You may obtain a copy of the License at +<br/>* http://www.apache.org/licenses/LICENSE-2.0 +<br/>* +<br/>* Unless required by applicable law or agreed to in writing, software +<br/>* distributed under the License is distributed on an "AS IS" BASIS, +<br/>* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +<br/>* See the License for the specific language governing permissions and +<br/>* limitations under the License. +<br/>*/</code>]]></bottom> + </configuration> + </plugin> + + </plugins> + <pluginManagement> + <plugins> + <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-help-plugin</artifactId> + <versionRange>[2.1.1,)</versionRange> + <goals> + <goal>evaluate</goal> + </goals> + </pluginExecutionFilter> + <action> + <ignore></ignore> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-resources-plugin</artifactId> + <version>2.4.3</version> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <version>2.12</version> + <configuration> + <includes> + <include>**/Test*.java</include> + <include>**/*Test.java</include> + <include>**/*Tests.java</include> + <include>**/*TestCase.java</include> + </includes> + </configuration> + </plugin> + </plugins> + </pluginManagement> + </build> + <reporting> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>emma-maven-plugin</artifactId> + <version>1.0-alpha-3</version> + <inherited>true</inherited> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>surefire-report-maven-plugin</artifactId> + <version>2.0-beta-1</version> + <inherited>true</inherited> + </plugin> + </plugins> + </reporting> +</project> diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/Exports.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/Exports.java new file mode 100644 index 0000000000000..92e7ba51241a4 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/Exports.java @@ -0,0 +1,70 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.UserAgentFilter; +import java.util.Map; + +import com.microsoft.windowsazure.services.servicebus.implementation.BrokerPropertiesMapper; +import com.microsoft.windowsazure.services.servicebus.implementation.EntryModelProvider; +import com.microsoft.windowsazure.services.servicebus.implementation.MarshallerProvider; +import com.microsoft.windowsazure.services.servicebus.implementation.ServiceBusExceptionProcessor; +import com.microsoft.windowsazure.services.servicebus.implementation.ServiceBusRestProxy; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.json.JSONConfiguration; + +public class Exports implements Builder.Exports { + @Override + public void register(Builder.Registry registry) { + + // provide contract implementation + registry.add(ServiceBusContract.class, + ServiceBusExceptionProcessor.class); + registry.add(ServiceBusExceptionProcessor.class); + registry.add(ServiceBusRestProxy.class); + registry.add(UserAgentFilter.class); + + // alter jersey client config for serviceBus + registry.alter(ServiceBusContract.class, ClientConfig.class, + new Builder.Alteration<ClientConfig>() { + + @Override + public ClientConfig alter(String profile, + ClientConfig instance, Builder builder, + Map<String, Object> properties) { + + // enable this feature for unattributed json object + // serialization + instance.getProperties().put( + JSONConfiguration.FEATURE_POJO_MAPPING, true); + + // need to avoid certain element prefixes, which the + // service does not ignore + instance.getSingletons().add(new MarshallerProvider()); + + // add body reader/writer for EntryModel<?> descendant + // classes + instance.getClasses().add(EntryModelProvider.class); + + return instance; + } + }); + + // convenience provider to transform BrokerProperty headers to json + registry.add(BrokerPropertiesMapper.class); + + } +} diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusConfiguration.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusConfiguration.java new file mode 100644 index 0000000000000..4d7d36412a781 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusConfiguration.java @@ -0,0 +1,241 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import com.microsoft.windowsazure.Configuration; + +/** + * Provides functionality to create a service bus configuration. + * + */ +public abstract class ServiceBusConfiguration { + + /** + * Defines the configuration connection string constant. + * + */ + public static final String CONNECTION_STRING = "serviceBus.connection.string"; + + /** + * Defines the configuration URI constant. + * + */ + public static final String URI = "serviceBus.uri"; + + /** + * Defines the configuration wrap URI constant. + * + */ + public static final String WRAP_URI = "serviceBus.wrap.uri"; + + /** + * Defines the configuration wrap name constant. + * + */ + public static final String WRAP_NAME = "serviceBus.wrap.name"; + + /** + * Defines the configuration wrap password constant. + * + */ + public static final String WRAP_PASSWORD = "serviceBus.wrap.password"; + + /** + * Creates a service bus configuration using the specified namespace, name, + * and password. + * + * @param namespace + * A <code>String</code> object that represents the namespace. + * + * @param authenticationName + * A <code>String</code> object that represents the + * authentication name. + * + * @param authenticationPassword + * A <code>String</code> object that represents the + * authentication password. + * + * @param serviceBusRootUri + * A <code>String</code> object containing the base URI that is + * added to your Service Bus namespace to form the URI to connect + * to the Service Bus service. + * + * To access the default public Azure service, pass + * ".servicebus.windows.net" + * + * @param wrapRootUri + * A <code>String</code> object containing the base URI that is + * added to your Service Bus namespace to form the URI to get an + * access token for the Service Bus service. + * + * To access the default public Azure service, pass + * "-sb.accesscontrol.windows.net/WRAPv0.9" + * + * @return A <code>Configuration</code> object that can be used when + * creating an instance of the <code>ServiceBusService</code> class. + * + */ + public static Configuration configureWithWrapAuthentication( + String namespace, String authenticationName, + String authenticationPassword, String serviceBusRootUri, + String wrapRootUri) { + return configureWithWrapAuthentication(null, + Configuration.getInstance(), namespace, authenticationName, + authenticationPassword, serviceBusRootUri, wrapRootUri); + } + + /** + * Creates a service bus configuration using the specified configuration, + * namespace, name, and password. + * + * @param configuration + * A previously instantiated <code>Configuration</code> object. + * + * @param namespace + * A <code>String</code> object that represents the namespace. + * + * @param authenticationName + * A <code>String</code> object that represents the + * authentication name. + * + * @param authenticationPassword + * A <code>String</code> object that represents the + * authentication password. + * + * @param serviceBusRootUri + * A <code>String</code> object containing the base URI that is + * added to your Service Bus namespace to form the URI to connect + * to the Service Bus service. + * + * To access the default public Azure service, pass + * ".servicebus.windows.net" + * + * @param wrapRootUri + * A <code>String</code> object containing the base URI that is + * added to your Service Bus namespace to form the URI to get an + * access token for the Service Bus service. + * + * To access the default public Azure service, pass + * "-sb.accesscontrol.windows.net/WRAPv0.9" + * + * @return A <code>Configuration</code> object that can be used when + * creating an instance of the <code>ServiceBusService</code> class. + * + */ + public static Configuration configureWithWrapAuthentication( + Configuration configuration, String namespace, + String authenticationName, String authenticationPassword, + String serviceBusRootUri, String wrapRootUri) { + return configureWithWrapAuthentication(null, configuration, namespace, + authenticationName, authenticationPassword, serviceBusRootUri, + wrapRootUri); + } + + /** + * Creates a service bus configuration using the specified profile, + * configuration, namespace, name, and password. + * + * @param profile + * A <code>String</code> object that represents the profile. + * + * @param configuration + * A previously instantiated <code>Configuration</code> object. + * + * @param namespace + * A <code>String</code> object that represents the namespace. + * + * @param authenticationName + * A <code>String</code> object that represents the + * authentication name. + * + * @param authenticationPassword + * A <code>String</code> object that represents the + * authentication password. + * + * @param serviceBusRootUri + * A <code>String</code> object containing the base URI that is + * added to your Service Bus namespace to form the URI to connect + * to the Service Bus service. + * + * To access the default public Azure service, pass + * ".servicebus.windows.net" + * + * @param wrapRootUri + * A <code>String</code> object containing the base URI that is + * added to your Service Bus namespace to form the URI to get an + * access token for the Service Bus service. + * + * To access the default public Azure service, pass + * "-sb.accesscontrol.windows.net/WRAPv0.9" + * + * @return A <code>Configuration</code> object that can be used when + * creating an instance of the <code>ServiceBusService</code> class. + * + */ + public static Configuration configureWithWrapAuthentication(String profile, + Configuration configuration, String namespace, + String authenticationName, String authenticationPassword, + String serviceBusRootUri, String wrapRootUri) { + + if (profile == null) { + profile = ""; + } else if (profile.length() != 0 && !profile.endsWith(".")) { + profile = profile + "."; + } + + configuration.setProperty(profile + CONNECTION_STRING, null); + + configuration.setProperty(profile + URI, "https://" + namespace + + serviceBusRootUri); + + configuration.setProperty(profile + WRAP_URI, "https://" + namespace + + wrapRootUri); + + configuration.setProperty(profile + WRAP_NAME, authenticationName); + configuration.setProperty(profile + WRAP_PASSWORD, + authenticationPassword); + + return configuration; + } + + /** + * Creates a service bus configuration using the specified connection + * string. + * + * @param profile + * A <code>String</code> object that represents the profile. + * @param configuration + * A previously instantiated <code>Configuration</cone> object. + * @param connectionString + * A <code>String</code> object the contains the connection + * string for the service bus connection information. + * @return A <code>Configuration</code> object that can be used when + * creating an instance of the <code>ServiceBusService</code> class. + */ + public static Configuration configureWithConnectionString(String profile, + Configuration configuration, String connectionString) { + + if (profile == null) { + profile = ""; + } else if (profile.length() != 0 && !profile.endsWith(".")) { + profile = profile + "."; + } + + configuration + .setProperty(profile + CONNECTION_STRING, connectionString); + + return configuration; + } +} diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusContract.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusContract.java new file mode 100644 index 0000000000000..2b0c276442cd3 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusContract.java @@ -0,0 +1,604 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import com.microsoft.windowsazure.core.pipeline.jersey.JerseyFilterableService; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.servicebus.models.BrokeredMessage; +import com.microsoft.windowsazure.services.servicebus.models.CreateQueueResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateRuleResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateSubscriptionResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateTopicResult; +import com.microsoft.windowsazure.services.servicebus.models.GetQueueResult; +import com.microsoft.windowsazure.services.servicebus.models.GetRuleResult; +import com.microsoft.windowsazure.services.servicebus.models.GetSubscriptionResult; +import com.microsoft.windowsazure.services.servicebus.models.GetTopicResult; +import com.microsoft.windowsazure.services.servicebus.models.ListQueuesOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListQueuesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListRulesOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListRulesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListSubscriptionsOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListSubscriptionsResult; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsResult; +import com.microsoft.windowsazure.services.servicebus.models.QueueInfo; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageOptions; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveQueueMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveSubscriptionMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.RuleInfo; +import com.microsoft.windowsazure.services.servicebus.models.SubscriptionInfo; +import com.microsoft.windowsazure.services.servicebus.models.TopicInfo; + +/** + * + * Defines the service bus contract. + * + */ +public interface ServiceBusContract extends + JerseyFilterableService<ServiceBusContract> { + + /** + * Sends a queue message. + * + * @param queuePath + * A <code>String</code> object that represents the name of the + * queue to which the message will be sent. + * @param message + * A <code>Message</code> object that represents the message to + * send. + * @throws ServiceException + * If a service exception is encountered. + */ + void sendQueueMessage(String queuePath, BrokeredMessage message) + throws ServiceException; + + /** + * Receives a queue message. + * + * @param queuePath + * A <code>String</code> object that represents the name of the + * queue from which to receive the message. + * @return A <code>ReceiveQueueMessageResult</code> object that represents + * the result. + * @throws ServiceException + * If a service exception is encountered. + */ + ReceiveQueueMessageResult receiveQueueMessage(String queuePath) + throws ServiceException; + + /** + * Receives a queue message using the specified receive message options. + * + * @param queuePath + * A <code>String</code> object that represents the name of the + * queue from which to receive the message. + * @param options + * A <code>ReceiveMessageOptions</code> object that represents + * the receive message options. + * @return A <code>ReceiveQueueMessageResult</code> object that represents + * the result. + * @throws ServiceException + * If a service exception is encountered. + */ + ReceiveQueueMessageResult receiveQueueMessage(String queuePath, + ReceiveMessageOptions options) throws ServiceException; + + /** + * Sends a topic message. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic to which the message will be sent. + * @param message + * A <code>Message</code> object that represents the message to + * send. + * @throws ServiceException + * If a service exception is encountered. + */ + void sendTopicMessage(String topicPath, BrokeredMessage message) + throws ServiceException; + + /** + * Receives a subscription message. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic to receive. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription from the message will be received. + * @return A <code>ReceiveSubscriptionMessageResult</code> object that + * represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + ReceiveSubscriptionMessageResult receiveSubscriptionMessage( + String topicPath, String subscriptionName) throws ServiceException; + + /** + * Receives a subscription message using the specified receive message + * options. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic to receive. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription from the message will be received. + * @param options + * A <code>ReceiveMessageOptions</code> object that represents + * the receive message options. + * @return A <code>ReceiveSubscriptionMessageResult</code> object that + * represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + ReceiveSubscriptionMessageResult receiveSubscriptionMessage( + String topicPath, String subscriptionName, + ReceiveMessageOptions options) throws ServiceException; + + /** + * Unlocks a message. + * + * @param message + * A <code>Message</code> object that represents the message to + * unlock. + * @throws ServiceException + * If a service exception is encountered. + */ + void unlockMessage(BrokeredMessage message) throws ServiceException; + + /** + * Sends a message. + * + * @param path + * A <code>String</code> object that represents the path to which + * the message will be sent. This may be the value of a queuePath + * or a topicPath. + * @param message + * A <code>Message</code> object that represents the message to + * send. + * + * @throws ServiceException + * If a service exception is encountered. + */ + void sendMessage(String path, BrokeredMessage message) + throws ServiceException; + + /** + * Receives a message. + * + * @param path + * A <code>String</code> object that represents the path from + * which a message will be received. This may either be the value + * of queuePath or a combination of the topicPath + + * "/subscriptions/" + subscriptionName. + * @return A <code>ReceiveSubscriptionMessageResult</code> object that + * represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + ReceiveMessageResult receiveMessage(String path) throws ServiceException; + + /** + * Receives a message using the specified receive message options. + * + * @param path + * A <code>String</code> object that represents the path from + * which a message will be received. This may either be the value + * of queuePath or a combination of the topicPath + + * "/subscriptions/" + subscriptionName. + * @param options + * A <code>ReceiveMessageOptions</code> object that represents + * the receive message options. + * @return A <code>ReceiveSubscriptionMessageResult</code> object that + * represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + ReceiveMessageResult receiveMessage(String path, + ReceiveMessageOptions options) throws ServiceException; + + /** + * Deletes a message. + * + * @param message + * A <code>Message</code> object that represents the message to + * delete. + * @throws ServiceException + * If a service exception is encountered. + */ + void deleteMessage(BrokeredMessage message) throws ServiceException; + + /** + * Creates a queue. + * + * @param queueInfo + * A <code>QueueInfo</code> object that represents the queue to + * create. + * @return A <code>CreateQueueResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + CreateQueueResult createQueue(QueueInfo queueInfo) throws ServiceException; + + /** + * Deletes a queue. + * + * @param queuePath + * A <code>String</code> object that represents the name of the + * queue to delete. + * @throws ServiceException + * If a service exception is encountered. + */ + void deleteQueue(String queuePath) throws ServiceException; + + /** + * Retrieves a queue. + * + * @param queuePath + * A <code>String</code> object that represents the name of the + * queue to retrieve. + * @return A <code>GetQueueResult</code> object that represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + GetQueueResult getQueue(String queuePath) throws ServiceException; + + /** + * Returns a list of queues. + * + * @return A <code>ListQueuesResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + ListQueuesResult listQueues() throws ServiceException; + + /** + * Returns a list of queues. + * + * @param options + * A <code>ListQueueOptions</code> object that represents the + * options to list the queue. + * @return A <code>ListQueuesResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + ListQueuesResult listQueues(ListQueuesOptions options) + throws ServiceException; + + /** + * Updates the information of a queue. + * + * @param queueInfo + * The information of a queue to be updated. + * + * @return A <code>QueueInfo</code> object that represents the updated + * queue. + * + * @throws ServiceException + * If a service exception is encountered. + */ + QueueInfo updateQueue(QueueInfo queueInfo) throws ServiceException; + + /** + * Creates a topic. + * + * @param topic + * A <code>Topic</code> object that represents the topic to + * create. + * @return A <code>CreateTopicResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + CreateTopicResult createTopic(TopicInfo topic) throws ServiceException; + + /** + * Deletes a topic. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * queue to delete. + * @throws ServiceException + * If a service exception is encountered. + */ + void deleteTopic(String topicPath) throws ServiceException; + + /** + * Retrieves a topic. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic to retrieve. + * @return A <code>GetTopicResult</code> object that represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + GetTopicResult getTopic(String topicPath) throws ServiceException; + + /** + * Returns a list of topics. + * + * @return A <code>ListTopicsResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + ListTopicsResult listTopics() throws ServiceException; + + /** + * Returns a list of topics. + * + * @param options + * A <code>ListTopicsOptions</code> object that represents the + * options to list the topic. + * @return A <code>ListTopicsResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + ListTopicsResult listTopics(ListTopicsOptions options) + throws ServiceException; + + /** + * Updates a topic. + * + * @param topicInfo + * A <code>TopicInfo</code> object that represents the topic to + * be updated. + * + * @return A <code>TopicInfo</code> object that represents the update topic + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + TopicInfo updateTopic(TopicInfo topicInfo) throws ServiceException; + + /** + * Creates a subscription. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscription + * A <code>Subscription</code> object that represents the + * subscription to create. + * @return A <code>CreateSubscriptionResult</code> object that represents + * the result. + * @throws ServiceException + * If a service exception is encountered. + */ + CreateSubscriptionResult createSubscription(String topicPath, + SubscriptionInfo subscription) throws ServiceException; + + /** + * Deletes a subscription. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription to delete. + * @throws ServiceException + * If a service exception is encountered. + */ + void deleteSubscription(String topicPath, String subscriptionName) + throws ServiceException; + + /** + * Retrieves a subscription. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription to retrieve. + * @return A <code>GetSubscriptionResult</code> object that represents the + * result. A <code>String</code> object that represents the name of + * the subscription to retrieve. + * @throws ServiceException + * If a service exception is encountered. + */ + GetSubscriptionResult getSubscription(String topicPath, + String subscriptionName) throws ServiceException; + + /** + * Returns a list of subscriptions. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscriptions to retrieve. + * @return A <code>ListSubscriptionsResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + ListSubscriptionsResult listSubscriptions(String topicPath) + throws ServiceException; + + /** + * Returns a list of subscriptions. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscriptions to retrieve. + * + * @param options + * A <code>ListSubscriptionsOptions</code> object that represents + * the options to list subscriptions. + * + * @return A <code>ListSubscriptionsResult</code> object that represents the + * result. + * + * @throws ServiceException + * the service exception + */ + ListSubscriptionsResult listSubscriptions(String topicPath, + ListSubscriptionsOptions options) throws ServiceException; + + /** + * Updates a subscription. + * + * @param topicName + * A <code>String</code> option which represents the name of the + * topic. + * @param subscriptionInfo + * A <code>SubscriptionInfo</code> option which represents the + * information of the subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + SubscriptionInfo updateSubscription(String topicName, + SubscriptionInfo subscriptionInfo) throws ServiceException; + + /** + * Creates a rule. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription for which the rule will be created. + * @param rule + * A <code>Rule</code> object that represents the rule to create. + * @return A <code>CreateRuleResult</code> object that represents the + * result. + * @throws ServiceException + * If a service exception is encountered. + */ + CreateRuleResult createRule(String topicPath, String subscriptionName, + RuleInfo rule) throws ServiceException; + + /** + * Deletes a rule. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription for which the rule will be deleted. + * @param ruleName + * A <code>String</code> object that represents the name of the + * rule to delete. + * @throws ServiceException + * If a service exception is encountered. + */ + void deleteRule(String topicPath, String subscriptionName, String ruleName) + throws ServiceException; + + /** + * Retrieves a rule. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription for which the rule will be retrieved. + * @param ruleName + * A <code>String</code> object that represents the name of the + * rule to retrieve. + * @return A <code>GetRuleResult</code> object that represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + GetRuleResult getRule(String topicPath, String subscriptionName, + String ruleName) throws ServiceException; + + /** + * Returns a list of rules. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription whose rules are being retrieved. + * @return A <code>ListRulesResult</code> object that represents the result. + * @throws ServiceException + * If a service exception is encountered. + */ + ListRulesResult listRules(String topicPath, String subscriptionName) + throws ServiceException; + + /** + * Returns a list of rules. + * + * @param topicPath + * A <code>String</code> object that represents the name of the + * topic for the subscription. + * @param subscriptionName + * A <code>String</code> object that represents the name of the + * subscription whose rules are being retrieved. + * @param options + * A <code>ListRulesOptions</code> object that represents the + * options to retrieve rules. + * @return the list rules result + * @throws ServiceException + * If a service exception is encountered. + */ + ListRulesResult listRules(String topicPath, String subscriptionName, + ListRulesOptions options) throws ServiceException; + + /** + * Renew queue lock. + * + * @param queueName + * A <code>String</code> object that represents the name of the + * queue. + * @param messageId + * A <code>String</code> object that represents the ID of the + * message. + * @param lockToken + * A <code>String</code> object that represents the token of the + * lock. + * @throws ServiceException + * If a service exception is encountered. + */ + void renewQueueLock(String queueName, String messageId, String lockToken) + throws ServiceException; + + /** + * Renew subscription lock. + * + * @param topicName + * A <code>String</code> object that represents the name of the + * topic. + * @param queueName + * A <code>String</code> object that represents the name of the + * queue. + * @param messageId + * A <code>String</code> object that represents the ID of the + * message. + * @param lockToken + * A <code>String</code> object that represents the token of the + * lock. + * @throws ServiceException + * If a service exception is encountered. + */ + void renewSubscriptionLock(String topicName, String subscriptionName, + String messageId, String lockToken) throws ServiceException; +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusService.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusService.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusService.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusService.java index b36011b789033..9c7d64a69d26e 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/ServiceBusService.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/ServiceBusService.java @@ -12,16 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus; +package com.microsoft.windowsazure.services.servicebus; -import com.microsoft.windowsazure.services.core.Configuration; +import com.microsoft.windowsazure.Configuration; /** * * Access service bus functionality. * */ -public class ServiceBusService { +public final class ServiceBusService { private ServiceBusService() { // class is not instantiated @@ -36,10 +36,12 @@ public static ServiceBusContract create() { } /** - * Creates an instance of the <code>ServiceBusContract</code> API using the specified configuration. + * Creates an instance of the <code>ServiceBusContract</code> API using the + * specified configuration. * * @param config - * A <code>Configuration</code> object that represents the configuration for the service bus service. + * A <code>Configuration</code> object that represents the + * configuration for the service bus service. * */ public static ServiceBusContract create(Configuration config) { @@ -51,14 +53,17 @@ public static ServiceBusContract create(Configuration config) { * */ public static ServiceBusContract create(String profile) { - return Configuration.getInstance().create(profile, ServiceBusContract.class); + return Configuration.getInstance().create(profile, + ServiceBusContract.class); } /** - * Creates an instance of the <code>ServiceBusContract</code> API using the specified configuration. + * Creates an instance of the <code>ServiceBusContract</code> API using the + * specified configuration. * * @param config - * A <code>Configuration</code> object that represents the configuration for the service bus service. + * A <code>Configuration</code> object that represents the + * configuration for the service bus service. * */ public static ServiceBusContract create(String profile, Configuration config) { diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/Util.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/Util.java new file mode 100644 index 0000000000000..682a00ce4c9df --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/Util.java @@ -0,0 +1,31 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.services.servicebus.models.QueueInfo; +import com.microsoft.windowsazure.services.servicebus.models.TopicInfo; + +public abstract class Util { + public static Iterable<QueueInfo> iterateQueues(ServiceBusContract service) + throws ServiceException { + return service.listQueues().getItems(); + } + + public static Iterable<TopicInfo> iterateTopics(ServiceBusContract service) + throws ServiceException { + return service.listTopics().getItems(); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/BrokerProperties.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/BrokerProperties.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/BrokerProperties.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/BrokerProperties.java index e677178530558..0654c733315b9 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/BrokerProperties.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/BrokerProperties.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; import java.util.Date; @@ -31,49 +31,49 @@ public class BrokerProperties { @JsonProperty("CorrelationId") - String correlationId; + private String correlationId; @JsonProperty("SessionId") - String sessionId; + private String sessionId; @JsonProperty("DeliveryCount") - Integer deliveryCount; + private Integer deliveryCount; @JsonProperty("LockedUntilUtc") - Date lockedUntilUtc; + private Date lockedUntilUtc; @JsonProperty("LockToken") - String lockToken; + private String lockToken; @JsonProperty("MessageId") - String messageId; + private String messageId; @JsonProperty("Label") - String label; + private String label; @JsonProperty("ReplyTo") - String replyTo; + private String replyTo; @JsonProperty("SequenceNumber") - Long sequenceNumber; + private Long sequenceNumber; @JsonProperty("TimeToLive") - Double timeToLive; + private Double timeToLive; @JsonProperty("To") - String to; + private String to; @JsonProperty("ScheduledEnqueueTimeUtc") - Date scheduledEnqueueTimeUtc; + private Date scheduledEnqueueTimeUtc; @JsonProperty("ReplyToSessionId") - String replyToSessionId; + private String replyToSessionId; @JsonProperty("MessageLocation") - String messageLocation; + private String messageLocation; @JsonProperty("LockLocation") - String lockLocation; + private String lockLocation; @JsonIgnore public Integer getDeliveryCount() { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/BrokerPropertiesMapper.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/BrokerPropertiesMapper.java similarity index 75% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/BrokerPropertiesMapper.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/BrokerPropertiesMapper.java index 3dfa6ea80c5f4..6a404f72cd9c8 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/BrokerPropertiesMapper.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/BrokerPropertiesMapper.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; import java.io.IOException; import java.io.StringWriter; @@ -27,21 +27,20 @@ public class BrokerPropertiesMapper { - public BrokerProperties fromString(String value) throws IllegalArgumentException { + public BrokerProperties fromString(String value) { ObjectMapper mapper = new ObjectMapper(); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat( + "EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); mapper.setDateFormat(simpleDateFormat); try { - return mapper.readValue(value.getBytes("UTF-8"), BrokerProperties.class); - } - catch (JsonParseException e) { + return mapper.readValue(value.getBytes("UTF-8"), + BrokerProperties.class); + } catch (JsonParseException e) { throw new IllegalArgumentException(e); - } - catch (JsonMappingException e) { + } catch (JsonMappingException e) { throw new IllegalArgumentException(e); - } - catch (IOException e) { + } catch (IOException e) { throw new IllegalArgumentException(e); } } @@ -51,14 +50,11 @@ public String toString(BrokerProperties value) { Writer writer = new StringWriter(); try { mapper.writeValue(writer, value); - } - catch (JsonGenerationException e) { + } catch (JsonGenerationException e) { throw new RuntimeException(e); - } - catch (JsonMappingException e) { + } catch (JsonMappingException e) { throw new RuntimeException(e); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } return writer.toString(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/CustomPropertiesMapper.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/CustomPropertiesMapper.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/CustomPropertiesMapper.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/CustomPropertiesMapper.java index 89e6fec612bcd..6cf4850d6a21b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/CustomPropertiesMapper.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/CustomPropertiesMapper.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; import java.text.DateFormat; import java.text.ParseException; @@ -34,39 +34,30 @@ public String toString(Object value) { Class<? extends Object> type = value.getClass(); if (type == Byte.class) { return value.toString(); - } - else if (type == Short.class) { + } else if (type == Short.class) { return value.toString(); - } - else if (type == Integer.class) { + } else if (type == Integer.class) { return value.toString(); - } - else if (type == Long.class) { + } else if (type == Long.class) { return value.toString(); - } - else if (type == Float.class) { + } else if (type == Float.class) { return value.toString(); - } - else if (type == Double.class) { + } else if (type == Double.class) { return value.toString(); - } - else if (type == Boolean.class) { + } else if (type == Boolean.class) { return value.toString(); - } - else if (Calendar.class.isAssignableFrom(type)) { + } else if (Calendar.class.isAssignableFrom(type)) { DateFormat format = new SimpleDateFormat(RFC_1123, Locale.US); Calendar calendar = (Calendar) value; format.setTimeZone(calendar.getTimeZone()); String formatted = format.format(calendar.getTime()); return "\"" + formatted + "\""; - } - else if (Date.class.isAssignableFrom(type)) { + } else if (Date.class.isAssignableFrom(type)) { DateFormat format = new SimpleDateFormat(RFC_1123, Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); String formatted = format.format((Date) value); return "\"" + formatted + "\""; - } - else { + } else { return "\"" + value.toString() + "\""; } } @@ -79,22 +70,19 @@ public Object fromString(String value) throws ParseException { if (value.startsWith("\"") && value.endsWith("\"")) { String text = value.substring(1, value.length() - 1); if (isRFC1123(text)) { - SimpleDateFormat format = new SimpleDateFormat(RFC_1123, Locale.US); + SimpleDateFormat format = new SimpleDateFormat(RFC_1123, + Locale.US); return format.parse(text); } return text; - } - else if ("true".equals(value)) { + } else if ("true".equals(value)) { return Boolean.TRUE; - } - else if ("false".equals(value)) { + } else if ("false".equals(value)) { return Boolean.FALSE; - } - else if (isInteger(value)) { + } else if (isInteger(value)) { return Integer.parseInt(value); - } - else { + } else { return Double.parseDouble(value); } } @@ -107,8 +95,7 @@ private boolean isRFC1123(String text) { SimpleDateFormat format = new SimpleDateFormat(RFC_1123, Locale.US); format.parse(text); return true; - } - catch (ParseException e) { + } catch (ParseException e) { return false; } } @@ -117,8 +104,7 @@ private boolean isInteger(String value) { try { Integer.parseInt(value); return true; - } - catch (NumberFormatException e) { + } catch (NumberFormatException e) { return false; } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/EntryModel.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/EntryModel.java similarity index 90% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/EntryModel.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/EntryModel.java index e61d84d987e70..d0237459636a0 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/EntryModel.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/EntryModel.java @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; public class EntryModel<T> { - Entry entry; - T model; + private Entry entry; + private T model; public EntryModel(Entry entry, T model) { this.entry = entry; diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/EntryModelProvider.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/EntryModelProvider.java new file mode 100644 index 0000000000000..e752b18c3d6fd --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/EntryModelProvider.java @@ -0,0 +1,96 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Type; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.MessageBodyWriter; + +import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; +import com.sun.jersey.spi.MessageBodyWorkers; + +public class EntryModelProvider extends + AbstractMessageReaderWriterProvider<EntryModel<?>> { + + private MessageBodyWorkers workers; + + public EntryModelProvider(@Context MessageBodyWorkers workers) { + this.workers = workers; + } + + @Override + public boolean isReadable(Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return EntryModel.class.isAssignableFrom(type); + } + + @Override + public EntryModel<?> readFrom(Class<EntryModel<?>> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> httpHeaders, InputStream entityStream) + throws IOException { + + MessageBodyReader<Entry> reader = workers.getMessageBodyReader( + Entry.class, Entry.class, annotations, mediaType); + + Entry entry = reader.readFrom(Entry.class, Entry.class, annotations, + mediaType, httpHeaders, entityStream); + + // these exceptions are masked as a RuntimeException because they cannot + // be thrown by this override + try { + return type.getConstructor(Entry.class).newInstance(entry); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } catch (InvocationTargetException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (InstantiationException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean isWriteable(Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return EntryModel.class.isAssignableFrom(type); + } + + @Override + public void writeTo(EntryModel<?> t, Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, Object> httpHeaders, + OutputStream entityStream) throws IOException { + + Entry entry = t.getEntry(); + + MessageBodyWriter<Entry> writer = workers.getMessageBodyWriter( + Entry.class, Entry.class, annotations, mediaType); + + writer.writeTo(entry, Entry.class, genericType, annotations, mediaType, + httpHeaders, entityStream); + } + +} diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/Exports.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/Exports.java new file mode 100644 index 0000000000000..d007f6c8e9401 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/Exports.java @@ -0,0 +1,58 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.utils.ConnectionStringSyntaxException; +import static com.microsoft.windowsazure.core.utils.ExportUtils.getPropertyIfExists; +import com.microsoft.windowsazure.services.servicebus.ServiceBusConfiguration; +import java.net.URISyntaxException; +import java.util.Map; + +public class Exports implements Builder.Exports { + + @Override + public void register(Builder.Registry registry) { + registry.add(WrapContract.class, WrapRestProxy.class); + registry.add(WrapTokenManager.class); + registry.add(WrapFilter.class); + + registry.add(new Builder.Factory<ServiceBusConnectionSettings>() { + + @Override + public <S> ServiceBusConnectionSettings create(String profile, + Class<S> service, Builder builder, + Map<String, Object> properties) { + try { + return new ServiceBusConnectionSettings( + (String) getPropertyIfExists(profile, properties, + ServiceBusConfiguration.CONNECTION_STRING), + (String) getPropertyIfExists(profile, properties, + ServiceBusConfiguration.URI), + (String) getPropertyIfExists(profile, properties, + ServiceBusConfiguration.WRAP_URI), + (String) getPropertyIfExists(profile, properties, + ServiceBusConfiguration.WRAP_NAME), + (String) getPropertyIfExists(profile, properties, + ServiceBusConfiguration.WRAP_PASSWORD)); + } catch (ConnectionStringSyntaxException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (URISyntaxException e) { + throw new RuntimeException(e.getMessage(), e); + } + } + }); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/MarshallerProvider.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/MarshallerProvider.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/MarshallerProvider.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/MarshallerProvider.java index 3edfc51d87c26..ff1df8c5780b5 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/MarshallerProvider.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/MarshallerProvider.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; @@ -35,18 +35,16 @@ public Marshaller getContext(Class<?> type) { Marshaller marshaller; try { marshaller = getJAXBContext(type).createMarshaller(); - } - catch (JAXBException e) { + } catch (JAXBException e) { return null; - } - catch (Exception e) { + } catch (Exception e) { return null; } com.sun.xml.bind.marshaller.NamespacePrefixMapper mapper = new NamespacePrefixMapperImpl(); try { - marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper); - } - catch (PropertyException e) { + marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", + mapper); + } catch (PropertyException e) { return null; } return marshaller; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/NamespacePrefixMapperImpl.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/NamespacePrefixMapperImpl.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/NamespacePrefixMapperImpl.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/NamespacePrefixMapperImpl.java index 2cf8396485af1..323b3f82fddfc 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/NamespacePrefixMapperImpl.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/NamespacePrefixMapperImpl.java @@ -12,18 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; import com.sun.xml.bind.marshaller.NamespacePrefixMapper; public class NamespacePrefixMapperImpl extends NamespacePrefixMapper { @Override - public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) { + public String getPreferredPrefix(String namespaceUri, String suggestion, + boolean requirePrefix) { if (namespaceUri == "http://www.w3.org/2005/Atom") { return "atom"; - } - else if (namespaceUri == "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect") { + } else if (namespaceUri == "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect") { return ""; } return suggestion; diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionSettings.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionSettings.java new file mode 100644 index 0000000000000..277723628c0c0 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionSettings.java @@ -0,0 +1,93 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.core.utils.ConnectionStringSyntaxException; +import java.net.URI; +import java.net.URISyntaxException; + +/** + * Class that encapsulates all the various settings needed to connect to Service + * Bus, provided via either a connection string or via separate configuration + * variables. + * <p/> + * The connection string is looked for first, falling back to separate config + * values if not found. + */ +class ServiceBusConnectionSettings { + private String uri; + private String wrapUri; + private String wrapName; + private String wrapPassword; + + public ServiceBusConnectionSettings(String connectionString, String uri, + String wrapUri, String wrapName, String wrapPassword) + throws ConnectionStringSyntaxException, URISyntaxException { + if (connectionString != null) { + parseConnectionString(connectionString); + } else { + this.uri = uri; + this.wrapUri = wrapUri; + this.wrapName = wrapName; + this.wrapPassword = wrapPassword; + } + } + + public String getUri() { + return uri; + } + + public String getWrapUri() { + return wrapUri; + } + + public String getWrapName() { + return wrapName; + } + + public String getWrapPassword() { + return wrapPassword; + } + + private boolean parseConnectionString(String connectionString) + throws URISyntaxException, ConnectionStringSyntaxException { + ServiceBusConnectionString cs = new ServiceBusConnectionString( + connectionString); + setUri(cs); + setWrapUri(cs); + wrapName = cs.getSharedSecretIssuer(); + wrapPassword = cs.getSharedSecretValue(); + return true; + } + + private void setUri(ServiceBusConnectionString connectionString) { + uri = connectionString.getEndpoint().replaceFirst("^sb://", "https://"); + } + + private void setWrapUri(ServiceBusConnectionString connectionString) + throws URISyntaxException { + if (connectionString.getStsEndpoint() == null + || connectionString.getStsEndpoint().isEmpty()) { + URI hostUri = new URI(uri); + String namespace = hostUri.getHost().split("\\.")[0]; + wrapUri = "https://" + namespace + + "-sb.accesscontrol.windows.net/WRAPv0.9"; + } else { + wrapUri = connectionString.getStsEndpoint().replaceAll("\\/$", "") + + "/WRAPv0.9"; + } + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionString.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionString.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionString.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionString.java index ee63db4ccaf8a..53017532c365b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/ServiceBusConnectionString.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionString.java @@ -13,29 +13,31 @@ * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; -import com.microsoft.windowsazure.services.core.utils.ConnectionStringSyntaxException; -import com.microsoft.windowsazure.services.core.utils.ParsedConnectionString; +import com.microsoft.windowsazure.core.utils.ConnectionStringSyntaxException; +import com.microsoft.windowsazure.core.utils.ParsedConnectionString; /** * Class that parses the fields present in a service bus connection string. - * + * */ public class ServiceBusConnectionString extends ParsedConnectionString { /** - * Construct the {@link ServiceBusConnectionString} instance with the - * data from the given connection string + * Construct the {@link ServiceBusConnectionString} instance with the data + * from the given connection string + * + * @param connectionString + * The connection string * - * @param connectionString The connection string - * * @throws ConnectionStringSyntaxException */ - public ServiceBusConnectionString(String connectionString) throws ConnectionStringSyntaxException { + public ServiceBusConnectionString(String connectionString) + throws ConnectionStringSyntaxException { super(connectionString); } - + private String endpoint; private String stsEndpoint; private String sharedSecretIssuer; @@ -43,6 +45,7 @@ public ServiceBusConnectionString(String connectionString) throws ConnectionStri /** * Get the endpoint from the connection string + * * @return the endpoint */ public String getEndpoint() { @@ -51,6 +54,7 @@ public String getEndpoint() { /** * Sets the endpoint value + * * @param endpoint */ public void setEndpoint(String endpoint) { @@ -59,6 +63,7 @@ public void setEndpoint(String endpoint) { /** * Get the StsEndpoint from the connection string + * * @return the sts endpoint */ public String getStsEndpoint() { @@ -67,6 +72,7 @@ public String getStsEndpoint() { /** * Sets the StsEndpoint value + * * @param stsEndpoint */ public void setStsEndpoint(String stsEndpoint) { @@ -75,6 +81,7 @@ public void setStsEndpoint(String stsEndpoint) { /** * Get the shared secret issuer + * * @return the issuer */ public String getSharedSecretIssuer() { @@ -83,6 +90,7 @@ public String getSharedSecretIssuer() { /** * Set the shared secret issuer + * * @param sharedSecretIssuer */ public void setSharedSecretIssuer(String sharedSecretIssuer) { @@ -91,6 +99,7 @@ public void setSharedSecretIssuer(String sharedSecretIssuer) { /** * Get the shared secret value + * * @return the shared secret value */ public String getSharedSecretValue() { @@ -99,6 +108,7 @@ public String getSharedSecretValue() { /** * Set the shared secret value + * * @param sharedSecretValue */ public void setSharedSecretValue(String sharedSecretValue) { diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusExceptionProcessor.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusExceptionProcessor.java new file mode 100644 index 0000000000000..2b6f15f4adbb5 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusExceptionProcessor.java @@ -0,0 +1,537 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import javax.inject.Inject; +import javax.ws.rs.WebApplicationException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.microsoft.windowsazure.services.servicebus.ServiceBusContract; +import com.microsoft.windowsazure.services.servicebus.models.BrokeredMessage; +import com.microsoft.windowsazure.services.servicebus.models.CreateQueueResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateRuleResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateSubscriptionResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateTopicResult; +import com.microsoft.windowsazure.services.servicebus.models.GetQueueResult; +import com.microsoft.windowsazure.services.servicebus.models.GetRuleResult; +import com.microsoft.windowsazure.services.servicebus.models.GetSubscriptionResult; +import com.microsoft.windowsazure.services.servicebus.models.GetTopicResult; +import com.microsoft.windowsazure.services.servicebus.models.ListQueuesOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListQueuesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListRulesOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListRulesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListSubscriptionsOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListSubscriptionsResult; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsResult; +import com.microsoft.windowsazure.services.servicebus.models.QueueInfo; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageOptions; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveQueueMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveSubscriptionMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.RuleInfo; +import com.microsoft.windowsazure.services.servicebus.models.SubscriptionInfo; +import com.microsoft.windowsazure.services.servicebus.models.TopicInfo; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class ServiceBusExceptionProcessor implements ServiceBusContract { + + private final ServiceBusContract next; + private static Log log = LogFactory.getLog(ServiceBusContract.class); + + public ServiceBusExceptionProcessor(ServiceBusContract next) { + this.next = next; + } + + @Inject + public ServiceBusExceptionProcessor(ServiceBusRestProxy next) { + this.next = next; + } + + @Override + public ServiceBusContract withFilter(ServiceFilter filter) { + return new ServiceBusExceptionProcessor(next.withFilter(filter)); + } + + @Override + public ServiceBusContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + return new ServiceBusExceptionProcessor( + next.withRequestFilterFirst(serviceRequestFilter)); + } + + @Override + public ServiceBusContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + return new ServiceBusExceptionProcessor( + next.withRequestFilterLast(serviceRequestFilter)); + } + + @Override + public ServiceBusContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + return new ServiceBusExceptionProcessor( + next.withResponseFilterFirst(serviceResponseFilter)); + } + + @Override + public ServiceBusContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + return new ServiceBusExceptionProcessor( + next.withResponseFilterLast(serviceResponseFilter)); + } + + private ServiceException processCatch(ServiceException e) { + log.warn(e.getMessage(), e.getCause()); + return ServiceExceptionFactory.process("serviceBus", e); + } + + @Override + public void sendQueueMessage(String path, BrokeredMessage message) + throws ServiceException { + try { + next.sendQueueMessage(path, message); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ReceiveQueueMessageResult receiveQueueMessage(String queueName) + throws ServiceException { + try { + return next.receiveQueueMessage(queueName); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ReceiveQueueMessageResult receiveQueueMessage(String queueName, + ReceiveMessageOptions options) throws ServiceException { + try { + return next.receiveQueueMessage(queueName, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void sendTopicMessage(String path, BrokeredMessage message) + throws ServiceException { + try { + next.sendTopicMessage(path, message); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ReceiveSubscriptionMessageResult receiveSubscriptionMessage( + String topicName, String subscriptionName) throws ServiceException { + try { + return next.receiveSubscriptionMessage(topicName, subscriptionName); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ReceiveSubscriptionMessageResult receiveSubscriptionMessage( + String topicName, String subscriptionName, + ReceiveMessageOptions options) throws ServiceException { + try { + return next.receiveSubscriptionMessage(topicName, subscriptionName, + options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void unlockMessage(BrokeredMessage message) throws ServiceException { + try { + next.unlockMessage(message); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteMessage(BrokeredMessage message) throws ServiceException { + try { + next.deleteMessage(message); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public CreateQueueResult createQueue(QueueInfo queue) + throws ServiceException { + try { + return next.createQueue(queue); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteQueue(String queuePath) throws ServiceException { + try { + next.deleteQueue(queuePath); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetQueueResult getQueue(String queuePath) throws ServiceException { + try { + return next.getQueue(queuePath); + } catch (WebApplicationException e) { + throw processCatch(new ServiceException(e)); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListQueuesResult listQueues() throws ServiceException { + try { + return next.listQueues(); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public QueueInfo updateQueue(QueueInfo queueInfo) throws ServiceException { + try { + return next.updateQueue(queueInfo); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public CreateTopicResult createTopic(TopicInfo topic) + throws ServiceException { + try { + return next.createTopic(topic); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteTopic(String topicPath) throws ServiceException { + try { + next.deleteTopic(topicPath); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetTopicResult getTopic(String topicPath) throws ServiceException { + try { + return next.getTopic(topicPath); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListTopicsResult listTopics() throws ServiceException { + try { + return next.listTopics(); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public TopicInfo updateTopic(TopicInfo topicInfo) throws ServiceException { + try { + return next.updateTopic(topicInfo); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public CreateSubscriptionResult createSubscription(String topicPath, + SubscriptionInfo subscription) throws ServiceException { + try { + return next.createSubscription(topicPath, subscription); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteSubscription(String topicPath, String subscriptionName) + throws ServiceException { + try { + next.deleteSubscription(topicPath, subscriptionName); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetSubscriptionResult getSubscription(String topicPath, + String subscriptionName) throws ServiceException { + try { + return next.getSubscription(topicPath, subscriptionName); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListSubscriptionsResult listSubscriptions(String topicPath) + throws ServiceException { + try { + return next.listSubscriptions(topicPath); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public SubscriptionInfo updateSubscription(String topicName, + SubscriptionInfo subscriptionInfo) throws ServiceException { + try { + return next.updateSubscription(topicName, subscriptionInfo); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public CreateRuleResult createRule(String topicPath, + String subscriptionName, RuleInfo rule) throws ServiceException { + try { + return next.createRule(topicPath, subscriptionName, rule); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void deleteRule(String topicPath, String subscriptionName, + String ruleName) throws ServiceException { + try { + next.deleteRule(topicPath, subscriptionName, ruleName); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public GetRuleResult getRule(String topicPath, String subscriptionName, + String ruleName) throws ServiceException { + try { + return next.getRule(topicPath, subscriptionName, ruleName); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListRulesResult listRules(String topicPath, String subscriptionName) + throws ServiceException { + try { + return next.listRules(topicPath, subscriptionName); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListQueuesResult listQueues(ListQueuesOptions options) + throws ServiceException { + try { + return next.listQueues(options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListTopicsResult listTopics(ListTopicsOptions options) + throws ServiceException { + try { + return next.listTopics(options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListSubscriptionsResult listSubscriptions(String topicName, + ListSubscriptionsOptions options) throws ServiceException { + try { + return next.listSubscriptions(topicName, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ListRulesResult listRules(String topicName, String subscriptionName, + ListRulesOptions options) throws ServiceException { + try { + return next.listRules(topicName, subscriptionName, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void sendMessage(String path, BrokeredMessage message) + throws ServiceException { + try { + next.sendMessage(path, message); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ReceiveMessageResult receiveMessage(String path) + throws ServiceException { + try { + return next.receiveMessage(path); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public ReceiveMessageResult receiveMessage(String path, + ReceiveMessageOptions options) throws ServiceException { + try { + return next.receiveMessage(path, options); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void renewQueueLock(String queueName, String messageId, + String lockToken) throws ServiceException { + try { + next.renewQueueLock(queueName, messageId, lockToken); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + + @Override + public void renewSubscriptionLock(String topicName, + String subscriptionName, String messageId, String lockToken) + throws ServiceException { + try { + next.renewSubscriptionLock(topicName, subscriptionName, messageId, + lockToken); + } catch (UniformInterfaceException e) { + throw processCatch(new ServiceException(e)); + } catch (ClientHandlerException e) { + throw processCatch(new ServiceException(e)); + } + } + +} diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusRestProxy.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusRestProxy.java new file mode 100644 index 0000000000000..256f9ee4c852f --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusRestProxy.java @@ -0,0 +1,580 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.core.pipeline.PipelineHelpers; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestFilter; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterRequestAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterResponseAdapter; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import java.io.InputStream; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; + +import javax.inject.Inject; +import javax.ws.rs.core.MediaType; + +import com.microsoft.windowsazure.services.servicebus.ServiceBusContract; +import com.microsoft.windowsazure.services.servicebus.models.AbstractListOptions; +import com.microsoft.windowsazure.services.servicebus.models.BrokeredMessage; +import com.microsoft.windowsazure.services.servicebus.models.CreateQueueResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateRuleResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateSubscriptionResult; +import com.microsoft.windowsazure.services.servicebus.models.CreateTopicResult; +import com.microsoft.windowsazure.services.servicebus.models.GetQueueResult; +import com.microsoft.windowsazure.services.servicebus.models.GetRuleResult; +import com.microsoft.windowsazure.services.servicebus.models.GetSubscriptionResult; +import com.microsoft.windowsazure.services.servicebus.models.GetTopicResult; +import com.microsoft.windowsazure.services.servicebus.models.ListQueuesOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListQueuesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListRulesOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListRulesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListSubscriptionsOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListSubscriptionsResult; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsResult; +import com.microsoft.windowsazure.services.servicebus.models.QueueInfo; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageOptions; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveQueueMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveSubscriptionMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.RuleInfo; +import com.microsoft.windowsazure.services.servicebus.models.SubscriptionInfo; +import com.microsoft.windowsazure.services.servicebus.models.TopicInfo; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class ServiceBusRestProxy implements ServiceBusContract { + + private Client channel; + private final String uri; + private final BrokerPropertiesMapper mapper; + private final CustomPropertiesMapper customPropertiesMapper; + + private ClientFilter[] filters; + + @Inject + public ServiceBusRestProxy(Client channel, WrapFilter authFilter, + UserAgentFilter userAgentFilter, + ServiceBusConnectionSettings connectionSettings, + BrokerPropertiesMapper mapper) { + + this.channel = channel; + this.filters = new ClientFilter[0]; + this.uri = connectionSettings.getUri(); + this.mapper = mapper; + this.customPropertiesMapper = new CustomPropertiesMapper(); + channel.addFilter(authFilter); + channel.addFilter(new ClientFilterRequestAdapter(userAgentFilter)); + } + + public ServiceBusRestProxy(Client channel, ClientFilter[] filters, + String uri, BrokerPropertiesMapper mapper) { + this.channel = channel; + this.filters = filters; + this.uri = uri; + this.mapper = mapper; + this.customPropertiesMapper = new CustomPropertiesMapper(); + } + + @Override + public ServiceBusContract withFilter(ServiceFilter filter) { + ClientFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1); + newFilters[filters.length] = new ClientFilterAdapter(filter); + return new ServiceBusRestProxy(channel, newFilters, uri, mapper); + } + + @Override + public ServiceBusContract withRequestFilterFirst( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterRequestAdapter(serviceRequestFilter); + return new ServiceBusRestProxy(channel, newFilters, uri, mapper); + } + + @Override + public ServiceBusContract withRequestFilterLast( + ServiceRequestFilter serviceRequestFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterRequestAdapter( + serviceRequestFilter); + return new ServiceBusRestProxy(channel, newFilters, uri, mapper); + } + + @Override + public ServiceBusContract withResponseFilterFirst( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = new ClientFilter[currentFilters.length + 1]; + System.arraycopy(currentFilters, 0, newFilters, 1, + currentFilters.length); + newFilters[0] = new ClientFilterResponseAdapter(serviceResponseFilter); + return new ServiceBusRestProxy(channel, newFilters, uri, mapper); + } + + @Override + public ServiceBusContract withResponseFilterLast( + ServiceResponseFilter serviceResponseFilter) { + ClientFilter[] currentFilters = filters; + ClientFilter[] newFilters = Arrays.copyOf(currentFilters, + currentFilters.length + 1); + newFilters[currentFilters.length] = new ClientFilterResponseAdapter( + serviceResponseFilter); + return new ServiceBusRestProxy(channel, newFilters, uri, mapper); + } + + public Client getChannel() { + return channel; + } + + public void setChannel(Client channel) { + this.channel = channel; + } + + private WebResource getResource() { + WebResource resource = getChannel().resource(uri).queryParam( + "api-version", "2012-08"); + for (ClientFilter filter : filters) { + resource.addFilter(filter); + } + return resource; + } + + @Override + public void sendMessage(String path, BrokeredMessage message) { + Builder request = getResource().path(path).path("messages") + .getRequestBuilder(); + + if (message.getContentType() != null) { + request = request.type(message.getContentType()); + } + + if (message.getBrokerProperties() != null) { + request = request.header("BrokerProperties", + mapper.toString(message.getBrokerProperties())); + } + + for (java.util.Map.Entry<String, Object> entry : message + .getProperties().entrySet()) { + request.header(entry.getKey(), + customPropertiesMapper.toString(entry.getValue())); + } + + request.post(message.getBody()); + } + + @Override + public void sendQueueMessage(String path, BrokeredMessage message) + throws ServiceException { + sendMessage(path, message); + } + + @Override + public ReceiveQueueMessageResult receiveQueueMessage(String queueName) + throws ServiceException { + return receiveQueueMessage(queueName, ReceiveMessageOptions.DEFAULT); + } + + @Override + public ReceiveQueueMessageResult receiveQueueMessage(String queuePath, + ReceiveMessageOptions options) throws ServiceException { + + WebResource resource = getResource().path(queuePath).path("messages") + .path("head"); + + BrokeredMessage message = receiveMessage(options, resource); + return new ReceiveQueueMessageResult(message); + } + + @Override + public ReceiveMessageResult receiveMessage(String path) + throws ServiceException { + return receiveMessage(path, ReceiveMessageOptions.DEFAULT); + } + + @Override + public ReceiveMessageResult receiveMessage(String path, + ReceiveMessageOptions options) throws ServiceException { + + WebResource resource = getResource().path(path).path("messages") + .path("head"); + + BrokeredMessage message = receiveMessage(options, resource); + return new ReceiveMessageResult(message); + } + + private BrokeredMessage receiveMessage(ReceiveMessageOptions options, + WebResource resource) { + if (options.getTimeout() != null) { + resource = resource.queryParam("timeout", + Integer.toString(options.getTimeout())); + } + + ClientResponse clientResult; + if (options.isReceiveAndDelete()) { + clientResult = resource.delete(ClientResponse.class); + } else if (options.isPeekLock()) { + clientResult = resource.post(ClientResponse.class, ""); + } else { + throw new RuntimeException("Unknown ReceiveMode"); + } + + if (clientResult.getStatus() == 204) { + return null; + } + + BrokerProperties brokerProperties; + if (clientResult.getHeaders().containsKey("BrokerProperties")) { + brokerProperties = mapper.fromString(clientResult.getHeaders() + .getFirst("BrokerProperties")); + } else { + brokerProperties = new BrokerProperties(); + } + + String location = clientResult.getHeaders().getFirst("Location"); + if (location != null) { + brokerProperties.setLockLocation(location); + } + + BrokeredMessage message = new BrokeredMessage(brokerProperties); + + MediaType contentType = clientResult.getType(); + if (contentType != null) { + message.setContentType(contentType.toString()); + } + + Date date = clientResult.getResponseDate(); + if (date != null) { + message.setDate(date); + } + + InputStream body = clientResult.getEntityInputStream(); + if (body != null) { + message.setBody(body); + } + + for (String key : clientResult.getHeaders().keySet()) { + Object value = clientResult.getHeaders().getFirst(key); + try { + value = customPropertiesMapper.fromString(value.toString()); + message.setProperty(key, value); + } catch (ParseException e) { + // log.warn("Unable to parse custom header", e); + } catch (NumberFormatException e) { + // log.warn("Unable to parse custom header", e); + } + } + + return message; + } + + @Override + public void sendTopicMessage(String topicName, BrokeredMessage message) + throws ServiceException { + sendMessage(topicName, message); + } + + @Override + public ReceiveSubscriptionMessageResult receiveSubscriptionMessage( + String topicName, String subscriptionName) throws ServiceException { + return receiveSubscriptionMessage(topicName, subscriptionName, + ReceiveMessageOptions.DEFAULT); + } + + @Override + public ReceiveSubscriptionMessageResult receiveSubscriptionMessage( + String topicName, String subscriptionName, + ReceiveMessageOptions options) throws ServiceException { + WebResource resource = getResource().path(topicName) + .path("subscriptions").path(subscriptionName).path("messages") + .path("head"); + + BrokeredMessage message = receiveMessage(options, resource); + return new ReceiveSubscriptionMessageResult(message); + } + + @Override + public void unlockMessage(BrokeredMessage message) throws ServiceException { + getChannel().resource(message.getLockLocation()).put(""); + } + + @Override + public void deleteMessage(BrokeredMessage message) throws ServiceException { + getChannel().resource(message.getLockLocation()).delete(); + } + + @Override + public CreateQueueResult createQueue(QueueInfo queueInfo) + throws ServiceException { + Builder webResourceBuilder = getResource().path(queueInfo.getPath()) + .type("application/atom+xml;type=entry;charset=utf-8"); + if ((queueInfo.getForwardTo() != null) + && !queueInfo.getForwardTo().isEmpty()) { + webResourceBuilder.header("ServiceBusSupplementaryAuthorization", + queueInfo.getForwardTo()); + } + return new CreateQueueResult(webResourceBuilder.put(QueueInfo.class, + queueInfo)); + } + + @Override + public void deleteQueue(String queuePath) throws ServiceException { + getResource().path(queuePath).delete(); + } + + @Override + public GetQueueResult getQueue(String queuePath) throws ServiceException { + return new GetQueueResult(getResource().path(queuePath).get( + QueueInfo.class)); + } + + @Override + public ListQueuesResult listQueues(ListQueuesOptions options) + throws ServiceException { + Feed feed = listOptions(options, + getResource().path("$Resources/Queues")).get(Feed.class); + ArrayList<QueueInfo> queues = new ArrayList<QueueInfo>(); + for (Entry entry : feed.getEntries()) { + queues.add(new QueueInfo(entry)); + } + ListQueuesResult result = new ListQueuesResult(); + result.setItems(queues); + return result; + } + + @Override + public QueueInfo updateQueue(QueueInfo queueInfo) throws ServiceException { + Builder webResourceBuilder = getResource().path(queueInfo.getPath()) + .type("application/atom+xml;type=entry;charset=utf-8") + .header("If-Match", "*"); + if ((queueInfo.getForwardTo() != null) + && !queueInfo.getForwardTo().isEmpty()) { + webResourceBuilder.header("ServiceBusSupplementaryAuthorization", + queueInfo.getForwardTo()); + } + return webResourceBuilder.put(QueueInfo.class, queueInfo); + } + + private WebResource listOptions(AbstractListOptions<?> options, + WebResource path) { + if (options.getTop() != null) { + path = path.queryParam("$top", options.getTop().toString()); + } + if (options.getSkip() != null) { + path = path.queryParam("$skip", options.getSkip().toString()); + } + if (options.getFilter() != null) { + path = path.queryParam("$filter", options.getFilter()); + } + return path; + } + + @Override + public CreateTopicResult createTopic(TopicInfo entry) + throws ServiceException { + return new CreateTopicResult(getResource().path(entry.getPath()) + .type("application/atom+xml;type=entry;charset=utf-8") + .put(TopicInfo.class, entry)); + } + + @Override + public void deleteTopic(String topicPath) throws ServiceException { + getResource().path(topicPath).delete(); + } + + @Override + public GetTopicResult getTopic(String topicPath) throws ServiceException { + return new GetTopicResult(getResource().path(topicPath).get( + TopicInfo.class)); + } + + @Override + public ListTopicsResult listTopics(ListTopicsOptions options) + throws ServiceException { + Feed feed = listOptions(options, + getResource().path("$Resources/Topics")).get(Feed.class); + ArrayList<TopicInfo> topics = new ArrayList<TopicInfo>(); + for (Entry entry : feed.getEntries()) { + topics.add(new TopicInfo(entry)); + } + ListTopicsResult result = new ListTopicsResult(); + result.setItems(topics); + return result; + } + + @Override + public TopicInfo updateTopic(TopicInfo topicInfo) throws ServiceException { + return getResource().path(topicInfo.getPath()) + .type("application/atom+xml;type=entry;charset=utf-8") + .header("If-Match", "*").put(TopicInfo.class, topicInfo); + } + + @Override + public CreateSubscriptionResult createSubscription(String topicPath, + SubscriptionInfo subscriptionInfo) { + Builder webResourceBuilder = getResource().path(topicPath) + .path("subscriptions").path(subscriptionInfo.getName()) + .type("application/atom+xml;type=entry;charset=utf-8"); + if ((subscriptionInfo.getForwardTo() != null) + && (!subscriptionInfo.getForwardTo().isEmpty())) { + webResourceBuilder.header("ServiceBusSupplementaryAuthorization", + subscriptionInfo.getForwardTo()); + + } + return new CreateSubscriptionResult(webResourceBuilder.put( + SubscriptionInfo.class, subscriptionInfo)); + } + + @Override + public void deleteSubscription(String topicPath, String subscriptionName) { + getResource().path(topicPath).path("subscriptions") + .path(subscriptionName).delete(); + } + + @Override + public GetSubscriptionResult getSubscription(String topicPath, + String subscriptionName) { + return new GetSubscriptionResult(getResource().path(topicPath) + .path("subscriptions").path(subscriptionName) + .get(SubscriptionInfo.class)); + } + + @Override + public ListSubscriptionsResult listSubscriptions(String topicPath, + ListSubscriptionsOptions options) { + Feed feed = listOptions(options, + getResource().path(topicPath).path("subscriptions")).get( + Feed.class); + ArrayList<SubscriptionInfo> list = new ArrayList<SubscriptionInfo>(); + for (Entry entry : feed.getEntries()) { + list.add(new SubscriptionInfo(entry)); + } + ListSubscriptionsResult result = new ListSubscriptionsResult(); + result.setItems(list); + return result; + } + + @Override + public SubscriptionInfo updateSubscription(String topicName, + SubscriptionInfo subscriptionInfo) throws ServiceException { + Builder webResourceBuilder = getResource().path(topicName) + .path("subscriptions").path(subscriptionInfo.getName()) + .type("application/atom+xml;type=entry;charset=utf-8") + .header("If-Match", "*"); + if ((subscriptionInfo.getForwardTo() != null) + && !subscriptionInfo.getForwardTo().isEmpty()) { + webResourceBuilder.header("ServiceBusSupplementaryAuthorization", + subscriptionInfo.getForwardTo()); + } + return webResourceBuilder.put(SubscriptionInfo.class, subscriptionInfo); + } + + @Override + public CreateRuleResult createRule(String topicPath, + String subscriptionName, RuleInfo rule) { + return new CreateRuleResult(getResource().path(topicPath) + .path("subscriptions").path(subscriptionName).path("rules") + .path(rule.getName()) + .type("application/atom+xml;type=entry;charset=utf-8") + .put(RuleInfo.class, rule)); + } + + @Override + public void deleteRule(String topicPath, String subscriptionName, + String ruleName) { + getResource().path(topicPath).path("subscriptions") + .path(subscriptionName).path("rules").path(ruleName).delete(); + } + + @Override + public GetRuleResult getRule(String topicPath, String subscriptionName, + String ruleName) { + return new GetRuleResult(getResource().path(topicPath) + .path("subscriptions").path(subscriptionName).path("rules") + .path(ruleName).get(RuleInfo.class)); + } + + @Override + public ListRulesResult listRules(String topicPath, String subscriptionName, + ListRulesOptions options) { + Feed feed = listOptions( + options, + getResource().path(topicPath).path("subscriptions") + .path(subscriptionName).path("rules")).get(Feed.class); + ArrayList<RuleInfo> list = new ArrayList<RuleInfo>(); + for (Entry entry : feed.getEntries()) { + list.add(new RuleInfo(entry)); + } + ListRulesResult result = new ListRulesResult(); + result.setItems(list); + return result; + } + + @Override + public ListQueuesResult listQueues() throws ServiceException { + return listQueues(ListQueuesOptions.DEFAULT); + } + + @Override + public ListTopicsResult listTopics() throws ServiceException { + return listTopics(ListTopicsOptions.DEFAULT); + } + + @Override + public ListSubscriptionsResult listSubscriptions(String topicName) + throws ServiceException { + return listSubscriptions(topicName, ListSubscriptionsOptions.DEFAULT); + } + + @Override + public ListRulesResult listRules(String topicName, String subscriptionName) + throws ServiceException { + return listRules(topicName, subscriptionName, ListRulesOptions.DEFAULT); + } + + @Override + public void renewQueueLock(String queueName, String messageId, + String lockToken) throws ServiceException { + ClientResponse clientResponse = getResource().path(queueName) + .path("messages").path(messageId).path(lockToken) + .post(ClientResponse.class, ""); + PipelineHelpers.throwIfNotSuccess(clientResponse); + } + + @Override + public void renewSubscriptionLock(String topicName, + String subscriptionName, String messageId, String lockToken) + throws ServiceException { + ClientResponse clientResponse = getResource().path(topicName) + .path("Subscriptions").path(subscriptionName).path("messages") + .path(messageId).path(lockToken).post(ClientResponse.class, ""); + PipelineHelpers.throwIfNotSuccess(clientResponse); + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapAccessTokenResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapAccessTokenResult.java similarity index 90% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapAccessTokenResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapAccessTokenResult.java index ee6e919010cf8..bb47b3fdf9a30 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapAccessTokenResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapAccessTokenResult.java @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; public class WrapAccessTokenResult { - String accessToken; - long expiresIn; + private String accessToken; + private long expiresIn; /** * @return the accessToken diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapContract.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapContract.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapContract.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapContract.java index 2e8389774679d..ff7079ba7a588 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapContract.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapContract.java @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; -import com.microsoft.windowsazure.services.core.ServiceException; +import com.microsoft.windowsazure.exception.ServiceException; public interface WrapContract { - WrapAccessTokenResult wrapAccessToken(String uri, String name, String password, String scope) - throws ServiceException; + WrapAccessTokenResult wrapAccessToken(String uri, String name, + String password, String scope) throws ServiceException; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapFilter.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapFilter.java similarity index 75% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapFilter.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapFilter.java index f1d0187a6b21c..dfb9b0784e331 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapFilter.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapFilter.java @@ -12,12 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; +import com.microsoft.windowsazure.exception.ServiceException; import java.net.URI; import java.net.URISyntaxException; -import com.microsoft.windowsazure.services.core.ServiceException; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientRequest; import com.sun.jersey.api.client.ClientResponse; @@ -31,15 +31,19 @@ public WrapFilter(WrapTokenManager tokenManager) { } @Override - public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { + public ClientResponse handle(ClientRequest cr) { String accessToken = getWrapToken(cr.getURI()); cr.getHeaders().add("Authorization", accessToken); - String secondaryAuthorizationUri = (String) cr.getHeaders().getFirst("ServiceBusSupplementaryAuthorization"); - if ((secondaryAuthorizationUri != null) && (!secondaryAuthorizationUri.isEmpty())) { - String secondaryAccessToken = getWrapToken(URI.create(secondaryAuthorizationUri)); + String secondaryAuthorizationUri = (String) cr.getHeaders().getFirst( + "ServiceBusSupplementaryAuthorization"); + if ((secondaryAuthorizationUri != null) + && (!secondaryAuthorizationUri.isEmpty())) { + String secondaryAccessToken = getWrapToken(URI + .create(secondaryAuthorizationUri)); cr.getHeaders().remove("ServiceBusSupplementaryAuthorization"); - cr.getHeaders().add("ServiceBusSupplementaryAuthorization", secondaryAccessToken); + cr.getHeaders().add("ServiceBusSupplementaryAuthorization", + secondaryAccessToken); } return this.getNext().handle(cr); @@ -49,12 +53,10 @@ private String getWrapToken(URI uri) { String result; try { result = tokenManager.getAccessToken(uri); - } - catch (ServiceException e) { + } catch (ServiceException e) { // must wrap exception because of base class signature throw new ClientHandlerException(e); - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { // must wrap exception because of base class signature throw new ClientHandlerException(e); } diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapRestProxy.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapRestProxy.java new file mode 100644 index 0000000000000..59326e7f99cd1 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapRestProxy.java @@ -0,0 +1,72 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.core.UserAgentFilter; +import com.microsoft.windowsazure.core.pipeline.jersey.ClientFilterRequestAdapter; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import javax.inject.Inject; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.representation.Form; + +public class WrapRestProxy implements WrapContract { + private Client channel; + + private static Log log = LogFactory.getLog(WrapContract.class); + + @Inject + public WrapRestProxy(Client channel, UserAgentFilter userAgentFilter) { + this.channel = channel; + this.channel.addFilter(new ClientFilterRequestAdapter(userAgentFilter)); + } + + @Override + public WrapAccessTokenResult wrapAccessToken(String uri, String name, + String password, String scope) throws ServiceException { + Form requestForm = new Form(); + requestForm.add("wrap_name", name); + requestForm.add("wrap_password", password); + requestForm.add("wrap_scope", scope); + + Form responseForm; + try { + responseForm = channel.resource(uri) + .accept(MediaType.APPLICATION_FORM_URLENCODED) + .type(MediaType.APPLICATION_FORM_URLENCODED) + .post(Form.class, requestForm); + } catch (UniformInterfaceException e) { + log.warn("WRAP server returned error acquiring access_token", e); + throw ServiceExceptionFactory.process("WRAP", new ServiceException( + "WRAP server returned error acquiring access_token", e)); + } + + WrapAccessTokenResult response = new WrapAccessTokenResult(); + + response.setAccessToken(responseForm.getFirst("wrap_access_token")); + + String expiresIn = responseForm + .getFirst("wrap_access_token_expires_in"); + response.setExpiresIn(Long.parseLong(expiresIn)); + + return response; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManager.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManager.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManager.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManager.java index 5255b4ec25cd8..333544937d7af 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManager.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManager.java @@ -12,8 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; +import com.microsoft.windowsazure.core.utils.DateFactory; +import com.microsoft.windowsazure.exception.ServiceException; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; @@ -25,12 +27,9 @@ import javax.inject.Inject; import javax.management.timer.Timer; -import com.microsoft.windowsazure.services.core.ServiceException; -import com.microsoft.windowsazure.services.core.utils.DateFactory; - public class WrapTokenManager { - WrapContract contract; + private WrapContract contract; private final DateFactory dateFactory; private final String uri; private final String name; @@ -64,10 +63,12 @@ public void setContract(WrapContract contract) { this.contract = contract; } - public String getAccessToken(URI targetUri) throws ServiceException, URISyntaxException { + public String getAccessToken(URI targetUri) throws ServiceException, + URISyntaxException { Date now = dateFactory.getDate(); - URI scopeUri = new URI("http", targetUri.getAuthority(), targetUri.getPath(), null, null); + URI scopeUri = new URI("http", targetUri.getAuthority(), + targetUri.getPath(), null, null); String scope = scopeUri.toString(); ActiveToken active = this.activeTokens.get(scope); @@ -77,7 +78,8 @@ public String getAccessToken(URI targetUri) throws ServiceException, URISyntaxEx } // sweep expired tokens out of collection - Iterator<Entry<String, ActiveToken>> iterator = activeTokens.entrySet().iterator(); + Iterator<Entry<String, ActiveToken>> iterator = activeTokens.entrySet() + .iterator(); while (iterator.hasNext()) { Entry<String, ActiveToken> entry = iterator.next(); if (!now.before(entry.getValue().getExpiresUtc())) { @@ -85,8 +87,10 @@ public String getAccessToken(URI targetUri) throws ServiceException, URISyntaxEx } } - WrapAccessTokenResult wrapResponse = getContract().wrapAccessToken(uri, name, password, scope); - Date expiresUtc = new Date(now.getTime() + wrapResponse.getExpiresIn() * Timer.ONE_SECOND / 2); + WrapAccessTokenResult wrapResponse = getContract().wrapAccessToken(uri, + name, password, scope); + Date expiresUtc = new Date(now.getTime() + wrapResponse.getExpiresIn() + * Timer.ONE_SECOND / 2); ActiveToken acquired = new ActiveToken(); acquired.setWrapResponse(wrapResponse); @@ -97,8 +101,8 @@ public String getAccessToken(URI targetUri) throws ServiceException, URISyntaxEx } class ActiveToken { - Date expiresUtc; - WrapAccessTokenResult wrapResponse; + private Date expiresUtc; + private WrapAccessTokenResult wrapResponse; /** * @return the expiresUtc diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/package.html b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/package.html rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/implementation/package.html diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/AbstractListOptions.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/AbstractListOptions.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/AbstractListOptions.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/AbstractListOptions.java index 79fbb5a31769f..a95a55eb97924 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/AbstractListOptions.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/AbstractListOptions.java @@ -12,12 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; public abstract class AbstractListOptions<T> { - Integer skip; - Integer top; - String filter; + private Integer skip; + private Integer top; + private String filter; public Integer getSkip() { return skip; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/BrokeredMessage.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/BrokeredMessage.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/BrokeredMessage.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/BrokeredMessage.java index 3c222a52e7930..488ec022d1331 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/BrokeredMessage.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/BrokeredMessage.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -21,17 +21,17 @@ import java.util.HashMap; import java.util.Map; -import com.microsoft.windowsazure.services.serviceBus.implementation.BrokerProperties; +import com.microsoft.windowsazure.services.servicebus.implementation.BrokerProperties; /** * Represents a service bus message. */ public class BrokeredMessage { - BrokerProperties brokerProperties; - InputStream body; - String contentType; - Date date; - Map<String, Object> customProperties; + private BrokerProperties brokerProperties; + private InputStream body; + private String contentType; + private Date date; + private Map<String, Object> customProperties; /** * Creates an instance of the <code>Message</code> class. @@ -41,10 +41,12 @@ public BrokeredMessage() { } /** - * Creates an instance of the <code>Message</code> class using the specified <code>InputStream</code>. + * Creates an instance of the <code>Message</code> class using the specified + * <code>InputStream</code>. * * @param body - * An <code>InputStream</code> object that represents the body of the message. + * An <code>InputStream</code> object that represents the body of + * the message. */ public BrokeredMessage(InputStream body) { this(new BrokerProperties()); @@ -52,7 +54,8 @@ public BrokeredMessage(InputStream body) { } /** - * Creates an instance of the <code>Message</code> class using the specified byte array. + * Creates an instance of the <code>Message</code> class using the specified + * byte array. * * @param body * A byte array that represents the body of the message. @@ -67,14 +70,15 @@ public BrokeredMessage(byte[] body) { * string. * * @param body - * A <code>String</code> object that represents the body of the message. + * A <code>String</code> object that represents the body of the + * message. */ public BrokeredMessage(String body) { this(new BrokerProperties()); try { - this.body = (body == null) ? null : new ByteArrayInputStream(body.getBytes("UTF-8")); - } - catch (UnsupportedEncodingException e) { + this.body = (body == null) ? null : new ByteArrayInputStream( + body.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @@ -92,7 +96,8 @@ public BrokeredMessage(BrokerProperties properties) { /** * Returns the properties of the message. * - * @return A {@link BrokerProperties} object that represents the properties of the message. + * @return A {@link BrokerProperties} object that represents the properties + * of the message. */ public BrokerProperties getBrokerProperties() { return brokerProperties; @@ -101,7 +106,8 @@ public BrokerProperties getBrokerProperties() { /** * Returns the body of the message. * - * @return An <code>InputStream</code> object that represents the body of the message. + * @return An <code>InputStream</code> object that represents the body of + * the message. */ public InputStream getBody() { return body; @@ -111,9 +117,11 @@ public InputStream getBody() { * Specifies the body of the message. * * @param body - * An <code>InputStream</code> object that represents the body of the message. + * An <code>InputStream</code> object that represents the body of + * the message. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setBody(InputStream body) { this.body = body; @@ -135,7 +143,8 @@ public String getContentType() { * @param contentType * A <code>String</code> object that represents the content type. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setContentType(String contentType) { this.contentType = contentType; @@ -145,7 +154,8 @@ public BrokeredMessage setContentType(String contentType) { /** * Returns the date/time of the message. * - * @return A <code>Date</code> object that represents the date/time of the object. + * @return A <code>Date</code> object that represents the date/time of the + * object. */ public Date getDate() { return date; @@ -155,9 +165,11 @@ public Date getDate() { * Sets the date/time of the message. * * @param date - * A <code>Date</code> object that represents the date/time of the object. + * A <code>Date</code> object that represents the date/time of + * the object. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setDate(Date date) { this.date = date; @@ -168,8 +180,10 @@ public BrokeredMessage setDate(Date date) { * Returns a user defined property of the message. * * @param name - * A <code>String</code> object that represents the name of the property. - * @return An <code>Object</code> object that represents the value of the property. + * A <code>String</code> object that represents the name of the + * property. + * @return An <code>Object</code> object that represents the value of the + * property. */ public Object getProperty(String name) { return customProperties.get(name); @@ -179,10 +193,13 @@ public Object getProperty(String name) { * Sets a user defined property of the message. * * @param name - * A <code>String</code> object that represents the name of the property. + * A <code>String</code> object that represents the name of the + * property. * @param value - * An <code>Object</code> object that represents the value of the property. - * @return A <code>Message</code> object that represents the updated message. + * An <code>Object</code> object that represents the value of the + * property. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setProperty(String name, Object value) { customProperties.put(name, value); @@ -192,7 +209,8 @@ public BrokeredMessage setProperty(String name, Object value) { /** * Returns the user defined properties of the message. * - * @return A <code>Map</code> object that represents the user defined properties. + * @return A <code>Map</code> object that represents the user defined + * properties. */ public Map<String, Object> getProperties() { return customProperties; @@ -222,7 +240,8 @@ public String getMessageId() { * @param messageId * A <code>String</code> object that represents the message ID. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setMessageId(String messageId) { brokerProperties.setMessageId(messageId); @@ -254,7 +273,8 @@ public Double getTimeToLive() { * @param timeToLive * The time, in seconds, for the message to live. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setTimeToLive(Double timeToLive) { brokerProperties.setTimeToLive(timeToLive); @@ -273,7 +293,8 @@ public String getLockToken() { /** * Returns the locked-until date/time. * - * @return A <code>Date</code> object that represents the locked-until date/time, in UTC format. + * @return A <code>Date</code> object that represents the locked-until + * date/time, in UTC format. */ public Date getLockedUntilUtc() { return brokerProperties.getLockedUntilUtc(); @@ -293,9 +314,11 @@ public String getCorrelationId() { * Sets the correlation ID. * * @param correlationId - * A <code>String</code> object that represents the correlation ID. + * A <code>String</code> object that represents the correlation + * ID. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setCorrelationId(String correlationId) { brokerProperties.setCorrelationId(correlationId); @@ -318,7 +341,8 @@ public String getSessionId() { * @param sessionId * A <code>String</code> object that represents the session ID. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setSessionId(String sessionId) { brokerProperties.setSessionId(sessionId); @@ -340,7 +364,8 @@ public String getLabel() { * @param label * A <code>String</code> object that represents the label. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setLabel(String label) { brokerProperties.setLabel(label); @@ -350,7 +375,8 @@ public BrokeredMessage setLabel(String label) { /** * Returns the Reply-To recipient of the message. * - * @return A <code>String</code> object that represents the Reply-To recipient. + * @return A <code>String</code> object that represents the Reply-To + * recipient. */ public String getReplyTo() { return brokerProperties.getReplyTo(); @@ -360,9 +386,11 @@ public String getReplyTo() { * Sets the Reply-To recipient for the message. * * @param replyTo - * A <code>String</code> object that represents the Reply-To recipient. + * A <code>String</code> object that represents the Reply-To + * recipient. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setReplyTo(String replyTo) { brokerProperties.setReplyTo(replyTo); @@ -384,7 +412,8 @@ public String getTo() { * @param to * A <code>String</code> object that represents the To recipient. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setTo(String to) { brokerProperties.setTo(to); @@ -394,7 +423,8 @@ public BrokeredMessage setTo(String to) { /** * Returns the scheduled enqueue date/time. * - * @return A <code>Date</code> object that represents the date/time of the message in UTC format. + * @return A <code>Date</code> object that represents the date/time of the + * message in UTC format. */ public Date getScheduledEnqueueTimeUtc() { return brokerProperties.getScheduledEnqueueTimeUtc(); @@ -404,11 +434,14 @@ public Date getScheduledEnqueueTimeUtc() { * Sets the scheduled enqueue time. * * @param scheduledEnqueueTimeUtc - * A <code>Date</code> object that represents the date/time of the message in UTC format. + * A <code>Date</code> object that represents the date/time of + * the message in UTC format. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ - public BrokeredMessage setScheduledEnqueueTimeUtc(Date scheduledEnqueueTimeUtc) { + public BrokeredMessage setScheduledEnqueueTimeUtc( + Date scheduledEnqueueTimeUtc) { brokerProperties.setScheduledEnqueueTimeUtc(scheduledEnqueueTimeUtc); return this; } @@ -416,7 +449,8 @@ public BrokeredMessage setScheduledEnqueueTimeUtc(Date scheduledEnqueueTimeUtc) /** * Returns the session ID of the Reply To recipient. * - * @return A <code>String</code> object that represents the session ID of the Reply To recipient. + * @return A <code>String</code> object that represents the session ID of + * the Reply To recipient. */ public String getReplyToSessionId() { return brokerProperties.getReplyToSessionId(); @@ -426,9 +460,11 @@ public String getReplyToSessionId() { * Sets the session ID of the Reply To recipient. * * @param replyToSessionId - * A <code>String</code> object that represents the session ID of the Reply To recipient. + * A <code>String</code> object that represents the session ID of + * the Reply To recipient. * - * @return A <code>Message</code> object that represents the updated message. + * @return A <code>Message</code> object that represents the updated + * message. */ public BrokeredMessage setReplyToSessionId(String replyToSessionId) { brokerProperties.setReplyToSessionId(replyToSessionId); @@ -438,7 +474,8 @@ public BrokeredMessage setReplyToSessionId(String replyToSessionId) { /** * Returns the message location. * - * @return A <code>String</code> object that represents the message location. + * @return A <code>String</code> object that represents the message + * location. */ public String getMessageLocation() { return brokerProperties.getMessageLocation(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateQueueResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateQueueResult.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateQueueResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateQueueResult.java index 8b0a7eceb6c7d..5bcf3f6174af1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateQueueResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateQueueResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>createQueue</code> operation. @@ -25,7 +25,8 @@ public class CreateQueueResult { * Creates an instance of the <code>CreateQueueResult</code> class. * * @param value - * A {@link QueueInfo} object assigned as the value of the result. + * A {@link QueueInfo} object assigned as the value of the + * result. */ public CreateQueueResult(QueueInfo value) { this.setValue(value); @@ -35,7 +36,8 @@ public CreateQueueResult(QueueInfo value) { * Specfies the value of the result. * * @param value - * A {@link QueueInfo} object assigned as the value of the result. + * A {@link QueueInfo} object assigned as the value of the + * result. */ public void setValue(QueueInfo value) { this.value = value; @@ -44,7 +46,8 @@ public void setValue(QueueInfo value) { /** * Returns the value of the result. * - * @return A {@link QueueInfo} object that represents the value of the result. + * @return A {@link QueueInfo} object that represents the value of the + * result. */ public QueueInfo getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateRuleResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateRuleResult.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateRuleResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateRuleResult.java index bc72c6da29025..ecba91120bc51 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateRuleResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateRuleResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>createRule</code> operation. @@ -44,7 +44,8 @@ public void setValue(RuleInfo value) { /** * Returns the value of the result. * - * @return A {@link RuleInfo} object that represents the value of the result. + * @return A {@link RuleInfo} object that represents the value of the + * result. */ public RuleInfo getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateSubscriptionResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateSubscriptionResult.java similarity index 91% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateSubscriptionResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateSubscriptionResult.java index 1580bc79005a8..de4e91357596d 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateSubscriptionResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateSubscriptionResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>createSubscription</code> operation. @@ -25,7 +25,8 @@ public class CreateSubscriptionResult { * Creates an instance of the <code>CreateSubscriptionResult</code> class. * * @param value - * A {@link SubscriptionInfo} object assigned as the value of the result. + * A {@link SubscriptionInfo} object assigned as the value of the + * result. */ public CreateSubscriptionResult(SubscriptionInfo value) { this.setValue(value); @@ -45,7 +46,8 @@ public void setValue(SubscriptionInfo value) { /** * Returns the value of the result. * - * @return A {@link SubscriptionInfo} object that represents the value of the result. + * @return A {@link SubscriptionInfo} object that represents the value of + * the result. */ public SubscriptionInfo getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateTopicResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateTopicResult.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateTopicResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateTopicResult.java index 8c0baaca9afeb..21fd291197da1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/CreateTopicResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/CreateTopicResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>createTopic</code> operation. @@ -25,7 +25,8 @@ public class CreateTopicResult { * Creates an instance of the <code>CreateTopicResult</code> class. * * @param value - * A {@link TopicInfo} object assigned as the value of the result. + * A {@link TopicInfo} object assigned as the value of the + * result. */ public CreateTopicResult(TopicInfo value) { this.setValue(value); @@ -35,7 +36,8 @@ public CreateTopicResult(TopicInfo value) { * Specfies the value of the result. * * @param value - * A {@link TopicInfo} object assigned as the value of the result. + * A {@link TopicInfo} object assigned as the value of the + * result. */ public void setValue(TopicInfo value) { this.value = value; @@ -44,7 +46,8 @@ public void setValue(TopicInfo value) { /** * Returns the value of the result. * - * @return A {@link TopicInfo} object that represents the value of the result. + * @return A {@link TopicInfo} object that represents the value of the + * result. */ public TopicInfo getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetQueueResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetQueueResult.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetQueueResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetQueueResult.java index 0fff663cc9653..d1c6ecce03edc 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetQueueResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetQueueResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>getQueue</code> operation. @@ -25,7 +25,8 @@ public class GetQueueResult { * Creates an instance of the <code>GetQueueResult</code> class. * * @param value - * A {@link QueueInfo} object assigned as the value of the result. + * A {@link QueueInfo} object assigned as the value of the + * result. */ public GetQueueResult(QueueInfo value) { this.setValue(value); @@ -35,7 +36,8 @@ public GetQueueResult(QueueInfo value) { * Specfies the value of the result. * * @param value - * A {@link QueueInfo} object assigned as the value of the result. + * A {@link QueueInfo} object assigned as the value of the + * result. */ public void setValue(QueueInfo value) { this.value = value; @@ -44,7 +46,8 @@ public void setValue(QueueInfo value) { /** * Returns the value of the result. * - * @return A {@link QueueInfo} object that represents the value of the result. + * @return A {@link QueueInfo} object that represents the value of the + * result. */ public QueueInfo getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetRuleResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetRuleResult.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetRuleResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetRuleResult.java index c940040fc064e..dd721d5083d8a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetRuleResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetRuleResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>getRule</code> operation. @@ -44,7 +44,8 @@ public void setValue(RuleInfo value) { /** * Returns the value of the result. * - * @return A {@link RuleInfo} object that represents the value of the result. + * @return A {@link RuleInfo} object that represents the value of the + * result. */ public RuleInfo getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetSubscriptionResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetSubscriptionResult.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetSubscriptionResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetSubscriptionResult.java index ff8f5ee9e471f..23a43936f124b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetSubscriptionResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetSubscriptionResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>getSubscription</code> operation. @@ -46,8 +46,8 @@ public void setValue(SubscriptionInfo value) { /** * Returns the value of the result. * - * @return A {@link SubscriptionInfo} object that represents the value of the - * result. + * @return A {@link SubscriptionInfo} object that represents the value of + * the result. */ public SubscriptionInfo getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetTopicResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetTopicResult.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetTopicResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetTopicResult.java index 2254759074403..0fe2114b801c6 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/GetTopicResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/GetTopicResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>getTopic</code> operation. @@ -25,7 +25,8 @@ public class GetTopicResult { * Creates an instance of the <code>GetTopicResult</code> class. * * @param value - * A {@link TopicInfo} object assigned as the value of the result. + * A {@link TopicInfo} object assigned as the value of the + * result. */ public GetTopicResult(TopicInfo value) { this.setValue(value); @@ -35,7 +36,8 @@ public GetTopicResult(TopicInfo value) { * Specfies the value of the result. * * @param value - * A {@link TopicInfo} object assigned as the value of the result. + * A {@link TopicInfo} object assigned as the value of the + * result. */ public void setValue(TopicInfo value) { this.value = value; @@ -44,7 +46,8 @@ public void setValue(TopicInfo value) { /** * Returns the value of the result. * - * @return A {@link TopicInfo} object that represents the value of the result. + * @return A {@link TopicInfo} object that represents the value of the + * result. */ public TopicInfo getValue() { return value; diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListQueuesOptions.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListQueuesOptions.java new file mode 100644 index 0000000000000..dbf3394ae1311 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListQueuesOptions.java @@ -0,0 +1,19 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.models; + +public class ListQueuesOptions extends AbstractListOptions<ListQueuesOptions> { + public static final ListQueuesOptions DEFAULT = new ListQueuesOptions(); +} diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListQueuesResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListQueuesResult.java new file mode 100644 index 0000000000000..76a28ca3d2436 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListQueuesResult.java @@ -0,0 +1,46 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.models; + +import java.util.List; + +/** + * Represents the result of a <code>listQueues</code> operation. + */ +public class ListQueuesResult { + + private List<QueueInfo> items; + + /** + * Returns the items in the result list. + * + * @return A <code>List</code> of {@link QueueInfo} objects that represent + * the items in the result list. + */ + public List<QueueInfo> getItems() { + return items; + } + + /** + * Specfies the items in the result list. + * + * @param items + * A <code>List</code> object that contains the {@link QueueInfo} + * objects assigned as the value of the result. + */ + public void setItems(List<QueueInfo> items) { + this.items = items; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListRulesOptions.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListRulesOptions.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListRulesOptions.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListRulesOptions.java index 0e7beca7478ca..bc4354193c9c4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListRulesOptions.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListRulesOptions.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; public class ListRulesOptions extends AbstractListOptions<ListRulesOptions> { public static final ListRulesOptions DEFAULT = new ListRulesOptions(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListRulesResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListRulesResult.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListRulesResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListRulesResult.java index 3b08d444b95d4..0a96217da7de1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListRulesResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListRulesResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.util.List; @@ -26,8 +26,8 @@ public class ListRulesResult { /** * Returns the items in the result list. * - * @return A <code>List</code> of {@link RuleInfo} objects that represent the - * items in the result list. + * @return A <code>List</code> of {@link RuleInfo} objects that represent + * the items in the result list. */ public List<RuleInfo> getItems() { return items; @@ -37,8 +37,8 @@ public List<RuleInfo> getItems() { * Specifies the items in the result list. * * @param items - * A <code>List</code> object that contains the {@link RuleInfo} objects assigned as the value of the - * result. + * A <code>List</code> object that contains the {@link RuleInfo} + * objects assigned as the value of the result. */ public void setItems(List<RuleInfo> items) { this.items = items; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListSubscriptionsOptions.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListSubscriptionsOptions.java similarity index 80% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListSubscriptionsOptions.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListSubscriptionsOptions.java index c9c2efbbedb70..08427c8b9a8b7 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListSubscriptionsOptions.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListSubscriptionsOptions.java @@ -12,8 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; -public class ListSubscriptionsOptions extends AbstractListOptions<ListSubscriptionsOptions> { +public class ListSubscriptionsOptions extends + AbstractListOptions<ListSubscriptionsOptions> { public static final ListSubscriptionsOptions DEFAULT = new ListSubscriptionsOptions(); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListSubscriptionsResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListSubscriptionsResult.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListSubscriptionsResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListSubscriptionsResult.java index 14dbbff145451..1e69272f0b579 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListSubscriptionsResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListSubscriptionsResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.util.List; @@ -26,8 +26,8 @@ public class ListSubscriptionsResult { /** * Returns the items in the result list. * - * @return A <code>List</code> of {@link SubscriptionInfo} objects that represent the - * items in the result list. + * @return A <code>List</code> of {@link SubscriptionInfo} objects that + * represent the items in the result list. */ public List<SubscriptionInfo> getItems() { return items; @@ -37,8 +37,9 @@ public List<SubscriptionInfo> getItems() { * Specifies the items in the result list. * * @param items - * A <code>List</code> object that contains the {@link SubscriptionInfo} objects assigned as the value of - * the result. + * A <code>List</code> object that contains the + * {@link SubscriptionInfo} objects assigned as the value of the + * result. */ public void setItems(List<SubscriptionInfo> items) { this.items = items; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListTopicsOptions.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListTopicsOptions.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListTopicsOptions.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListTopicsOptions.java index 9363c7a902664..810b0226982f4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListTopicsOptions.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListTopicsOptions.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; public class ListTopicsOptions extends AbstractListOptions<ListTopicsOptions> { public static final ListTopicsOptions DEFAULT = new ListTopicsOptions(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListTopicsResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListTopicsResult.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListTopicsResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListTopicsResult.java index e43a27ccd8143..387e21bd28c1c 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ListTopicsResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ListTopicsResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.util.List; @@ -26,8 +26,8 @@ public class ListTopicsResult { /** * Returns the items in the result list. * - * @return A <code>List</code> of {@link TopicInfo} objects that represent the - * items in the result list. + * @return A <code>List</code> of {@link TopicInfo} objects that represent + * the items in the result list. */ public List<TopicInfo> getItems() { return items; @@ -37,8 +37,8 @@ public List<TopicInfo> getItems() { * Specifies the items in the result list. * * @param items - * A <code>List</code> object that contains the {@link TopicInfo} objects assigned as the value of the - * result. + * A <code>List</code> object that contains the {@link TopicInfo} + * objects assigned as the value of the result. */ public void setItems(List<TopicInfo> items) { this.items = items; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/QueueInfo.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/QueueInfo.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/QueueInfo.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/QueueInfo.java index d0600c19ec43f..50ed881877736 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/QueueInfo.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/QueueInfo.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.net.URI; import java.util.Calendar; @@ -20,14 +20,14 @@ import javax.ws.rs.core.MediaType; import javax.xml.datatype.Duration; -import com.microsoft.windowsazure.services.serviceBus.implementation.Content; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityAvailabilityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.Entry; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntryModel; -import com.microsoft.windowsazure.services.serviceBus.implementation.MessageCountDetails; -import com.microsoft.windowsazure.services.serviceBus.implementation.PartitioningPolicy; -import com.microsoft.windowsazure.services.serviceBus.implementation.QueueDescription; +import com.microsoft.windowsazure.services.servicebus.implementation.Content; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityAvailabilityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.Entry; +import com.microsoft.windowsazure.services.servicebus.implementation.EntryModel; +import com.microsoft.windowsazure.services.servicebus.implementation.MessageCountDetails; +import com.microsoft.windowsazure.services.servicebus.implementation.PartitioningPolicy; +import com.microsoft.windowsazure.services.servicebus.implementation.QueueDescription; /** * Represents a queue. @@ -45,7 +45,8 @@ public QueueInfo() { } /** - * Creates an instance of the <code>QueueInfo</code> class using the specified entry. + * Creates an instance of the <code>QueueInfo</code> class using the + * specified entry. * * @param entry * An <code>Entry</code> object. @@ -55,10 +56,12 @@ public QueueInfo(Entry entry) { } /** - * Creates an instance of the <code>QueueInfo</code> class using the specified name. + * Creates an instance of the <code>QueueInfo</code> class using the + * specified name. * * @param path - * A <code>String</code> object that represents the name of the queue. + * A <code>String</code> object that represents the name of the + * queue. */ public QueueInfo(String path) { this(); @@ -68,7 +71,8 @@ public QueueInfo(String path) { /** * Returns the name of the queue. * - * @return A <code>String</code> object that represents the name of the queue. + * @return A <code>String</code> object that represents the name of the + * queue. */ public String getPath() { return getEntry().getTitle(); @@ -80,7 +84,8 @@ public String getPath() { * @param value * A <code>String</code> that represents the name of the queue. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setPath(String value) { getEntry().setTitle(value); @@ -90,7 +95,8 @@ public QueueInfo setPath(String value) { /** * Returns the duration of the lock. * - * @return A <code>Duration</code> object that represents the duration of the lock. + * @return A <code>Duration</code> object that represents the duration of + * the lock. */ public Duration getLockDuration() { return getModel().getLockDuration(); @@ -102,7 +108,8 @@ public Duration getLockDuration() { * @param value * The duration, in seconds, of the lock. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setLockDuration(Duration value) { getModel().setLockDuration(value); @@ -124,7 +131,8 @@ public Long getMaxSizeInMegabytes() { * @param value * The maximum size, in megabytes, of the queue. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setMaxSizeInMegabytes(Long value) { getModel().setMaxSizeInMegabytes(value); @@ -134,7 +142,8 @@ public QueueInfo setMaxSizeInMegabytes(Long value) { /** * Indicates whether duplicate message detection is required. * - * @return <code>true</code> if duplicate message detection is required; otherwise, <code>false</code>. + * @return <code>true</code> if duplicate message detection is required; + * otherwise, <code>false</code>. */ public Boolean isRequiresDuplicateDetection() { return getModel().isRequiresDuplicateDetection(); @@ -144,9 +153,11 @@ public Boolean isRequiresDuplicateDetection() { * Specifies whether duplicate message detection is required. * * @param value - * <code>true</code> if duplicate message detection is required; otherwise, <code>false</code>. + * <code>true</code> if duplicate message detection is required; + * otherwise, <code>false</code>. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setRequiresDuplicateDetection(Boolean value) { getModel().setRequiresDuplicateDetection(value); @@ -156,7 +167,8 @@ public QueueInfo setRequiresDuplicateDetection(Boolean value) { /** * Indicates whether the queue is session-aware. * - * @return <code>true</code> if the queue is session aware; otherwise, <code>false</code>. + * @return <code>true</code> if the queue is session aware; otherwise, + * <code>false</code>. */ public Boolean isRequiresSession() { return getModel().isRequiresSession(); @@ -166,9 +178,11 @@ public Boolean isRequiresSession() { * Specifies whether the queue is session-aware. * * @param value - * <code>true</code> if the queue is session aware; otherwise, <code>false</code>. + * <code>true</code> if the queue is session aware; otherwise, + * <code>false</code>. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setRequiresSession(Boolean value) { getModel().setRequiresSession(value); @@ -179,19 +193,23 @@ public QueueInfo setRequiresSession(Boolean value) { * Returns the default message time-to-live (TTL). This applies when dead * lettering is in effect. * - * @return A <code>Duration</code> object that represents the default message TTL. + * @return A <code>Duration</code> object that represents the default + * message TTL. */ public Duration getDefaultMessageTimeToLive() { return getModel().getDefaultMessageTimeToLive(); } /** - * Sets the default message time-to-live (TTL). This applies when dead lettering is in effect. + * Sets the default message time-to-live (TTL). This applies when dead + * lettering is in effect. * * @param value - * A <code>Duration</code> object that represents the default message TTL. + * A <code>Duration</code> object that represents the default + * message TTL. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setDefaultMessageTimeToLive(Duration value) { getModel().setDefaultMessageTimeToLive(value); @@ -201,7 +219,8 @@ public QueueInfo setDefaultMessageTimeToLive(Duration value) { /** * Gets the time span before auto deletion starts. * - * @return A <code>Duration</code> object that represents the time span before auto deletion. + * @return A <code>Duration</code> object that represents the time span + * before auto deletion. */ public Duration getAutoDeleteOnIdle() { return getModel().getAutoDeleteOnIdle(); @@ -211,8 +230,10 @@ public Duration getAutoDeleteOnIdle() { * Sets the time span before auto deletion starts. * * @param autoDeleteOnIdle - * A <code>Duration</code> object that represents the time span before auto deletion starts. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * A <code>Duration</code> object that represents the time span + * before auto deletion starts. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setAutoDeleteOnIdle(Duration autoDeleteOnIdle) { getModel().setAutoDeleteOnIdle(autoDeleteOnIdle); @@ -222,7 +243,8 @@ public QueueInfo setAutoDeleteOnIdle(Duration autoDeleteOnIdle) { /** * Indicates whether dead lettering is in effect upon message expiration. * - * @return <code>true</code> if dead lettering is in effect; otherwise, <code>false</code>. + * @return <code>true</code> if dead lettering is in effect; otherwise, + * <code>false</code>. */ public Boolean isDeadLetteringOnMessageExpiration() { return getModel().isDeadLetteringOnMessageExpiration(); @@ -232,9 +254,11 @@ public Boolean isDeadLetteringOnMessageExpiration() { * Specifies whether dead lettering is in effect upon message expiration. * * @param value - * <code>true</code> if dead lettering is in effect; otherwise, <code>false</code>. + * <code>true</code> if dead lettering is in effect; otherwise, + * <code>false</code>. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setDeadLetteringOnMessageExpiration(Boolean value) { getModel().setDeadLetteringOnMessageExpiration(value); @@ -242,8 +266,8 @@ public QueueInfo setDeadLetteringOnMessageExpiration(Boolean value) { } /** - * Returns the time span during which the service bus will detect message duplication. This applies when duplicate - * message detection is in effect. + * Returns the time span during which the service bus will detect message + * duplication. This applies when duplicate message detection is in effect. * * @return A <code>Duration</code> object that represents the time span for * detecting message duplication. @@ -253,13 +277,15 @@ public Duration getDuplicateDetectionHistoryTimeWindow() { } /** - * Sets the time span during which the service bus will detect message duplication. This applies when duplicate - * message detection is in effect. + * Sets the time span during which the service bus will detect message + * duplication. This applies when duplicate message detection is in effect. * * @param value - * A <code>Duration</code> object that represents the time span for detecting message duplication. + * A <code>Duration</code> object that represents the time span + * for detecting message duplication. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setDuplicateDetectionHistoryTimeWindow(Duration value) { getModel().setDuplicateDetectionHistoryTimeWindow(value); @@ -269,7 +295,8 @@ public QueueInfo setDuplicateDetectionHistoryTimeWindow(Duration value) { /** * Returns the maximum delivery count for the queue. * - * @return An <code>Integer</code> object that represents the maximum delivery count. + * @return An <code>Integer</code> object that represents the maximum + * delivery count. */ public Integer getMaxDeliveryCount() { return getModel().getMaxDeliveryCount(); @@ -281,7 +308,8 @@ public Integer getMaxDeliveryCount() { * @param value * The maximum delivery count for the queue. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setMaxDeliveryCount(Integer value) { getModel().setMaxDeliveryCount(value); @@ -291,7 +319,8 @@ public QueueInfo setMaxDeliveryCount(Integer value) { /** * Indicates whether batch operations are enabled. * - * @return <code>true</code> if batch operations are enabled; otherwise, <code>false</code>. + * @return <code>true</code> if batch operations are enabled; otherwise, + * <code>false</code>. */ public Boolean isEnableBatchedOperations() { return getModel().isEnableBatchedOperations(); @@ -301,9 +330,11 @@ public Boolean isEnableBatchedOperations() { * Specifies whether batch operations are enabled. * * @param value - * <code>true</code> if batch operations are enabled; otherwise, <code>false</code>. + * <code>true</code> if batch operations are enabled; otherwise, + * <code>false</code>. * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setEnableBatchedOperations(Boolean value) { getModel().setEnableBatchedOperations(value); @@ -313,7 +344,8 @@ public QueueInfo setEnableBatchedOperations(Boolean value) { /** * Returns the size of the queue. * - * @return A <code>Long</code> object that represents the size of the queue in bytes. + * @return A <code>Long</code> object that represents the size of the queue + * in bytes. */ public Long getSizeInBytes() { return getModel().getSizeInBytes(); @@ -324,7 +356,8 @@ public Long getSizeInBytes() { * * @param sizeInBytes * the size in bytes - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setSizeInBytes(Long sizeInBytes) { getModel().setSizeInBytes(sizeInBytes); @@ -334,7 +367,8 @@ public QueueInfo setSizeInBytes(Long sizeInBytes) { /** * Returns the number of messages in the queue. * - * @return A <code>Long</code> object that represents the number of messages in the queue. + * @return A <code>Long</code> object that represents the number of messages + * in the queue. */ public Long getMessageCount() { return getModel().getMessageCount(); @@ -345,7 +379,8 @@ public Long getMessageCount() { * * @param messageCount * the message count - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setMessageCount(Long messageCount) { getModel().setMessageCount(messageCount); @@ -355,7 +390,8 @@ public QueueInfo setMessageCount(Long messageCount) { /** * Checks if is anonymous accessible. * - * @return <code>true</code> if the queue can be accessed anonymously. Otherwise, <code>false</code>. + * @return <code>true</code> if the queue can be accessed anonymously. + * Otherwise, <code>false</code>. */ public Boolean isAnonymousAccessible() { return getModel().isIsAnonymousAccessible(); @@ -366,7 +402,8 @@ public Boolean isAnonymousAccessible() { * * @param isAnonymousAccessible * the is anonymous accessible - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setIsAnonymousAccessible(Boolean isAnonymousAccessible) { getModel().setIsAnonymousAccessible(isAnonymousAccessible); @@ -376,7 +413,8 @@ public QueueInfo setIsAnonymousAccessible(Boolean isAnonymousAccessible) { /** * Checks if is support ordering. * - * @return <code>true</code> if ordering is supported, otherwise, <code>false</code>. + * @return <code>true</code> if ordering is supported, otherwise, + * <code>false</code>. */ public Boolean isSupportOrdering() { return getModel().isSupportOrdering(); @@ -386,8 +424,10 @@ public Boolean isSupportOrdering() { * Sets the support ordering. * * @param supportOrdering - * A <code>Boolean</code> object represents whether the queue supports ordering. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * A <code>Boolean</code> object represents whether the queue + * supports ordering. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setSupportOrdering(Boolean supportOrdering) { getModel().setSupportOrdering(supportOrdering); @@ -408,7 +448,8 @@ public EntityStatus getStatus() { * * @param entityStatus * the entity status - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setStatus(EntityStatus entityStatus) { getModel().setStatus(entityStatus); @@ -418,7 +459,8 @@ public QueueInfo setStatus(EntityStatus entityStatus) { /** * Gets the entity availability status. * - * @return A <code>EntityAvailabilityStatus</code> object which represents the availability status of the entity. + * @return A <code>EntityAvailabilityStatus</code> object which represents + * the availability status of the entity. */ public EntityAvailabilityStatus getEntityAvailabilityStatus() { return getModel().getEntityAvailabilityStatus(); @@ -429,9 +471,11 @@ public EntityAvailabilityStatus getEntityAvailabilityStatus() { * * @param entityAvailabilityStatus * A <code>EntityAvailabilityStatus</code> object. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ - public QueueInfo setEntityAvailabilityStatus(EntityAvailabilityStatus entityAvailabilityStatus) { + public QueueInfo setEntityAvailabilityStatus( + EntityAvailabilityStatus entityAvailabilityStatus) { getModel().setEntityAvailabilityStatus(entityAvailabilityStatus); return this; } @@ -439,7 +483,8 @@ public QueueInfo setEntityAvailabilityStatus(EntityAvailabilityStatus entityAvai /** * Gets the created at. * - * @return A <code>Calendar</code> object which represents the time of the queue created at. + * @return A <code>Calendar</code> object which represents the time of the + * queue created at. */ public Calendar getCreatedAt() { return getModel().getCreatedAt(); @@ -449,8 +494,10 @@ public Calendar getCreatedAt() { * Sets the created at. * * @param createdAt - * A <code>Calendar</code> ojbect which represnets the time of the queue created at. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * A <code>Calendar</code> ojbect which represnets the time of + * the queue created at. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setCreatedAt(Calendar createdAt) { getModel().setCreatedAt(createdAt); @@ -460,7 +507,8 @@ public QueueInfo setCreatedAt(Calendar createdAt) { /** * Gets the updated at. * - * @return A <code>Calendar</code> object which represents the time that the queue was updated at. + * @return A <code>Calendar</code> object which represents the time that the + * queue was updated at. */ public Calendar getUpdatedAt() { return getModel().getUpdatedAt(); @@ -470,8 +518,10 @@ public Calendar getUpdatedAt() { * Sets the updated at. * * @param updatedAt - * A <code>Calendar</code> object which represents the time that the queue was updated at. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * A <code>Calendar</code> object which represents the time that + * the queue was updated at. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setUpdatedAt(Calendar updatedAt) { getModel().setUpdatedAt(updatedAt); @@ -481,7 +531,8 @@ public QueueInfo setUpdatedAt(Calendar updatedAt) { /** * Gets the accessed at. * - * @return A <code>Calendar</code> object which represents the time that the queue was accessed at. + * @return A <code>Calendar</code> object which represents the time that the + * queue was accessed at. */ public Calendar getAccessedAt() { return getModel().getAccessedAt(); @@ -491,8 +542,10 @@ public Calendar getAccessedAt() { * Sets the accessed at. * * @param accessedAt - * A <code>Calendar</code> object which represents the time that the queue was accessed at. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * A <code>Calendar</code> object which represents the time that + * the queue was accessed at. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setAccessedAt(Calendar accessedAt) { getModel().setAccessedAt(accessedAt); @@ -502,7 +555,8 @@ public QueueInfo setAccessedAt(Calendar accessedAt) { /** * Gets the partitioning policy. * - * @return A <code>PartitioningPolicy</code> represents the partitioning policy. + * @return A <code>PartitioningPolicy</code> represents the partitioning + * policy. */ public PartitioningPolicy getPartitioningPolicy() { return getModel().getPartitioningPolicy(); @@ -512,8 +566,10 @@ public PartitioningPolicy getPartitioningPolicy() { * Sets the partitioning policy. * * @param partitioningPolicy - * A <code>PartitioningPolicy</code> represents the partitioning policy. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * A <code>PartitioningPolicy</code> represents the partitioning + * policy. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setPartitioningPolicy(PartitioningPolicy partitioningPolicy) { getModel().setPartitioningPolicy(partitioningPolicy); @@ -533,8 +589,10 @@ public String getUserMetadata() { * Sets the user metadata. * * @param userMetadata - * A <code>String</code> objects which contains the user metadata. - * @return A <code>QueueInfo</code> object that represents the updated queue. + * A <code>String</code> objects which contains the user + * metadata. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setUserMetadata(String userMetadata) { getModel().setUserMetadata(userMetadata); @@ -544,7 +602,8 @@ public QueueInfo setUserMetadata(String userMetadata) { /** * Gets the message count details. * - * @return A <code>MessageCountDetails</code> instance that represents the details of the message count. + * @return A <code>MessageCountDetails</code> instance that represents the + * details of the message count. */ public MessageCountDetails getCountDetails() { return getModel().getCountDetails(); @@ -556,7 +615,8 @@ public MessageCountDetails getCountDetails() { * @param uri * the URI of the <code>QueueInfo</code> * - * @return A <code>QueueInfo</code> object that represents the updated queue. + * @return A <code>QueueInfo</code> object that represents the updated + * queue. */ public QueueInfo setUri(URI uri) { getEntry().setId(uri.toString()); @@ -588,8 +648,10 @@ private String removeQueryString(String uri) { * Sets the URI of the entity to forward to. * * @param forwardTo - * A <code>String</code> instance representing the URI of the entity to forward message to. - * @return A <code>QueueInfo</code> instance representing the updated queue information. + * A <code>String</code> instance representing the URI of the + * entity to forward message to. + * @return A <code>QueueInfo</code> instance representing the updated queue + * information. */ public QueueInfo setForwardTo(String forwardTo) { getModel().setForwardTo(forwardTo); @@ -599,7 +661,8 @@ public QueueInfo setForwardTo(String forwardTo) { /** * Gets a <code>String</code> instance representing entity to forward to. * - * @return A <code>String</code> instance representing the URI of the instance to forward to. + * @return A <code>String</code> instance representing the URI of the + * instance to forward to. */ public String getForwardTo() { return getModel().getForwardTo(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMessageOptions.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMessageOptions.java similarity index 83% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMessageOptions.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMessageOptions.java index 3e304ad343306..2603e00aff307 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMessageOptions.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMessageOptions.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * @@ -20,7 +20,7 @@ * */ public class ReceiveMessageOptions { - Integer timeout; + private Integer timeout; private ReceiveMode receiveMode = ReceiveMode.RECEIVE_AND_DELETE; /** @@ -43,7 +43,8 @@ public Integer getTimeout() { * @param timeout * The timeout, in seconds. * - * @return A <code>ReceiveMessageOptions</code> object that represents the updated receive message options. + * @return A <code>ReceiveMessageOptions</code> object that represents the + * updated receive message options. */ public ReceiveMessageOptions setTimeout(Integer timeout) { this.timeout = timeout; @@ -65,7 +66,8 @@ public ReceiveMode getReceiveMode() { * @param receiveMode * A {@link ReceiveMode} value that specifies the receive mode. * - * @return A <code>ReceiveMessageOptions</code> object that represents the updated receive message options. + * @return A <code>ReceiveMessageOptions</code> object that represents the + * updated receive message options. */ public ReceiveMessageOptions setReceiveMode(ReceiveMode receiveMode) { this.receiveMode = receiveMode; @@ -75,7 +77,8 @@ public ReceiveMessageOptions setReceiveMode(ReceiveMode receiveMode) { /** * Indicates whether the receive mode is receive and delete. * - * @return <code>true</code> if the receive mode is {@link ReceiveMode#RECEIVE_AND_DELETE}; otherwise, + * @return <code>true</code> if the receive mode is + * {@link ReceiveMode#RECEIVE_AND_DELETE}; otherwise, * <code>false</code>. */ public boolean isReceiveAndDelete() { @@ -85,7 +88,8 @@ public boolean isReceiveAndDelete() { /** * Sets the receive mode to receive and delete. * - * @return A <code>ReceiveMessageOptions</code> object that represents the updated receive message options. + * @return A <code>ReceiveMessageOptions</code> object that represents the + * updated receive message options. */ public ReceiveMessageOptions setReceiveAndDelete() { this.receiveMode = ReceiveMode.RECEIVE_AND_DELETE; @@ -95,7 +99,8 @@ public ReceiveMessageOptions setReceiveAndDelete() { /** * Indicates whether the receive mode is peek/lock. * - * @return <code>true</code> if the receive mode is {@link ReceiveMode#PEEK_LOCK}; otherwise, <code>false</code>. + * @return <code>true</code> if the receive mode is + * {@link ReceiveMode#PEEK_LOCK}; otherwise, <code>false</code>. */ public boolean isPeekLock() { return receiveMode == ReceiveMode.PEEK_LOCK; @@ -104,7 +109,8 @@ public boolean isPeekLock() { /** * Sets the receive mode to peek/lock. * - * @return A <code>ReceiveMessageOptions</code> object that represents the updated receive message options. + * @return A <code>ReceiveMessageOptions</code> object that represents the + * updated receive message options. */ public ReceiveMessageOptions setPeekLock() { this.receiveMode = ReceiveMode.PEEK_LOCK; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMessageResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMessageResult.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMessageResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMessageResult.java index 7c092119e52f2..0f58653ad8a6b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMessageResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMessageResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>receiveMessage</code> operation. @@ -25,7 +25,8 @@ public class ReceiveMessageResult { * Creates an instance of the <code>ReceiveQueueMessageResult</code> class. * * @param value - * A {@link BrokeredMessage} object assigned as the value of the result. + * A {@link BrokeredMessage} object assigned as the value of the + * result. */ public ReceiveMessageResult(BrokeredMessage value) { this.setValue(value); @@ -35,7 +36,8 @@ public ReceiveMessageResult(BrokeredMessage value) { * Specifies the value of the result. * * @param value - * A {@link BrokeredMessage} object assigned as the value of the result. + * A {@link BrokeredMessage} object assigned as the value of the + * result. */ public void setValue(BrokeredMessage value) { this.value = value; @@ -44,7 +46,8 @@ public void setValue(BrokeredMessage value) { /** * Returns the value of the result. * - * @return A {@link BrokeredMessage} object that represents the value of the result. + * @return A {@link BrokeredMessage} object that represents the value of the + * result. */ public BrokeredMessage getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMode.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMode.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMode.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMode.java index 67e2f3bfc9c3c..66dd4de414e8d 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveMode.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveMode.java @@ -12,15 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Specifies the mode when a message is received. */ public enum ReceiveMode { /** - * The message is retrieved and locked for processing, until either the receiver deletes the message, unlocks it, or - * the lock duration expires. + * The message is retrieved and locked for processing, until either the + * receiver deletes the message, unlocks it, or the lock duration expires. */ PEEK_LOCK, /** diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveQueueMessageResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveQueueMessageResult.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveQueueMessageResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveQueueMessageResult.java index 5a5185491d4cd..f5444438d0fd7 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveQueueMessageResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveQueueMessageResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>receiveQueueMessage</code> operation. @@ -25,7 +25,8 @@ public class ReceiveQueueMessageResult { * Creates an instance of the <code>ReceiveQueueMessageResult</code> class. * * @param value - * A {@link BrokeredMessage} object assigned as the value of the result. + * A {@link BrokeredMessage} object assigned as the value of the + * result. */ public ReceiveQueueMessageResult(BrokeredMessage value) { this.setValue(value); @@ -35,7 +36,8 @@ public ReceiveQueueMessageResult(BrokeredMessage value) { * Specifies the value of the result. * * @param value - * A {@link BrokeredMessage} object assigned as the value of the result. + * A {@link BrokeredMessage} object assigned as the value of the + * result. */ public void setValue(BrokeredMessage value) { this.value = value; @@ -44,7 +46,8 @@ public void setValue(BrokeredMessage value) { /** * Returns the value of the result. * - * @return A {@link BrokeredMessage} object that represents the value of the result. + * @return A {@link BrokeredMessage} object that represents the value of the + * result. */ public BrokeredMessage getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveSubscriptionMessageResult.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveSubscriptionMessageResult.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveSubscriptionMessageResult.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveSubscriptionMessageResult.java index 4d32488b6e399..30710128c1c9b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/ReceiveSubscriptionMessageResult.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/ReceiveSubscriptionMessageResult.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; /** * Represents the result of a <code>receiveSubscriptionMessage</code> operation. @@ -22,10 +22,12 @@ public class ReceiveSubscriptionMessageResult { private BrokeredMessage value; /** - * Creates an instance of the <code>ReceiveSubscriptionMessageResult</code> class. + * Creates an instance of the <code>ReceiveSubscriptionMessageResult</code> + * class. * * @param value - * A {@link BrokeredMessage} object assigned as the value of the result. + * A {@link BrokeredMessage} object assigned as the value of the + * result. */ public ReceiveSubscriptionMessageResult(BrokeredMessage value) { this.setValue(value); @@ -35,7 +37,8 @@ public ReceiveSubscriptionMessageResult(BrokeredMessage value) { * Specifies the value of the result. * * @param value - * A {@link BrokeredMessage} object assigned as the value of the result. + * A {@link BrokeredMessage} object assigned as the value of the + * result. */ public void setValue(BrokeredMessage value) { this.value = value; @@ -44,7 +47,8 @@ public void setValue(BrokeredMessage value) { /** * Returns the value of the result. * - * @return A {@link BrokeredMessage} object that represents the value of the result. + * @return A {@link BrokeredMessage} object that represents the value of the + * result. */ public BrokeredMessage getValue() { return value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/RuleInfo.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/RuleInfo.java similarity index 83% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/RuleInfo.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/RuleInfo.java index bfd82d1d29f87..068c20a3384d0 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/RuleInfo.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/RuleInfo.java @@ -12,24 +12,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.util.Calendar; import javax.ws.rs.core.MediaType; -import com.microsoft.windowsazure.services.serviceBus.implementation.Content; -import com.microsoft.windowsazure.services.serviceBus.implementation.CorrelationFilter; -import com.microsoft.windowsazure.services.serviceBus.implementation.EmptyRuleAction; -import com.microsoft.windowsazure.services.serviceBus.implementation.Entry; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntryModel; -import com.microsoft.windowsazure.services.serviceBus.implementation.FalseFilter; -import com.microsoft.windowsazure.services.serviceBus.implementation.Filter; -import com.microsoft.windowsazure.services.serviceBus.implementation.RuleAction; -import com.microsoft.windowsazure.services.serviceBus.implementation.RuleDescription; -import com.microsoft.windowsazure.services.serviceBus.implementation.SqlFilter; -import com.microsoft.windowsazure.services.serviceBus.implementation.SqlRuleAction; -import com.microsoft.windowsazure.services.serviceBus.implementation.TrueFilter; +import com.microsoft.windowsazure.services.servicebus.implementation.Content; +import com.microsoft.windowsazure.services.servicebus.implementation.CorrelationFilter; +import com.microsoft.windowsazure.services.servicebus.implementation.EmptyRuleAction; +import com.microsoft.windowsazure.services.servicebus.implementation.Entry; +import com.microsoft.windowsazure.services.servicebus.implementation.EntryModel; +import com.microsoft.windowsazure.services.servicebus.implementation.FalseFilter; +import com.microsoft.windowsazure.services.servicebus.implementation.Filter; +import com.microsoft.windowsazure.services.servicebus.implementation.RuleAction; +import com.microsoft.windowsazure.services.servicebus.implementation.RuleDescription; +import com.microsoft.windowsazure.services.servicebus.implementation.SqlFilter; +import com.microsoft.windowsazure.services.servicebus.implementation.SqlRuleAction; +import com.microsoft.windowsazure.services.servicebus.implementation.TrueFilter; /** * Represents a rule. @@ -47,7 +47,8 @@ public RuleInfo() { } /** - * Creates an instance of the <code>RuleInfo</code> class using the specified entry. + * Creates an instance of the <code>RuleInfo</code> class using the + * specified entry. * * @param entry * An <code>Entry</code> object. @@ -58,10 +59,12 @@ public RuleInfo(Entry entry) { } /** - * Creates an instance of the <code>RuleInfo</code> class using the specified name. + * Creates an instance of the <code>RuleInfo</code> class using the + * specified name. * * @param name - * A <code>String</code> object that represents the name of the rule. + * A <code>String</code> object that represents the name of the + * rule. * */ public RuleInfo(String name) { @@ -72,7 +75,8 @@ public RuleInfo(String name) { /** * Returns the name of the rule. * - * @return A <code>String</code> object that represents the name of the rule. + * @return A <code>String</code> object that represents the name of the + * rule. */ public String getName() { return getEntry().getTitle(); @@ -82,7 +86,8 @@ public String getName() { * Sets the name of the rule. * * @param value - * A <code>String</code> object that represents the name of the rule. + * A <code>String</code> object that represents the name of the + * rule. * * @return A <code>RuleInfo</code> object that represents the updated rule. */ @@ -94,7 +99,8 @@ public RuleInfo setName(String value) { /** * Returns the filter used for the rule. * - * @return A <code>Filter</code> object that represents the filter of the rule. + * @return A <code>Filter</code> object that represents the filter of the + * rule. */ public Filter getFilter() { return getModel().getFilter(); @@ -104,7 +110,8 @@ public Filter getFilter() { * Specifies the filter used for the rule. * * @param value - * A <code>Filter</code> object that represents the filter of the rule. + * A <code>Filter</code> object that represents the filter of the + * rule. * * @return A <code>RuleInfo</code> object that represents the updated rule. */ @@ -126,7 +133,8 @@ public RuleAction getAction() { * Specifies the rule action for the rule. * * @param value - * A <code>RuleAction</code> object that represents the rule action. + * A <code>RuleAction</code> object that represents the rule + * action. * * @return A <code>RuleInfo</code> object that represents the updated rule. */ @@ -235,7 +243,8 @@ public String getTag() { * Sets the created at. * * @param createdAt - * A <code>Calendar> object which represents the time that the rule was created at. + * A + * <code>Calendar> object which represents the time that the rule was created at. * @return A <code>RuleInfo</code> object that represents the updated rule. */ public RuleInfo setCreatedAt(Calendar createdAt) { @@ -246,7 +255,8 @@ public RuleInfo setCreatedAt(Calendar createdAt) { /** * Gets the created at. * - * @return A <code>Calendar> object which represents the time that the rule was created at. + * @return A + * <code>Calendar> object which represents the time that the rule was created at. */ public Calendar getCreatedAt() { return getModel().getCreatedAt(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/SubscriptionInfo.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/SubscriptionInfo.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/SubscriptionInfo.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/SubscriptionInfo.java index 0df71b38b78f5..5f2961dcea4a5 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/SubscriptionInfo.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/SubscriptionInfo.java @@ -12,21 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.util.Calendar; import javax.ws.rs.core.MediaType; import javax.xml.datatype.Duration; -import com.microsoft.windowsazure.services.serviceBus.implementation.Content; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityAvailabilityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.Entry; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntryModel; -import com.microsoft.windowsazure.services.serviceBus.implementation.MessageCountDetails; -import com.microsoft.windowsazure.services.serviceBus.implementation.RuleDescription; -import com.microsoft.windowsazure.services.serviceBus.implementation.SubscriptionDescription; +import com.microsoft.windowsazure.services.servicebus.implementation.Content; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityAvailabilityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.Entry; +import com.microsoft.windowsazure.services.servicebus.implementation.EntryModel; +import com.microsoft.windowsazure.services.servicebus.implementation.MessageCountDetails; +import com.microsoft.windowsazure.services.servicebus.implementation.RuleDescription; +import com.microsoft.windowsazure.services.servicebus.implementation.SubscriptionDescription; /** * Represents a subscription. @@ -44,7 +44,8 @@ public SubscriptionInfo() { } /** - * Creates an instance of the <code>SubscriptionInfo</code> class using the specified entry. + * Creates an instance of the <code>SubscriptionInfo</code> class using the + * specified entry. * * @param entry * An <code>Entry</code> object. @@ -54,10 +55,12 @@ public SubscriptionInfo(Entry entry) { } /** - * Creates an instance of the <code>SubscriptionInfo</code> class using the specified name. + * Creates an instance of the <code>SubscriptionInfo</code> class using the + * specified name. * * @param name - * A <code>String</code> object that represents the name of the subscription. + * A <code>String</code> object that represents the name of the + * subscription. */ public SubscriptionInfo(String name) { this(); @@ -67,7 +70,8 @@ public SubscriptionInfo(String name) { /** * Returns the name of the subscription. * - * @return A <code>String</code> object that represents the name of the subscription. + * @return A <code>String</code> object that represents the name of the + * subscription. */ public String getName() { return getEntry().getTitle(); @@ -77,9 +81,11 @@ public String getName() { * Sets the name of the subscription. * * @param value - * A <code>String</code> that represents the name of the subscription. + * A <code>String</code> that represents the name of the + * subscription. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setName(String value) { getEntry().setTitle(value); @@ -89,7 +95,8 @@ public SubscriptionInfo setName(String value) { /** * Returns the duration of the lock. * - * @return A <code>Duration</code> object that represents the duration of the lock. + * @return A <code>Duration</code> object that represents the duration of + * the lock. */ public Duration getLockDuration() { return getModel().getLockDuration(); @@ -101,7 +108,8 @@ public Duration getLockDuration() { * @param value * The duration, in seconds, of the lock. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setLockDuration(Duration value) { getModel().setLockDuration(value); @@ -111,7 +119,8 @@ public SubscriptionInfo setLockDuration(Duration value) { /** * Indicates whether the subscription is session-aware. * - * @return <code>true</code> if the subscription is session aware; otherwise, <code>false</code>. + * @return <code>true</code> if the subscription is session aware; + * otherwise, <code>false</code>. */ public Boolean isRequiresSession() { return getModel().isRequiresSession(); @@ -121,9 +130,11 @@ public Boolean isRequiresSession() { * Specifies whether the subscription is session-aware. * * @param value - * <code>true</code> if the subscription is session aware; otherwise, <code>false</code>. + * <code>true</code> if the subscription is session aware; + * otherwise, <code>false</code>. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setRequiresSession(Boolean value) { getModel().setRequiresSession(value); @@ -134,19 +145,23 @@ public SubscriptionInfo setRequiresSession(Boolean value) { * Returns the default message time-to-live (TTL). This applies when dead * lettering is in effect. * - * @return A <code>Duration</code> object that represents the default message TTL. + * @return A <code>Duration</code> object that represents the default + * message TTL. */ public Duration getDefaultMessageTimeToLive() { return getModel().getDefaultMessageTimeToLive(); } /** - * Sets the default message time-to-live (TTL). This applies when dead lettering is in effect. + * Sets the default message time-to-live (TTL). This applies when dead + * lettering is in effect. * * @param value - * A <code>Duration</code> object that represents the default message TTL. + * A <code>Duration</code> object that represents the default + * message TTL. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setDefaultMessageTimeToLive(Duration value) { getModel().setDefaultMessageTimeToLive(value); @@ -156,7 +171,8 @@ public SubscriptionInfo setDefaultMessageTimeToLive(Duration value) { /** * Indicates whether dead lettering is in effect upon message expiration. * - * @return <code>true</code> if dead lettering is in effect; otherwise, <code>false</code>. + * @return <code>true</code> if dead lettering is in effect; otherwise, + * <code>false</code>. */ public Boolean isDeadLetteringOnMessageExpiration() { return getModel().isDeadLetteringOnMessageExpiration(); @@ -166,9 +182,11 @@ public Boolean isDeadLetteringOnMessageExpiration() { * Specifies whether dead lettering is in effect upon message expiration. * * @param value - * <code>true</code> if dead lettering is in effect; otherwise, <code>false</code>. + * <code>true</code> if dead lettering is in effect; otherwise, + * <code>false</code>. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setDeadLetteringOnMessageExpiration(Boolean value) { getModel().setDeadLetteringOnMessageExpiration(value); @@ -176,23 +194,29 @@ public SubscriptionInfo setDeadLetteringOnMessageExpiration(Boolean value) { } /** - * Indicates whether dead lettering is in effect when filter evaluation exceptions are encountered. + * Indicates whether dead lettering is in effect when filter evaluation + * exceptions are encountered. * - * @return <code>true</code> if dead lettering is in effect; otherwise, <code>false</code>. + * @return <code>true</code> if dead lettering is in effect; otherwise, + * <code>false</code>. */ public Boolean isDeadLetteringOnFilterEvaluationExceptions() { return getModel().isDeadLetteringOnFilterEvaluationExceptions(); } /** - * Specifies whether dead lettering is in effect when filter evaluation exceptions are encountered. + * Specifies whether dead lettering is in effect when filter evaluation + * exceptions are encountered. * * @param value - * <code>true</code> if dead lettering is in effect; otherwise, <code>false</code>. + * <code>true</code> if dead lettering is in effect; otherwise, + * <code>false</code>. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ - public SubscriptionInfo setDeadLetteringOnFilterEvaluationExceptions(Boolean value) { + public SubscriptionInfo setDeadLetteringOnFilterEvaluationExceptions( + Boolean value) { getModel().setDeadLetteringOnFilterEvaluationExceptions(value); return this; } @@ -200,7 +224,8 @@ public SubscriptionInfo setDeadLetteringOnFilterEvaluationExceptions(Boolean val /** * Returns the description of the default rule. * - * @return A <code>RuleDescription</code> object that represents the default rule description. + * @return A <code>RuleDescription</code> object that represents the default + * rule description. */ public RuleDescription getDefaultRuleDescription() { return getModel().getDefaultRuleDescription(); @@ -210,9 +235,11 @@ public RuleDescription getDefaultRuleDescription() { * Specifies the description for the default rule. * * @param value - * A <code>RuleDescription</code> object that represents the default rule description. + * A <code>RuleDescription</code> object that represents the + * default rule description. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setDefaultRuleDescription(RuleDescription value) { getModel().setDefaultRuleDescription(value); @@ -241,9 +268,11 @@ public Integer getMaxDeliveryCount() { * Sets the maximum delivery count for the subscription. * * @param value - * A <code>value</code> represents the maximum delivery count for the subscription. + * A <code>value</code> represents the maximum delivery count for + * the subscription. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setMaxDeliveryCount(Integer value) { getModel().setMaxDeliveryCount(value); @@ -253,7 +282,8 @@ public SubscriptionInfo setMaxDeliveryCount(Integer value) { /** * Indicates whether batch operations are enabled. * - * @return <code>true</code> if batch operations are enabled; otherwise, <code>false</code>. + * @return <code>true</code> if batch operations are enabled; otherwise, + * <code>false</code>. */ public Boolean isEnableBatchedOperations() { return getModel().isEnableBatchedOperations(); @@ -263,9 +293,11 @@ public Boolean isEnableBatchedOperations() { * Specifies whether batch operations are enabled. * * @param value - * <code>true</code> if batch operations are enabled; otherwise, <code>false</code>. + * <code>true</code> if batch operations are enabled; otherwise, + * <code>false</code>. * - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setEnableBatchedOperations(Boolean value) { getModel().setEnableBatchedOperations(value); @@ -277,7 +309,8 @@ public SubscriptionInfo setEnableBatchedOperations(Boolean value) { * * @param messageCount * A <code>Long</code> object represents the message count. - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setMessageCount(Long messageCount) { getModel().setMessageCount(messageCount); @@ -288,8 +321,10 @@ public SubscriptionInfo setMessageCount(Long messageCount) { * Sets the status. * * @param entityStatus - * A <code>EntityStatus</code> object represents the status of the entity. - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * A <code>EntityStatus</code> object represents the status of + * the entity. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setStatus(EntityStatus entityStatus) { getModel().setStatus(entityStatus); @@ -299,7 +334,8 @@ public SubscriptionInfo setStatus(EntityStatus entityStatus) { /** * Gets the status. * - * @return A <code>EntityStatus</code> object represents the status of the entity. + * @return A <code>EntityStatus</code> object represents the status of the + * entity. */ public EntityStatus getStatus() { return getModel().getStatus(); @@ -310,7 +346,8 @@ public EntityStatus getStatus() { * * @param createdAt * the created at - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setCreatedAt(Calendar createdAt) { getModel().setCreatedAt(createdAt); @@ -331,7 +368,8 @@ public Calendar getCreatedAt() { * * @param updatedAt * the updated at - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setUpdatedAt(Calendar updatedAt) { getModel().setUpdatedAt(updatedAt); @@ -352,7 +390,8 @@ public Calendar getUpdatedAt() { * * @param accessedAt * the accessed at - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setAccessedAt(Calendar accessedAt) { getModel().setAccessedAt(accessedAt); @@ -373,7 +412,8 @@ public Calendar getAccessedAt() { * * @param userMetadata * the user metadata - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setUserMetadata(String userMetadata) { getModel().setUserMetadata(userMetadata); @@ -393,8 +433,10 @@ public String getUserMetadata() { * Sets the auto delete on idle. * * @param autoDeleteOnIdle - * A <code>Duration</code> object represents the auto delete on idle. - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * A <code>Duration</code> object represents the auto delete on + * idle. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ public SubscriptionInfo setAutoDeleteOnIdle(Duration autoDeleteOnIdle) { getModel().setAutoDeleteOnIdle(autoDeleteOnIdle); @@ -404,7 +446,8 @@ public SubscriptionInfo setAutoDeleteOnIdle(Duration autoDeleteOnIdle) { /** * Gets the auto delete on idle. * - * @return A <code>Duration</code> object represents the auto delete on idle. + * @return A <code>Duration</code> object represents the auto delete on + * idle. */ public Duration getAutoDeleteOnIdle() { return getModel().getAutoDeleteOnIdle(); @@ -414,10 +457,13 @@ public Duration getAutoDeleteOnIdle() { * Sets the entity availability status. * * @param entityAvailabilityStatus - * An <code>EntityAvailabilityStatus</code> instance representing the entity availiability status. - * @return A <code>SubscriptionInfo</code> object that represents the updated subscription. + * An <code>EntityAvailabilityStatus</code> instance representing + * the entity availiability status. + * @return A <code>SubscriptionInfo</code> object that represents the + * updated subscription. */ - public SubscriptionInfo setEntityAvailabilityStatus(EntityAvailabilityStatus entityAvailabilityStatus) { + public SubscriptionInfo setEntityAvailabilityStatus( + EntityAvailabilityStatus entityAvailabilityStatus) { getModel().setEntityAvailabilityStatus(entityAvailabilityStatus); return this; } @@ -425,7 +471,8 @@ public SubscriptionInfo setEntityAvailabilityStatus(EntityAvailabilityStatus ent /** * Gets the entity availability status. * - * @return An <code>EntityAvailabilityStatus</code> instance representing the entity availiability status. + * @return An <code>EntityAvailabilityStatus</code> instance representing + * the entity availiability status. */ public EntityAvailabilityStatus getEntityAvailabilityStatus() { return getModel().getEntityAvailabilityStatus(); @@ -434,7 +481,8 @@ public EntityAvailabilityStatus getEntityAvailabilityStatus() { /** * Gets the message count details. * - * @return A <code>MessageCountDetails</code> instance representing the details of the message count. + * @return A <code>MessageCountDetails</code> instance representing the + * details of the message count. */ public MessageCountDetails getCountDetails() { return getModel().getCountDetails(); @@ -453,9 +501,11 @@ public SubscriptionInfo setForwardTo(String forwardTo) { } /** - * Gets a <code>String</code> representing the URI of the entity to forward to. + * Gets a <code>String</code> representing the URI of the entity to forward + * to. * - * @return A <code>String</code> representing the URI of the entity to forward to. + * @return A <code>String</code> representing the URI of the entity to + * forward to. */ public String getForwardTo() { return getModel().getForwardTo(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/TopicInfo.java b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/TopicInfo.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/TopicInfo.java rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/TopicInfo.java index d3233b1a81745..65c5cdb471883 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/TopicInfo.java +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/TopicInfo.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import java.net.URI; import java.util.Calendar; @@ -20,14 +20,14 @@ import javax.ws.rs.core.MediaType; import javax.xml.datatype.Duration; -import com.microsoft.windowsazure.services.serviceBus.implementation.Content; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityAvailabilityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntityStatus; -import com.microsoft.windowsazure.services.serviceBus.implementation.Entry; -import com.microsoft.windowsazure.services.serviceBus.implementation.EntryModel; -import com.microsoft.windowsazure.services.serviceBus.implementation.MessageCountDetails; -import com.microsoft.windowsazure.services.serviceBus.implementation.PartitioningPolicy; -import com.microsoft.windowsazure.services.serviceBus.implementation.TopicDescription; +import com.microsoft.windowsazure.services.servicebus.implementation.Content; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityAvailabilityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.Entry; +import com.microsoft.windowsazure.services.servicebus.implementation.EntryModel; +import com.microsoft.windowsazure.services.servicebus.implementation.MessageCountDetails; +import com.microsoft.windowsazure.services.servicebus.implementation.PartitioningPolicy; +import com.microsoft.windowsazure.services.servicebus.implementation.TopicDescription; /** * Represents a topic. @@ -44,20 +44,24 @@ public TopicInfo() { } /** - * Creates an instance of the <code>TopicInfo</code> class using the specified entry. + * Creates an instance of the <code>TopicInfo</code> class using the + * specified entry. * * @param entry - * An <code>Entry</code> object that represents the entry for the topic. + * An <code>Entry</code> object that represents the entry for the + * topic. */ public TopicInfo(Entry entry) { super(entry, entry.getContent().getTopicDescription()); } /** - * Creates an instance of the <code>TopicInfo</code> class using the specified name. + * Creates an instance of the <code>TopicInfo</code> class using the + * specified name. * * @param path - * A <code>String</code> object that represents the name for the topic. + * A <code>String</code> object that represents the name for the + * topic. */ public TopicInfo(String path) { this(); @@ -67,7 +71,8 @@ public TopicInfo(String path) { /** * Returns the name of the topic. * - * @return A <code>String</code> object that represents the name of the topic. + * @return A <code>String</code> object that represents the name of the + * topic. */ public String getPath() { return getEntry().getTitle(); @@ -79,7 +84,8 @@ public String getPath() { * @param value * A <code>String</code> that represents the name of the topic. * - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setPath(String value) { getEntry().setTitle(value); @@ -89,7 +95,8 @@ public TopicInfo setPath(String value) { /** * Returns the default message time-to-live (TTL). * - * @return A <code>Duration</code> object that represents the default message TTL. + * @return A <code>Duration</code> object that represents the default + * message TTL. */ public Duration getDefaultMessageTimeToLive() { return getModel().getDefaultMessageTimeToLive(); @@ -99,9 +106,11 @@ public Duration getDefaultMessageTimeToLive() { * Sets the default message time-to-live (TTL). * * @param value - * A <code>Duration</code> object that represents the default message TTL. + * A <code>Duration</code> object that represents the default + * message TTL. * - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setDefaultMessageTimeToLive(Duration value) { getModel().setDefaultMessageTimeToLive(value); @@ -123,7 +132,8 @@ public Long getMaxSizeInMegabytes() { * @param value * The maximum size, in megabytes, of the topic. * - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setMaxSizeInMegabytes(Long value) { getModel().setMaxSizeInMegabytes(value); @@ -133,7 +143,8 @@ public TopicInfo setMaxSizeInMegabytes(Long value) { /** * Indicates whether duplicate message detection is required. * - * @return <code>true</code> if duplicate message detection is required; otherwise, <code>false</code>. + * @return <code>true</code> if duplicate message detection is required; + * otherwise, <code>false</code>. */ public Boolean isRequiresDuplicateDetection() { return getModel().isRequiresDuplicateDetection(); @@ -143,9 +154,11 @@ public Boolean isRequiresDuplicateDetection() { * Specifies whether duplicate message detection is required. * * @param value - * <code>true</code> if duplicate message detection is required; otherwise, <code>false</code>. + * <code>true</code> if duplicate message detection is required; + * otherwise, <code>false</code>. * - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setRequiresDuplicateDetection(Boolean value) { getModel().setRequiresDuplicateDetection(value); @@ -153,7 +166,8 @@ public TopicInfo setRequiresDuplicateDetection(Boolean value) { } /** - * Returns the time span during which the service bus will detect message duplication. + * Returns the time span during which the service bus will detect message + * duplication. * * @return A <code>Duration</code> object that represents the time span for * detecting message duplication. @@ -163,12 +177,15 @@ public Duration getDuplicateDetectionHistoryTimeWindow() { } /** - * Sets the time span during which the service bus will detect message duplication. + * Sets the time span during which the service bus will detect message + * duplication. * * @param value - * A <code>Duration</code> object that represents the time span for detecting message duplication. + * A <code>Duration</code> object that represents the time span + * for detecting message duplication. * - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setDuplicateDetectionHistoryTimeWindow(Duration value) { getModel().setDuplicateDetectionHistoryTimeWindow(value); @@ -178,7 +195,8 @@ public TopicInfo setDuplicateDetectionHistoryTimeWindow(Duration value) { /** * Indicates whether batch operations are enabled. * - * @return <code>true</code> if batch operations are enabled; otherwise, <code>false</code>. + * @return <code>true</code> if batch operations are enabled; otherwise, + * <code>false</code>. */ public Boolean isEnableBatchedOperations() { return getModel().isEnableBatchedOperations(); @@ -188,9 +206,11 @@ public Boolean isEnableBatchedOperations() { * Specifies whether batch operations are enabled. * * @param value - * <code>true</code> if batch operations are enabled; otherwise, <code>false</code>. + * <code>true</code> if batch operations are enabled; otherwise, + * <code>false</code>. * - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setEnableBatchedOperations(Boolean value) { getModel().setEnableBatchedOperations(value); @@ -211,7 +231,8 @@ public Long getSizeInBytes() { * * @param sizeInBytes * A <code>Long</code> instance of the size in bytes. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setSizeInBytes(Long sizeInBytes) { getModel().setSizeInBytes(sizeInBytes); @@ -222,18 +243,23 @@ public TopicInfo setSizeInBytes(Long sizeInBytes) { * Sets the filtering message before publishing. * * @param filteringMessageBeforePublishing - * <code>true</code> if filter message before publishing, otherwise false. - * @return A <code>TopicInfo</code> object that represents the updated topic. - */ - public TopicInfo setFilteringMessageBeforePublishing(Boolean filteringMessageBeforePublishing) { - getModel().setFilteringMessagesBeforePublishing(filteringMessageBeforePublishing); + * <code>true</code> if filter message before publishing, + * otherwise false. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. + */ + public TopicInfo setFilteringMessageBeforePublishing( + Boolean filteringMessageBeforePublishing) { + getModel().setFilteringMessagesBeforePublishing( + filteringMessageBeforePublishing); return this; } /** * Checks if is filtering message before publishing. * - * @return <code>true</code> if filter message before publishing, otherwise false. + * @return <code>true</code> if filter message before publishing, otherwise + * false. */ public Boolean isFilteringMessageBeforePublishing() { return getModel().isFilteringMessagesBeforePublishing(); @@ -243,8 +269,10 @@ public Boolean isFilteringMessageBeforePublishing() { * Sets the anonymous accessible. * * @param anonymousAccessible - * <code>true</code> if is anonymous accessible, otherwise <code>false</code>. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * <code>true</code> if is anonymous accessible, otherwise + * <code>false</code>. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setAnonymousAccessible(Boolean anonymousAccessible) { getModel().setIsAnonymousAccessible(anonymousAccessible); @@ -254,7 +282,8 @@ public TopicInfo setAnonymousAccessible(Boolean anonymousAccessible) { /** * Checks if is anonymous accessible. * - * @return <code>true</code> if is anonymous accessible, otherwise <code>false</code>. + * @return <code>true</code> if is anonymous accessible, otherwise + * <code>false</code>. */ public Boolean isAnonymousAccessible() { return getModel().isIsAnonymousAccessible(); @@ -265,7 +294,8 @@ public Boolean isAnonymousAccessible() { * * @param status * the status - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setStatus(EntityStatus status) { getModel().setStatus(status); @@ -275,7 +305,8 @@ public TopicInfo setStatus(EntityStatus status) { /** * Gets the status. * - * @return An <code>EntityStatus</code> object that represents the status of the object. + * @return An <code>EntityStatus</code> object that represents the status of + * the object. */ public EntityStatus getStatus() { return getModel().getStatus(); @@ -286,7 +317,8 @@ public EntityStatus getStatus() { * * @param createdAt * the created at - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setCreatedAt(Calendar createdAt) { getModel().setCreatedAt(createdAt); @@ -296,7 +328,8 @@ public TopicInfo setCreatedAt(Calendar createdAt) { /** * Gets the created at. * - * @return A <code>Calendar</code> object which represents when the topic was created. + * @return A <code>Calendar</code> object which represents when the topic + * was created. */ public Calendar getCreatedAt() { return getModel().getCreatedAt(); @@ -306,8 +339,10 @@ public Calendar getCreatedAt() { * Sets the updated at. * * @param updatedAt - * A <code>Calendar</code> object which represents when the topic was updated. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * A <code>Calendar</code> object which represents when the topic + * was updated. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setUpdatedAt(Calendar updatedAt) { getModel().setUpdatedAt(updatedAt); @@ -317,7 +352,8 @@ public TopicInfo setUpdatedAt(Calendar updatedAt) { /** * Gets the updated at. * - * @return A <code>Calendar</code> object which represents when the topic was updated. + * @return A <code>Calendar</code> object which represents when the topic + * was updated. */ public Calendar getUpdatedAt() { return getModel().getUpdatedAt(); @@ -327,8 +363,10 @@ public Calendar getUpdatedAt() { * Sets the accessed at. * * @param accessedAt - * A <code>Calendar</code> instance representing when topic was last accessed at. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * A <code>Calendar</code> instance representing when topic was + * last accessed at. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setAccessedAt(Calendar accessedAt) { getModel().setAccessedAt(accessedAt); @@ -338,7 +376,8 @@ public TopicInfo setAccessedAt(Calendar accessedAt) { /** * Gets the accessed at. * - * @return A <code>Calendar</code> instance representing when topic was last accessed at. + * @return A <code>Calendar</code> instance representing when topic was last + * accessed at. */ public Calendar getAccessedAt() { return getModel().getAccessedAt(); @@ -349,7 +388,8 @@ public Calendar getAccessedAt() { * * @param userMetadata * A <code>String</code> represents the user metadata. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setUserMetadata(String userMetadata) { getModel().setUserMetadata(userMetadata); @@ -369,8 +409,10 @@ public String getUserMetadata() { * Sets the support ordering. * * @param supportOrdering - * <code>true</code> if supports ordering, otherwise <code>false</code>. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * <code>true</code> if supports ordering, otherwise + * <code>false</code>. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setSupportOrdering(Boolean supportOrdering) { getModel().setSupportOrdering(supportOrdering); @@ -380,7 +422,8 @@ public TopicInfo setSupportOrdering(Boolean supportOrdering) { /** * Checks if is support ordering. * - * @return <code>true</code> if supports ordering, otherwise <code>false</code>. + * @return <code>true</code> if supports ordering, otherwise + * <code>false</code>. */ public Boolean isSupportOrdering() { return getModel().isSupportOrdering(); @@ -391,7 +434,8 @@ public Boolean isSupportOrdering() { * * @param subscriptionCount * The count of the subscription. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setSubscriptionCount(Integer subscriptionCount) { getModel().setSubscriptionCount(subscriptionCount); @@ -410,7 +454,8 @@ public Integer getSubscriptionCount() { /** * Gets the message count details. * - * @return A <code>MessageCountDetails</code> instance representing the details of the message count. + * @return A <code>MessageCountDetails</code> instance representing the + * details of the message count. */ public MessageCountDetails getCountDetails() { return getModel().getCountDetails(); @@ -420,8 +465,10 @@ public MessageCountDetails getCountDetails() { * Sets the auto delete on idle. * * @param autoDeleteOnIdle - * A <code>Duration</code> object which represents the time span of auto delete on idle. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * A <code>Duration</code> object which represents the time span + * of auto delete on idle. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setAutoDeleteOnIdle(Duration autoDeleteOnIdle) { getModel().setAutoDeleteOnIdle(autoDeleteOnIdle); @@ -431,7 +478,8 @@ public TopicInfo setAutoDeleteOnIdle(Duration autoDeleteOnIdle) { /** * Gets the auto delete on idle. * - * @return A <code>Duration</code> object which represents the time span of auto delete on idle. + * @return A <code>Duration</code> object which represents the time span of + * auto delete on idle. */ public Duration getAutoDeleteOnIdle() { return getModel().getAutoDeleteOnIdle(); @@ -441,8 +489,10 @@ public Duration getAutoDeleteOnIdle() { * Sets the partitioning policy. * * @param partitioningPolicy - * A <code>PartitioningPolicy</code> object which represents the partitioning policy. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * A <code>PartitioningPolicy</code> object which represents the + * partitioning policy. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ public TopicInfo setPartitioningPolicy(PartitioningPolicy partitioningPolicy) { getModel().setPartitioningPolicy(partitioningPolicy); @@ -452,7 +502,8 @@ public TopicInfo setPartitioningPolicy(PartitioningPolicy partitioningPolicy) { /** * Gets the partitioning policy. * - * @return A <code>PartitioningPolicy</code> object which represents the partitioning policy. + * @return A <code>PartitioningPolicy</code> object which represents the + * partitioning policy. */ public PartitioningPolicy getPartitioningPolicy() { return getModel().getPartitioningPolicy(); @@ -462,10 +513,13 @@ public PartitioningPolicy getPartitioningPolicy() { * Sets the entity availability status. * * @param entityAvailabilityStatus - * An <code>EntityAvailabilityStatus</code> instance which represents the entity availability status. - * @return A <code>TopicInfo</code> object that represents the updated topic. + * An <code>EntityAvailabilityStatus</code> instance which + * represents the entity availability status. + * @return A <code>TopicInfo</code> object that represents the updated + * topic. */ - public TopicInfo setEntityAvailabilityStatus(EntityAvailabilityStatus entityAvailabilityStatus) { + public TopicInfo setEntityAvailabilityStatus( + EntityAvailabilityStatus entityAvailabilityStatus) { getModel().setEntityAvailabilityStatus(entityAvailabilityStatus); return this; } @@ -473,7 +527,8 @@ public TopicInfo setEntityAvailabilityStatus(EntityAvailabilityStatus entityAvai /** * Gets the entity availability status. * - * @return An <code>EntityAvailabilityStatus</code> instance which represents the entity availability status. + * @return An <code>EntityAvailabilityStatus</code> instance which + * represents the entity availability status. */ public EntityAvailabilityStatus getEntityAvailabilityStatus() { return getModel().getEntityAvailabilityStatus(); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/package.html b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/serviceBus/models/package.html rename to serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/models/package.html diff --git a/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/package.html b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/package.html new file mode 100644 index 0000000000000..f320abf4cc9a2 --- /dev/null +++ b/serviceBus/src/main/java/com/microsoft/windowsazure/services/servicebus/package.html @@ -0,0 +1,6 @@ +<html> +<head /> +<body>This package contains the service bus service class, + interface, and associated configuration and utility classes. +</body> +</html> diff --git a/serviceBus/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports b/serviceBus/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports new file mode 100644 index 0000000000000..311eabe761f50 --- /dev/null +++ b/serviceBus/src/main/resources/META-INF/services/com.microsoft.windowsazure.core.Builder$Exports @@ -0,0 +1,2 @@ +com.microsoft.windowsazure.services.servicebus.Exports +com.microsoft.windowsazure.services.servicebus.implementation.Exports \ No newline at end of file diff --git a/serviceBus/src/main/resources/serviceBus/package-names.xjb b/serviceBus/src/main/resources/serviceBus/package-names.xjb new file mode 100644 index 0000000000000..b148b606845b2 --- /dev/null +++ b/serviceBus/src/main/resources/serviceBus/package-names.xjb @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" + jaxb:version="2.0" + jaxb:extensionBindingPrefixes="xjc"> + + <jaxb:bindings schemaLocation="schemas.microsoft.com.netservices.2011.06.servicebus.xsd" node="/xsd:schema"> + <jaxb:schemaBindings> + <jaxb:package name="com.microsoft.windowsazure.services.servicebus.implementation"/> + </jaxb:schemaBindings> + </jaxb:bindings> + <jaxb:bindings schemaLocation="schemas.microsoft.com.netservices.2010.10.servicebus.connect.xsd" node="/xsd:schema"> + <jaxb:schemaBindings> + <jaxb:package name="com.microsoft.windowsazure.services.servicebus.implementation"/> + </jaxb:schemaBindings> + </jaxb:bindings> + <jaxb:bindings schemaLocation="servicebus-atom.xsd" node="/xsd:schema"> + <jaxb:schemaBindings> + <jaxb:package name="com.microsoft.windowsazure.services.servicebus.implementation"/> + </jaxb:schemaBindings> + </jaxb:bindings> +</jaxb:bindings> diff --git a/microsoft-azure-api/src/main/resources/serviceBus/schemas.microsoft.com.2003.10.Serialization.xsd b/serviceBus/src/main/resources/serviceBus/schemas.microsoft.com.2003.10.Serialization.xsd similarity index 100% rename from microsoft-azure-api/src/main/resources/serviceBus/schemas.microsoft.com.2003.10.Serialization.xsd rename to serviceBus/src/main/resources/serviceBus/schemas.microsoft.com.2003.10.Serialization.xsd diff --git a/microsoft-azure-api/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2010.10.servicebus.connect.xsd b/serviceBus/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2010.10.servicebus.connect.xsd similarity index 100% rename from microsoft-azure-api/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2010.10.servicebus.connect.xsd rename to serviceBus/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2010.10.servicebus.connect.xsd diff --git a/microsoft-azure-api/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2011.06.servicebus.xsd b/serviceBus/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2011.06.servicebus.xsd similarity index 100% rename from microsoft-azure-api/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2011.06.servicebus.xsd rename to serviceBus/src/main/resources/serviceBus/schemas.microsoft.com.netservices.2011.06.servicebus.xsd diff --git a/microsoft-azure-api/src/main/resources/serviceBus/servicebus-atom.xsd b/serviceBus/src/main/resources/serviceBus/servicebus-atom.xsd similarity index 100% rename from microsoft-azure-api/src/main/resources/serviceBus/servicebus-atom.xsd rename to serviceBus/src/main/resources/serviceBus/servicebus-atom.xsd diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/BrokerPropertiesMapperTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/BrokerPropertiesMapperTest.java new file mode 100644 index 0000000000000..738551198f274 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/BrokerPropertiesMapperTest.java @@ -0,0 +1,195 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import static org.junit.Assert.*; + +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.microsoft.windowsazure.services.servicebus.implementation.BrokerProperties; +import com.microsoft.windowsazure.services.servicebus.implementation.BrokerPropertiesMapper; + +public class BrokerPropertiesMapperTest { + + private final String testBrokerPropertiesString = "{" + + "\"CorrelationId\": \"corid\"," + + "\"SessionId\": \"sesid\"," + + "\"DeliveryCount\": 5," + + "\"LockedUntilUtc\": \" Fri, 14 Oct 2011 12:34:56 GMT\"," + + "\"LockToken\": \"loctok\"," + + "\"MessageId\": \"mesid\"," + + "\"Label\": \"lab\"," + + "\"ReplyTo\": \"repto\"," + + "\"SequenceNumber\": 7," + + "\"TimeToLive\": 8.123," + + "\"To\": \"to\"," + + "\"ScheduledEnqueueTimeUtc\": \" Sun, 06 Nov 1994 08:49:37 GMT\"," + + "\"ReplyToSessionId\": \"reptosesid\"," + + "\"MessageLocation\": \"mesloc\"," + + "\"LockLocation\": \"locloc\"" + "}"; + + private static Date schedTimeUtc, lockedUntilUtc; + + @BeforeClass + public static void setup() { + Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + calendar.set(1994, 10, 6, 8, 49, 37); + schedTimeUtc = calendar.getTime(); + + Calendar calendar2 = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + calendar2.set(2011, 9, 14, 12, 34, 56); + lockedUntilUtc = calendar2.getTime(); + + } + + @Test + public void jsonStringMapsToBrokerPropertiesObject() { + // Arrange + BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); + + // Act + BrokerProperties properties = mapper + .fromString("{\"DeliveryCount\":5,\"MessageId\":\"something\"}"); + + // Assert + assertNotNull(properties); + assertEquals(new Integer(5), properties.getDeliveryCount()); + assertEquals("something", properties.getMessageId()); + } + + @Test + public void nonDefaultPropertiesMapToJsonString() { + // Arrange + BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); + + // Act + BrokerProperties properties = new BrokerProperties(); + properties.setMessageId("foo"); + properties.setDeliveryCount(7); + String json = mapper.toString(properties); + + // Assert + assertNotNull(json); + assertEquals("{\"DeliveryCount\":7,\"MessageId\":\"foo\"}", json); + } + + @Test + public void deserializingAllPossibleValues() { + // Arrange + BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); + + // Act + BrokerProperties properties = mapper + .fromString(testBrokerPropertiesString); + + // Assert + assertNotNull(properties); + + long lockedUntilDelta = properties.getLockedUntilUtc().getTime() + - lockedUntilUtc.getTime(); + long schedTimeDelta = properties.getScheduledEnqueueTimeUtc().getTime() + - schedTimeUtc.getTime(); + + assertEquals("corid", properties.getCorrelationId()); + assertEquals("sesid", properties.getSessionId()); + assertEquals(5, (int) properties.getDeliveryCount()); + assertTrue(Math.abs(lockedUntilDelta) < 2000); + assertEquals("loctok", properties.getLockToken()); + assertEquals("mesid", properties.getMessageId()); + assertEquals("lab", properties.getLabel()); + assertEquals("repto", properties.getReplyTo()); + assertEquals(7, (long) properties.getSequenceNumber()); + assertEquals(8.123, properties.getTimeToLive(), .001); + assertEquals("to", properties.getTo()); + assertTrue(Math.abs(schedTimeDelta) < 2000); + assertEquals("reptosesid", properties.getReplyToSessionId()); + assertEquals("mesloc", properties.getMessageLocation()); + assertEquals("locloc", properties.getLockLocation()); + } + + @Test + public void missingDatesDeserializeAsNull() { + // Arrange + BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); + + // Act + BrokerProperties properties = mapper.fromString("{}"); + + // Assert + assertNull(properties.getLockedUntilUtc()); + assertNull(properties.getScheduledEnqueueTimeUtc()); + } + + @Test + public void deserializeDateInKrKrLocaleCorrectly() { + // Arrange + BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); + Locale defaultLocale = Locale.getDefault(); + Locale.setDefault(Locale.KOREA); + + // Act + BrokerProperties brokerProperties = mapper + .fromString(testBrokerPropertiesString); + Locale.setDefault(defaultLocale); + + // Assert + long lockedUntilDelta = brokerProperties.getLockedUntilUtc().getTime() + - lockedUntilUtc.getTime(); + assertTrue(Math.abs(lockedUntilDelta) < 2000); + } + + @Test + public void deserializeDateInEnUsLocaleCorrectly() { + // Arrange + BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); + Locale defaultLocale = Locale.getDefault(); + Locale.setDefault(Locale.US); + + // Act + BrokerProperties brokerProperties = mapper + .fromString(testBrokerPropertiesString); + Locale.setDefault(defaultLocale); + + // Assert + long lockedUntilDelta = brokerProperties.getLockedUntilUtc().getTime() + - lockedUntilUtc.getTime(); + assertTrue(Math.abs(lockedUntilDelta) < 2000); + + } + + @Test + public void deserializeDateInZhCnLocaleCorrectly() { + // Arrange + BrokerPropertiesMapper mapper = new BrokerPropertiesMapper(); + Locale defaultLocale = Locale.getDefault(); + Locale.setDefault(Locale.CHINA); + + // Act + BrokerProperties brokerProperties = mapper + .fromString(testBrokerPropertiesString); + Locale.setDefault(defaultLocale); + + // Assert + long lockedUntilDelta = brokerProperties.getLockedUntilUtc().getTime() + - lockedUntilUtc.getTime(); + assertTrue(Math.abs(lockedUntilDelta) < 2000); + } +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/IntegrationTestBase.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/IntegrationTestBase.java new file mode 100644 index 0000000000000..8d4d47f87e13f --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/IntegrationTestBase.java @@ -0,0 +1,107 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.exception.ServiceException; +import static com.microsoft.windowsazure.services.servicebus.Util.*; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; + +import com.microsoft.windowsazure.services.servicebus.models.QueueInfo; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageOptions; +import com.microsoft.windowsazure.services.servicebus.models.TopicInfo; + +public abstract class IntegrationTestBase { + + private ServiceBusContract service; + + @BeforeClass + public static void initializeSystem() { + System.setProperty("http.keepAlive", "false"); + } + + @Before + public void initialize() throws Exception { + + boolean testAlphaExists = false; + Configuration config = createConfiguration(); + service = ServiceBusService.create(config); + for (QueueInfo queue : iterateQueues(service)) { + String queueName = queue.getPath(); + if (queueName.startsWith("Test") || queueName.startsWith("test")) { + if (queueName.equalsIgnoreCase("TestAlpha")) { + testAlphaExists = true; + long count = queue.getMessageCount(); + for (long i = 0; i != count; ++i) { + service.receiveQueueMessage(queueName, + new ReceiveMessageOptions().setTimeout(20)); + } + } else { + service.deleteQueue(queueName); + } + } + } + + removeTopics(); + + if (!testAlphaExists) { + service.createQueue(new QueueInfo("TestAlpha")); + } + } + + protected void removeTopics() throws ServiceException { + for (TopicInfo topic : iterateTopics(service)) { + String topicName = topic.getPath(); + if (topicName.startsWith("Test") || topicName.startsWith("test")) { + service.deleteTopic(topicName); + } + } + } + + @AfterClass + public static void cleanUpTestArtifacts() throws Exception { + Configuration config = createConfiguration(); + ServiceBusContract service = ServiceBusService.create(config); + for (QueueInfo queue : iterateQueues(service)) { + String queueName = queue.getPath(); + if (queueName.startsWith("Test") || queueName.startsWith("test")) { + service.deleteQueue(queueName); + } + } + for (TopicInfo topic : iterateTopics(service)) { + String topicName = topic.getPath(); + if (topicName.startsWith("Test") || topicName.startsWith("test")) { + service.deleteTopic(topicName); + } + } + } + + protected static Configuration createConfiguration() throws Exception { + Configuration config = Configuration.load(); + overrideWithEnv(config, ServiceBusConfiguration.CONNECTION_STRING); + return config; + } + + private static void overrideWithEnv(Configuration config, String key) { + String value = System.getenv(key); + if (value == null) + return; + + config.setProperty(key, value); + } +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusConfigurationTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusConfigurationTest.java new file mode 100644 index 0000000000000..a61bb8aff43e7 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusConfigurationTest.java @@ -0,0 +1,61 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import com.microsoft.windowsazure.Configuration; +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ServiceBusConfigurationTest { + @Test + public void ConfigureSetsExpectedProperties() { + // Arrange + Configuration config = new Configuration(); + + // Act + ServiceBusConfiguration.configureWithWrapAuthentication(config, + "alpha", "beta", "gamma", ".servicebus.windows.net/", + "-sb.accesscontrol.windows.net/WRAPv0.9"); + + // Assert + assertEquals("https://alpha.servicebus.windows.net/", + config.getProperty("serviceBus.uri")); + assertEquals("https://alpha-sb.accesscontrol.windows.net/WRAPv0.9", + config.getProperty("serviceBus.wrap.uri")); + assertEquals("beta", config.getProperty("serviceBus.wrap.name")); + assertEquals("gamma", config.getProperty("serviceBus.wrap.password")); + } + + @Test + public void UsingProfileAddsPrefix() { + // Arrange + Configuration config = new Configuration(); + + // Act + ServiceBusConfiguration.configureWithWrapAuthentication("backup", + config, "alpha", "beta", "gamma", ".servicebus.windows.net/", + "-sb.accesscontrol.windows.net/WRAPv0.9"); + + // Assert + assertEquals("https://alpha.servicebus.windows.net/", + config.getProperty("backup.serviceBus.uri")); + assertEquals("https://alpha-sb.accesscontrol.windows.net/WRAPv0.9", + config.getProperty("backup.serviceBus.wrap.uri")); + assertEquals("beta", config.getProperty("backup.serviceBus.wrap.name")); + assertEquals("gamma", + config.getProperty("backup.serviceBus.wrap.password")); + } +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusCreationTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusCreationTest.java new file mode 100644 index 0000000000000..e309b6725a58d --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusCreationTest.java @@ -0,0 +1,109 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.services.servicebus.implementation.ServiceBusExceptionProcessor; + +public class ServiceBusCreationTest { + @Test + public void theServiceClassMayBeCreatedDirectlyViaSingletonConfig() + throws Exception { + ServiceBusConfiguration.configureWithWrapAuthentication("my-namespace", + "my-identity", "my-shared-secret", ".servicebus.windows.net", + "-sb.accesscontrol.windows.net/WRAPv0.9"); + ServiceBusContract service = ServiceBusService.create(); + + assertNotNull(service); + assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); + } + + public Configuration newConfiguration() { + Configuration config = new Configuration(); + ServiceBusConfiguration.configureWithWrapAuthentication(config, + "my-namespace", "my-identity", "my-shared-secret", + ".servicebus.windows.net", + "-sb.accesscontrol.windows.net/WRAPv0.9"); + return config; + } + + private Configuration newConfigurationWithProfile() { + Configuration config = newConfiguration(); + ServiceBusConfiguration.configureWithWrapAuthentication("other", + config, "my-other-namespace", "my-other-identity", + "my-shared-secret", ".servicebus.windows.net", + "-sb.accesscontrol.windows.net/WRAPv0.9"); + return config; + } + + private Configuration newConfigurationWithConnectionString() { + Configuration config = newConfiguration(); + ServiceBusConfiguration.configureWithConnectionString(null, config, + "Endpoint=https://my-other-namespace.servicebus.windows.net/;" + + "SharedSecretIssuer=owner;" + + "SharedSecretValue=my-shared-secret"); + return config; + } + + @Test + public void theServiceClassMayBeCreatedDirectlyWithConfig() + throws Exception { + Configuration config = newConfiguration(); + ServiceBusContract service = ServiceBusService.create(config); + + assertNotNull(service); + assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); + } + + @Test + public void theServiceClassMayAlsoBeCreatedFromConfig() throws Exception { + Configuration config = newConfiguration(); + ServiceBusContract service = config.create(ServiceBusContract.class); + + assertNotNull(service); + assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); + } + + @Test + public void testDefaultBuilderCreatesServiceImpl() throws Exception { + Configuration config = newConfiguration(); + ServiceBusContract service = config.create(ServiceBusContract.class); + + assertNotNull(service); + } + + @Test + public void theServiceClassCanBeCreatedThroughAProfile() throws Exception { + Configuration config = newConfigurationWithProfile(); + ServiceBusContract service = config.create("other", + ServiceBusContract.class); + + assertNotNull(service); + assertEquals(ServiceBusExceptionProcessor.class, service.getClass()); + } + + @Test + public void theServiceClassCanBeCreatedThroughConnectionString() + throws Exception { + Configuration config = newConfigurationWithConnectionString(); + + ServiceBusContract service = config.create(ServiceBusContract.class); + assertNotNull(service); + } +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusIntegrationTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusIntegrationTest.java new file mode 100644 index 0000000000000..50171ed0a861c --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/ServiceBusIntegrationTest.java @@ -0,0 +1,1203 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.core.Builder; +import com.microsoft.windowsazure.core.Builder.Alteration; +import com.microsoft.windowsazure.core.Builder.Registry; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceRequestContext; +import com.microsoft.windowsazure.core.pipeline.filter.ServiceResponseContext; +import com.microsoft.windowsazure.core.pipeline.jersey.ServiceFilter; +import com.microsoft.windowsazure.exception.ServiceException; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import com.microsoft.windowsazure.services.servicebus.implementation.CorrelationFilter; +import com.microsoft.windowsazure.services.servicebus.implementation.EmptyRuleAction; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.FalseFilter; +import com.microsoft.windowsazure.services.servicebus.implementation.MessageCountDetails; +import com.microsoft.windowsazure.services.servicebus.implementation.RuleDescription; +import com.microsoft.windowsazure.services.servicebus.implementation.SqlFilter; +import com.microsoft.windowsazure.services.servicebus.implementation.SqlRuleAction; +import com.microsoft.windowsazure.services.servicebus.implementation.TrueFilter; +import com.microsoft.windowsazure.services.servicebus.models.BrokeredMessage; +import com.microsoft.windowsazure.services.servicebus.models.GetQueueResult; +import com.microsoft.windowsazure.services.servicebus.models.ListQueuesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListRulesResult; +import com.microsoft.windowsazure.services.servicebus.models.ListSubscriptionsResult; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsOptions; +import com.microsoft.windowsazure.services.servicebus.models.ListTopicsResult; +import com.microsoft.windowsazure.services.servicebus.models.QueueInfo; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveMessageOptions; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveQueueMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.ReceiveSubscriptionMessageResult; +import com.microsoft.windowsazure.services.servicebus.models.RuleInfo; +import com.microsoft.windowsazure.services.servicebus.models.SubscriptionInfo; +import com.microsoft.windowsazure.services.servicebus.models.TopicInfo; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.filter.LoggingFilter; + +public class ServiceBusIntegrationTest extends IntegrationTestBase { + + private ServiceBusContract service; + + static ReceiveMessageOptions RECEIVE_AND_DELETE_5_SECONDS = new ReceiveMessageOptions() + .setReceiveAndDelete().setTimeout(5); + static ReceiveMessageOptions PEEK_LOCK_5_SECONDS = new ReceiveMessageOptions() + .setPeekLock().setTimeout(5); + + private String createLongString(int length) { + String result = new String(); + for (int i = 0; i < length; i++) { + result = result + "a"; + } + return result; + } + + @Before + public void createService() throws Exception { + // reinitialize configuration from known state + Configuration config = createConfiguration(); + + // add LoggingFilter to any pipeline that is created + Registry builder = (Registry) config.getBuilder(); + builder.alter(ServiceBusContract.class, Client.class, + new Alteration<Client>() { + @Override + public Client alter(String profile, Client instance, + Builder builder, Map<String, Object> properties) { + instance.addFilter(new LoggingFilter()); + return instance; + } + }); + + // applied as default configuration + Configuration.setInstance(config); + service = ServiceBusService.create(); + } + + @Test + public void fetchQueueAndListQueuesWorks() throws Exception { + // Arrange + + // Act + QueueInfo entry = service.getQueue("TestAlpha").getValue(); + ListQueuesResult feed = service.listQueues(); + + // Assert + assertNotNull(entry); + assertNotNull(feed); + } + + @Test + public void createQueueWorks() throws Exception { + // Arrange + + // Act + QueueInfo queue = new QueueInfo("TestCreateQueueWorks") + .setMaxSizeInMegabytes(1024L); + QueueInfo saved = service.createQueue(queue).getValue(); + + // Assert + assertNotNull(saved); + assertNotSame(queue, saved); + assertEquals(false, saved.isDeadLetteringOnMessageExpiration()); + assertEquals(false, saved.isAnonymousAccessible()); + assertNotNull(saved.getAutoDeleteOnIdle()); + assertEquals(true, saved.isSupportOrdering()); + assertEquals("TestCreateQueueWorks", saved.getPath()); + } + + @Test + public void updateQueueWorks() throws Exception { + // Arrange + QueueInfo queue = new QueueInfo("TestUpdateQueueWorks") + .setMaxSizeInMegabytes(1024L); + QueueInfo originalQueue = service.createQueue(queue).getValue(); + Long expectedMaxSizeInMegaBytes = 512L; + + // Act + QueueInfo updatedQueue = service.updateQueue(originalQueue + .setMaxSizeInMegabytes(512L)); + + // Assert + assertEquals(expectedMaxSizeInMegaBytes, + updatedQueue.getMaxSizeInMegabytes()); + } + + @Test + public void getQueueWorks() throws Exception { + // Arrange + String queuePath = "TestGetQueueWorks"; + service.createQueue(new QueueInfo(queuePath)); + + // Act + GetQueueResult getQueueResult = service.getQueue(queuePath); + + // Assert + assertNotNull(getQueueResult); + + } + + @Test(expected = ServiceException.class) + public void getNonExistQueueFail() throws Exception { + // Arrange + String queuePath = "testGetNonExistQueueFail"; + + // Act + service.getQueue(queuePath); + + // Assert + } + + @Test + public void deleteQueueWorks() throws Exception { + // Arrange + service.createQueue(new QueueInfo("TestDeleteQueueWorks")); + + // Act + service.deleteQueue("TestDeleteQueueWorks"); + + // Assert + } + + @Test + public void sendMessageWorks() throws Exception { + // Arrange + BrokeredMessage message = new BrokeredMessage("sendMessageWorks"); + + // Act + service.sendQueueMessage("TestAlpha", message); + + // Assert + } + + @Test + public void getQueueMessageCountDetails() throws Exception { + // Arrange + String queueName = "testGetQueueMessageCountDetails"; + service.createQueue(new QueueInfo(queueName)); + service.sendQueueMessage(queueName, new BrokeredMessage("Hello World")); + Long expectedActiveMessageCount = 1L; + Long expectedDeadLetterMessageCount = 0L; + Long expectedScheduledMessageCount = 0L; + Long expectedTransferMessageCount = 0L; + Long expectedTransferDeadLetterMessageCount = 0L; + + // Act + QueueInfo queueInfo = service.getQueue(queueName).getValue(); + MessageCountDetails countDetails = queueInfo.getCountDetails(); + + // Assert + assertEquals(true, queueInfo.isSupportOrdering()); + assertNotNull(countDetails); + assertEquals(expectedActiveMessageCount, + countDetails.getActiveMessageCount()); + assertEquals(expectedDeadLetterMessageCount, + countDetails.getDeadLetterMessageCount()); + assertEquals(expectedScheduledMessageCount, + countDetails.getScheduledMessageCount()); + assertEquals(expectedTransferMessageCount, + countDetails.getTransferMessageCount()); + assertEquals(expectedTransferDeadLetterMessageCount, + countDetails.getTransferDeadLetterMessageCount()); + + } + + @Test + public void getTopicMessageCountDetails() throws Exception { + // Arrange + String topicName = "TestGetTopicMessageCountDetails"; + service.createTopic(new TopicInfo(topicName)).getValue(); + Long expectedActiveMessageCount = 0L; + Long expectedDeadLetterMessageCount = 0L; + Long expectedScheduledMessageCount = 0L; + Long expectedTransferMessageCount = 0L; + Long expectedTransferDeadLetterMessageCount = 0L; + + // Act + TopicInfo topicInfo = service.getTopic(topicName).getValue(); + MessageCountDetails countDetails = topicInfo.getCountDetails(); + + // Assert + assertNotNull(topicInfo); + assertNotNull(countDetails); + assertEquals(expectedActiveMessageCount, + countDetails.getActiveMessageCount()); + assertEquals(expectedDeadLetterMessageCount, + countDetails.getDeadLetterMessageCount()); + assertEquals(expectedScheduledMessageCount, + countDetails.getScheduledMessageCount()); + assertEquals(expectedTransferMessageCount, + countDetails.getTransferMessageCount()); + assertEquals(expectedTransferDeadLetterMessageCount, + countDetails.getTransferDeadLetterMessageCount()); + + } + + @Test + public void getSubscriptionMessageCountDetails() throws Exception { + // Arrange + String topicName = "TestGetSubscriptionMessageCountDetails"; + String subscriptionName = "TestGetSubscriptionMessageCountDetails"; + service.createTopic(new TopicInfo(topicName)).getValue(); + service.createSubscription(topicName, new SubscriptionInfo( + subscriptionName)); + Long expectedActiveMessageCount = 1L; + Long expectedDeadLetterMessageCount = 0L; + Long expectedScheduledMessageCount = 0L; + Long expectedTransferMessageCount = 0L; + Long expectedTransferDeadLetterMessageCount = 0L; + + // Act + service.sendTopicMessage(topicName, new BrokeredMessage("Hello world!")); + SubscriptionInfo subscriptionInfo = service.getSubscription(topicName, + subscriptionName).getValue(); + MessageCountDetails countDetails = subscriptionInfo.getCountDetails(); + + // Assert + assertNotNull(subscriptionInfo); + assertNotNull(countDetails); + // TODO: makes the test flickery + /* assertEquals(expectedActiveMessageCount, + countDetails.getActiveMessageCount());*/ + assertEquals(expectedDeadLetterMessageCount, + countDetails.getDeadLetterMessageCount()); + assertEquals(expectedScheduledMessageCount, + countDetails.getScheduledMessageCount()); + assertEquals(expectedTransferMessageCount, + countDetails.getTransferMessageCount()); + assertEquals(expectedTransferDeadLetterMessageCount, + countDetails.getTransferDeadLetterMessageCount()); + } + + @Test + public void receiveMessageWorks() throws Exception { + // Arrange + String queueName = "TestReceiveMessageWorks"; + service.createQueue(new QueueInfo(queueName)); + service.sendQueueMessage(queueName, new BrokeredMessage("Hello World")); + + // Act + BrokeredMessage message = service.receiveQueueMessage(queueName, + RECEIVE_AND_DELETE_5_SECONDS).getValue(); + byte[] data = new byte[100]; + int size = message.getBody().read(data); + + // Assert + assertEquals(11, size); + assertArrayEquals("Hello World".getBytes(), Arrays.copyOf(data, size)); + } + + @Test + public void receiveLargeMessageWorks() throws Exception { + // Arrange + String queueName = "TestReceiveLargeMessageWorks"; + service.createQueue(new QueueInfo(queueName)); + String expectedBody = createLongString(64000); + BrokeredMessage expectedMessage = new BrokeredMessage(expectedBody); + service.sendQueueMessage(queueName, expectedMessage); + + // Act + BrokeredMessage message = service.receiveQueueMessage(queueName, + RECEIVE_AND_DELETE_5_SECONDS).getValue(); + byte[] data = new byte[64000]; + int size = message.getBody().read(data); + + // Assert + assertEquals(expectedBody.length(), size); + assertArrayEquals(expectedBody.getBytes(), Arrays.copyOf(data, size)); + + } + + @Test + public void renewSubscriptionMessageLockWorks() throws Exception { + // Arrange + String topicName = "TestRenewSubscriptionLockMessageWorks"; + String subscriptionName = "renewSubscriptionMessageLockWorks"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo( + subscriptionName)); + service.sendTopicMessage(topicName, new BrokeredMessage("Hello Again")); + + // Act + BrokeredMessage message = service.receiveSubscriptionMessage(topicName, + subscriptionName, PEEK_LOCK_5_SECONDS).getValue(); + service.renewSubscriptionLock(topicName, subscriptionName, + message.getMessageId(), message.getLockToken()); + + // Assert + assertNotNull(message); + } + + @Test + public void renewQueueMessageLockWorks() throws Exception { + // Arrange + String queueName = "TestRenewSubscriptionLockMessageWorks"; + service.createQueue(new QueueInfo(queueName)); + service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); + + // Act + BrokeredMessage message = service.receiveQueueMessage(queueName, + PEEK_LOCK_5_SECONDS).getValue(); + service.renewQueueLock(queueName, message.getMessageId(), + message.getLockToken()); + + // Assert + assertNotNull(message); + } + + @Test + public void receiveMessageEmptyQueueWorks() throws Exception { + // Arrange + String queueName = "TestReceiveMessageEmptyQueueWorks"; + service.createQueue(new QueueInfo(queueName)); + + // Act + ReceiveQueueMessageResult receiveQueueMessageResult = service + .receiveQueueMessage(queueName, RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveQueueMessageResult); + assertNull(receiveQueueMessageResult.getValue()); + } + + @Test + public void receiveQueueForwardToQueueMessageSuccess() throws Exception { + // Arrange + String sourceQueueName = "TestReceiveQueueForwardToQueueMessageSuccessSource"; + String destinationQueueName = "TestReceiveQueueForwardToQueueMessageSuccessDestination"; + QueueInfo destinationQueueInfo = service.createQueue( + new QueueInfo(destinationQueueName)).getValue(); + service.createQueue( + new QueueInfo(sourceQueueName) + .setForwardTo(destinationQueueInfo.getUri().toString())) + .getValue(); + + // Act + service.sendQueueMessage(sourceQueueName, new BrokeredMessage( + "Hello source queue!")); + ReceiveQueueMessageResult receiveQueueMessageResult = service + .receiveQueueMessage(destinationQueueName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveQueueMessageResult); + assertNotNull(receiveQueueMessageResult.getValue()); + } + + @Test + public void receiveUpdatedQueueForwardToQueueMessageSuccess() + throws Exception { + // Arrange + String sourceQueueName = "TestReceiveUpdatedQueueForwardToQueueMessageSuccessSource"; + String destinationQueueName = "TestReceiveUpdatedQueueForwardToQueueMessageSuccessDestination"; + QueueInfo destinationQueueInfo = service.createQueue( + new QueueInfo(destinationQueueName)).getValue(); + QueueInfo sourceQueueInfo = new QueueInfo(sourceQueueName); + service.createQueue(sourceQueueInfo).getValue(); + service.updateQueue(sourceQueueInfo.setForwardTo(destinationQueueInfo + .getUri().toString())); + + // Act + service.sendQueueMessage(sourceQueueName, new BrokeredMessage( + "Hello source queue!")); + ReceiveQueueMessageResult receiveQueueMessageResult = service + .receiveQueueMessage(destinationQueueName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveQueueMessageResult); + assertNotNull(receiveQueueMessageResult.getValue()); + } + + @Test + public void receiveSubscriptionForwardToQueueMessageSuccess() + throws Exception { + // Arrange + String sourceTopicName = "TestReceiveSubForwardToQueueMessageSuccessSource"; + String sourceSubscriptionName = "TestReceiveSubForwardToQueueMessageSuccessSource"; + String destinationQueueName = "TestReceiveSubForwardToQueueMessageSuccessDestination"; + service.createTopic(new TopicInfo(sourceTopicName)).getValue(); + QueueInfo destinationQueueInfo = service.createQueue( + new QueueInfo(destinationQueueName)).getValue(); + service.createSubscription(sourceTopicName, new SubscriptionInfo( + sourceSubscriptionName).setForwardTo(destinationQueueInfo + .getUri().toString())); + + // Act + service.sendTopicMessage(sourceTopicName, new BrokeredMessage( + "Hello source queue!")); + ReceiveQueueMessageResult receiveQueueMessageResult = service + .receiveQueueMessage(destinationQueueName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveQueueMessageResult); + assertNotNull(receiveQueueMessageResult.getValue()); + } + + @Test + public void receiveUpdatedSubscriptionForwardToQueueMessageSuccess() + throws Exception { + // Arrange + String sourceTopicName = "TestUpdatedReceiveSubForwardToQMessageSuccessSrc"; + String sourceSubscriptionName = "TestUpdatedReceiveSubForwardToQMessageSuccessSrc"; + String destinationQueueName = "TestUpdatedReceiveSubForwardToQMessageSuccessDest"; + service.createTopic(new TopicInfo(sourceTopicName)).getValue(); + QueueInfo destinationQueueInfo = service.createQueue( + new QueueInfo(destinationQueueName)).getValue(); + SubscriptionInfo sourceSubscriptionInfo = service.createSubscription( + sourceTopicName, new SubscriptionInfo(sourceSubscriptionName)) + .getValue(); + service.updateSubscription(sourceTopicName, sourceSubscriptionInfo + .setForwardTo(destinationQueueInfo.getUri().toString())); + // Act + service.sendTopicMessage(sourceTopicName, new BrokeredMessage( + "Hello source queue!")); + ReceiveQueueMessageResult receiveQueueMessageResult = service + .receiveQueueMessage(destinationQueueName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveQueueMessageResult); + assertNotNull(receiveQueueMessageResult.getValue()); + } + + @Test + public void receiveQueueForwardToTopicMessageSuccess() throws Exception { + // Arrange + String sourceQueueName = "TestReceiveQueueForwardToTopicMessageSuccessSource"; + String destinationTopicName = "TestReceiveQueueForwardToTopicMessageSuccessDestination"; + String destinationSubscriptionName = "TestReceiveQueueForwardToTopicMessageSuccessDestination"; + TopicInfo destinationTopicInfo = service.createTopic( + new TopicInfo(destinationTopicName)).getValue(); + service.createQueue( + new QueueInfo(sourceQueueName) + .setForwardTo(destinationTopicInfo.getUri().toString())) + .getValue(); + + // Act + service.sendQueueMessage(sourceQueueName, new BrokeredMessage( + "Hello source queue!")); + ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service + .receiveSubscriptionMessage(destinationTopicName, + destinationSubscriptionName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveSubscriptionMessageResult); + assertNotNull(receiveSubscriptionMessageResult.getValue()); + } + + @Test + @Ignore("Ignore because inconsistent server behavior.") + public void receiveUpdatedQueueForwardToTopicMessageSuccess() + throws Exception { + // Arrange + String sourceQueueName = "TestReceiveUpdatedQueueForwardToTopicMessageSuccessSource"; + String destinationTopicName = "TestReceiveUpdatedQueueForwardToTopicMessageSuccessDestination"; + String destinationSubscriptionName = "TestReceiveUpdatedQueueForwardToTopicMessageSuccessDestination"; + TopicInfo destinationTopicInfo = service.createTopic( + new TopicInfo(destinationTopicName)).getValue(); + QueueInfo sourceQueueInfo = new QueueInfo(sourceQueueName); + service.createQueue(sourceQueueInfo).getValue(); + service.updateQueue(sourceQueueInfo.setForwardTo(destinationTopicInfo + .getUri().toString())); + + // Act + service.sendQueueMessage(sourceQueueName, new BrokeredMessage( + "Hello source queue!")); + ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service + .receiveSubscriptionMessage(destinationTopicName, + destinationSubscriptionName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveSubscriptionMessageResult); + assertNotNull(receiveSubscriptionMessageResult.getValue()); + } + + @Test + @Ignore("due to inconsistent server behavior.") + public void receiveSubscriptionForwardToTopicMessageSuccess() + throws Exception { + // Arrange + String sourceTopicName = "TestReceiveSubForwardToTopMessageSuccessSrc"; + String sourceSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessSrc"; + String destinationTopicName = "TestReceiveSubForwardToTopMessageSuccessDest"; + String destinationSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessDest"; + service.createTopic(new TopicInfo(sourceTopicName)).getValue(); + TopicInfo destinationTopicInfo = service.createTopic( + new TopicInfo(destinationTopicName)).getValue(); + service.createSubscription(destinationTopicName, + new SubscriptionInfo(destinationSubscriptionName)).getValue(); + service.createSubscription(sourceTopicName, new SubscriptionInfo( + sourceSubscriptionName).setForwardTo(destinationTopicInfo + .getUri().toString())); + + // Act + service.sendTopicMessage(sourceTopicName, new BrokeredMessage( + "Hello source queue!")); + ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service + .receiveSubscriptionMessage(destinationTopicName, + destinationSubscriptionName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveSubscriptionMessageResult); + assertNotNull(receiveSubscriptionMessageResult.getValue()); + } + + @Test + @Ignore("due to inconsistent server behavior.") + public void receiveUpdatedSubscriptionForwardToTopicMessageSuccess() + throws Exception { + // Arrange + String sourceTopicName = "TestReceiveSubForwardToTopMessageSuccessSrc"; + String sourceSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessSrc"; + String destinationTopicName = "TestReceiveSubForwardToTopMessageSuccessDest"; + String destinationSubscriptionName = "TestReceiveSubForwardToTopMessageSuccessDest"; + service.createTopic(new TopicInfo(sourceTopicName)).getValue(); + TopicInfo destinationTopicInfo = service.createTopic( + new TopicInfo(destinationTopicName)).getValue(); + service.createSubscription(destinationTopicName, + new SubscriptionInfo(destinationSubscriptionName)).getValue(); + SubscriptionInfo sourceSubscriptionInfo = service.createSubscription( + sourceTopicName, new SubscriptionInfo(sourceSubscriptionName)) + .getValue(); + service.updateSubscription(sourceTopicName, sourceSubscriptionInfo + .setForwardTo(destinationTopicInfo.getUri().toString())); + Thread.sleep(1000); + + // Act + service.sendTopicMessage(sourceTopicName, new BrokeredMessage( + "Hello source queue!")); + ReceiveSubscriptionMessageResult receiveSubscriptionMessageResult = service + .receiveSubscriptionMessage(destinationTopicName, + destinationSubscriptionName, + RECEIVE_AND_DELETE_5_SECONDS); + + // Assert + assertNotNull(receiveSubscriptionMessageResult); + assertNotNull(receiveSubscriptionMessageResult.getValue()); + } + + @Test + public void peekLockMessageWorks() throws Exception { + // Arrange + String queueName = "TestPeekLockMessageWorks"; + service.createQueue(new QueueInfo(queueName)); + service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); + + // Act + BrokeredMessage message = service.receiveQueueMessage(queueName, + PEEK_LOCK_5_SECONDS).getValue(); + + // Assert + byte[] data = new byte[100]; + int size = message.getBody().read(data); + assertEquals(11, size); + assertEquals("Hello Again", new String(data, 0, size)); + } + + @Test + public void peekLockMessageEmptyQueueWorks() throws Exception { + // Arrange + String queueName = "TestPeekLockMessageEmptyQueueWorks"; + service.createQueue(new QueueInfo(queueName)); + + // Act + ReceiveQueueMessageResult result = service.receiveQueueMessage( + queueName, PEEK_LOCK_5_SECONDS); + + // Assert + assertNotNull(result); + assertNull(result.getValue()); + } + + @Test + public void peekLockedMessageCanBeCompleted() throws Exception { + // Arrange + String queueName = "TestPeekLockedMessageCanBeCompleted"; + service.createQueue(new QueueInfo(queueName)); + service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); + BrokeredMessage message = service.receiveQueueMessage(queueName, + PEEK_LOCK_5_SECONDS).getValue(); + + // Act + String lockToken = message.getLockToken(); + Date lockedUntil = message.getLockedUntilUtc(); + String lockLocation = message.getLockLocation(); + + service.deleteMessage(message); + + // Assert + assertNotNull(lockToken); + assertNotNull(lockedUntil); + assertNotNull(lockLocation); + } + + @Test + public void peekLockedMessageCanBeUnlocked() throws Exception { + // Arrange + String queueName = "TestPeekLockedMessageCanBeUnlocked"; + service.createQueue(new QueueInfo(queueName)); + service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); + BrokeredMessage peekedMessage = service.receiveQueueMessage(queueName, + PEEK_LOCK_5_SECONDS).getValue(); + + // Act + String lockToken = peekedMessage.getLockToken(); + Date lockedUntil = peekedMessage.getLockedUntilUtc(); + + service.unlockMessage(peekedMessage); + BrokeredMessage receivedMessage = service.receiveQueueMessage( + queueName, RECEIVE_AND_DELETE_5_SECONDS).getValue(); + + // Assert + assertNotNull(lockToken); + assertNotNull(lockedUntil); + assertNull(receivedMessage.getLockToken()); + assertNull(receivedMessage.getLockedUntilUtc()); + } + + @Test + public void peekLockedMessageCanBeDeleted() throws Exception { + // Arrange + String queueName = "TestPeekLockedMessageCanBeDeleted"; + service.createQueue(new QueueInfo(queueName)); + service.sendQueueMessage(queueName, new BrokeredMessage("Hello Again")); + BrokeredMessage peekedMessage = service.receiveQueueMessage(queueName, + PEEK_LOCK_5_SECONDS).getValue(); + + // Act + String lockToken = peekedMessage.getLockToken(); + Date lockedUntil = peekedMessage.getLockedUntilUtc(); + + service.deleteMessage(peekedMessage); + BrokeredMessage receivedMessage = service.receiveQueueMessage( + queueName, RECEIVE_AND_DELETE_5_SECONDS).getValue(); + + // Assert + assertNotNull(lockToken); + assertNotNull(lockedUntil); + assertNull(receivedMessage); + } + + @Test + public void emptyQueueReturnsNullMessage() throws Exception { + // Arrange + String queueName = "testEmptyQueueReturnsNullMessage"; + service.createQueue(new QueueInfo(queueName)); + + // Act + BrokeredMessage brokeredMessage = service.receiveQueueMessage( + queueName, PEEK_LOCK_5_SECONDS).getValue(); + + // Assert + assertNull(brokeredMessage); + } + + @Test + public void contentTypePassesThrough() throws Exception { + // Arrange + String queueName = "TestContentTypePassesThrough"; + service.createQueue(new QueueInfo(queueName)); + + // Act + service.sendQueueMessage(queueName, new BrokeredMessage( + "<data>Hello Again</data>").setContentType("text/xml")); + + BrokeredMessage message = service.receiveQueueMessage(queueName, + RECEIVE_AND_DELETE_5_SECONDS).getValue(); + + // Assert + assertNotNull(message); + assertEquals("text/xml", message.getContentType()); + } + + @Test + public void topicCanBeCreatedListedFetchedAndDeleted() + throws ServiceException { + // Arrange + String topicName = "TestTopicCanBeCreatedListedFetchedAndDeleted"; + + // Act + TopicInfo created = service.createTopic( + new TopicInfo().setPath(topicName)).getValue(); + ListTopicsResult listed = service.listTopics(); + TopicInfo fetched = service.getTopic(topicName).getValue(); + service.deleteTopic(topicName); + ListTopicsResult listed2 = service.listTopics(); + + // Assert + assertNotNull(created); + assertNotNull(listed); + assertNotNull(fetched); + assertNotNull(listed2); + + assertEquals(listed.getItems().size() - 1, listed2.getItems().size()); + } + + @Test + public void listTopicsUnderASpecificPath() throws ServiceException { + // Arrange + String topicName = "testPathA/testPathB/listTopicUnderASpecificPath"; + + // Act + TopicInfo topicInfo = service.createTopic( + new TopicInfo().setPath(topicName)).getValue(); + ListTopicsResult listTopicResult = service + .listTopics(new ListTopicsOptions() + .setFilter("startswith(path, 'testPathA/testPathB') eq true")); + + // Assert + assertNotNull(topicInfo); + assertEquals(1, listTopicResult.getItems().size()); + } + + @Test + public void listTopicsUpdatedInLastFiveMinutes() throws ServiceException { + String topicName = "testListTopicUpdatedInLastFiveMinutes"; + + // Act + TopicInfo topicInfo = service.createTopic( + new TopicInfo().setPath(topicName)).getValue(); + ListTopicsResult listTopicResult = service + .listTopics(new ListTopicsOptions() + .setFilter("ModifiedAt gt '1/25/2012 3:41:41 PM'")); + + // Assert + assertNotNull(topicInfo); + assertEquals(1, listTopicResult.getItems().size()); + } + + @Test + public void listTopicsAccessedSinceASpecificTime() throws ServiceException { + removeTopics(); + String topicName = "testListTopicAccessedInLastFiveMinutes"; + + // Act + TopicInfo topicInfo = service.createTopic( + new TopicInfo().setPath(topicName)).getValue(); + ListTopicsResult listTopicResult = service + .listTopics(new ListTopicsOptions() + .setFilter("AccessedAt gt '1/25/2012 3:41:41 PM'")); + + // Assert + assertNotNull(topicInfo); + assertEquals(0, listTopicResult.getItems().size()); + } + + @Test + public void listTopicsCreatedSinceASpecificTime() throws ServiceException { + removeTopics(); + String topicName = "testListTopicCreatedInLastFiveMinutes"; + + // Act + TopicInfo topicInfo = service.createTopic( + new TopicInfo().setPath(topicName)).getValue(); + ListTopicsResult listTopicResult = service + .listTopics(new ListTopicsOptions() + .setFilter("CreatedAt gt '1/25/2012 3:41:41 PM'")); + + // Assert + assertNotNull(topicInfo); + assertEquals(1, listTopicResult.getItems().size()); + } + + @Test + public void topicCreatedContainsMetadata() throws ServiceException { + // Arrange + String topicName = "TestTopicCreatedContainsMetadata"; + + // Act + TopicInfo createdTopicInfo = service.createTopic( + new TopicInfo().setPath(topicName)).getValue(); + + // Assert + assertNotNull(createdTopicInfo); + assertNotNull(createdTopicInfo.getAutoDeleteOnIdle()); + assertEquals(false, createdTopicInfo.isRequiresDuplicateDetection()); + assertEquals(false, + createdTopicInfo.isFilteringMessageBeforePublishing()); + assertEquals(EntityStatus.ACTIVE, createdTopicInfo.getStatus()); + assertEquals(true, createdTopicInfo.isSupportOrdering()); + assertEquals(false, createdTopicInfo.isAnonymousAccessible()); + + } + + @Test + public void topicCanBeUpdated() throws ServiceException { + // Arrange + String topicName = "testTopicCanBeUpdated"; + Long expectedMaxSizeInMegabytes = 2048L; + + // Act + TopicInfo createdTopicInfo = service + .createTopic( + new TopicInfo().setPath(topicName) + .setMaxSizeInMegabytes(1024L)).getValue(); + TopicInfo updatedTopicInfo = service.updateTopic(createdTopicInfo + .setMaxSizeInMegabytes(expectedMaxSizeInMegabytes)); + + // Assert + assertEquals(expectedMaxSizeInMegabytes, + updatedTopicInfo.getMaxSizeInMegabytes()); + } + + @Test + public void filterCanSeeAndChangeRequestOrResponse() + throws ServiceException { + // Arrange + final List<ServiceRequestContext> requests = new ArrayList<ServiceRequestContext>(); + final List<ServiceResponseContext> responses = new ArrayList<ServiceResponseContext>(); + + ServiceBusContract filtered = service.withFilter(new ServiceFilter() { + @Override + public ServiceResponseContext handle(ServiceRequestContext request, + Next next) throws Exception { + requests.add(request); + ServiceResponseContext response = next.handle(request); + responses.add(response); + return response; + } + }); + + // Act + QueueInfo created = filtered.createQueue( + new QueueInfo("TestFilterCanSeeAndChangeRequestOrResponse")) + .getValue(); + + // Assert + assertNotNull(created); + assertEquals(1, requests.size()); + assertEquals(1, responses.size()); + } + + @Test + public void subscriptionsCanBeCreatedOnTopics() throws Exception { + // Arrange + String topicName = "TestSubscriptionsCanBeCreatedOnTopics"; + service.createTopic(new TopicInfo(topicName)); + + // Act + SubscriptionInfo created = service.createSubscription(topicName, + new SubscriptionInfo("MySubscription")).getValue(); + + // Assert + assertNotNull(created); + assertEquals("MySubscription", created.getName()); + assertEquals(false, created.isRequiresSession()); + assertEquals(true, + created.isDeadLetteringOnFilterEvaluationExceptions()); + assertNotNull(created.getCreatedAt()); + assertNotNull(created.getUpdatedAt()); + assertNotNull(created.getAccessedAt()); + assertNotNull(created.getAutoDeleteOnIdle()); + } + + @Test + public void createSubscriptionWithCorrelationFilter() throws Exception { + // Arrange + String topicName = "testCreateSubscriptionWithCorrelationFilter"; + String expectedCorrelationId = "sampleCorrelationId"; + String expectedContentType = "sampleContentType"; + String expectedLabel = "sampleLabel"; + String expectedMessageId = "sampleMessageId"; + String expectedSessionId = "sampleSessionId"; + String expectedReplyTo = "sampleReplyTo"; + String expectedTo = "sampleTo"; + service.createTopic(new TopicInfo(topicName)); + CorrelationFilter correlationFilter = new CorrelationFilter(); + correlationFilter.setCorrelationId(expectedCorrelationId); + correlationFilter.setContentType(expectedContentType); + correlationFilter.setLabel(expectedLabel); + correlationFilter.setMessageId(expectedMessageId); + correlationFilter.setReplyTo(expectedReplyTo); + correlationFilter.setSessionId(expectedSessionId); + correlationFilter.setTo(expectedTo); + RuleDescription ruleDescription = new RuleDescription(); + ruleDescription.setFilter(correlationFilter); + + // Act + SubscriptionInfo created = service.createSubscription( + topicName, + new SubscriptionInfo("MySubscription") + .setDefaultRuleDescription(ruleDescription)).getValue(); + + RuleInfo ruleInfo = service.getRule(topicName, "MySubscription", + "$Default").getValue(); + CorrelationFilter correlationFilterResult = (CorrelationFilter) ruleInfo + .getFilter(); + + // Assert + assertNotNull(created); + assertEquals("MySubscription", created.getName()); + assertEquals(false, created.isRequiresSession()); + assertEquals(true, + created.isDeadLetteringOnFilterEvaluationExceptions()); + assertNotNull(created.getCreatedAt()); + assertNotNull(created.getUpdatedAt()); + assertNotNull(created.getAccessedAt()); + assertNotNull(created.getAutoDeleteOnIdle()); + assertNotNull(correlationFilterResult); + assertEquals(expectedCorrelationId, + correlationFilterResult.getCorrelationId()); + assertEquals(expectedContentType, + correlationFilterResult.getContentType()); + assertEquals(expectedLabel, correlationFilterResult.getLabel()); + assertEquals(expectedMessageId, correlationFilterResult.getMessageId()); + assertEquals(expectedSessionId, correlationFilterResult.getSessionId()); + assertEquals(expectedReplyTo, correlationFilterResult.getReplyTo()); + assertEquals(expectedTo, correlationFilterResult.getTo()); + } + + @Test + public void subscriptionsCanBeListed() throws Exception { + // Arrange + String topicName = "TestSubscriptionsCanBeListed"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo( + "MySubscription2")); + + // Act + ListSubscriptionsResult result = service.listSubscriptions(topicName); + + // Assert + assertNotNull(result); + assertEquals(1, result.getItems().size()); + assertEquals("MySubscription2", result.getItems().get(0).getName()); + } + + @Test + public void subscriptionsDetailsMayBeFetched() throws Exception { + // Arrange + String topicName = "TestSubscriptionsDetailsMayBeFetched"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo( + "MySubscription3")); + + // Act + SubscriptionInfo result = service.getSubscription(topicName, + "MySubscription3").getValue(); + + // Assert + assertNotNull(result); + assertEquals("MySubscription3", result.getName()); + } + + @Test + public void subscriptionsMayBeDeleted() throws Exception { + // Arrange + String topicName = "TestSubscriptionsMayBeDeleted"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo( + "MySubscription4")); + service.createSubscription(topicName, new SubscriptionInfo( + "MySubscription5")); + + // Act + service.deleteSubscription(topicName, "MySubscription4"); + + // Assert + ListSubscriptionsResult result = service.listSubscriptions(topicName); + assertNotNull(result); + assertEquals(1, result.getItems().size()); + assertEquals("MySubscription5", result.getItems().get(0).getName()); + } + + @Test + public void subscriptionWillReceiveMessage() throws Exception { + // Arrange + String topicName = "TestSubscriptionWillReceiveMessage"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo("sub")); + service.sendTopicMessage(topicName, new BrokeredMessage( + "<p>Testing subscription</p>").setContentType("text/html")); + + // Act + BrokeredMessage message = service.receiveSubscriptionMessage(topicName, + "sub", RECEIVE_AND_DELETE_5_SECONDS).getValue(); + + // Assert + assertNotNull(message); + + byte[] data = new byte[100]; + int size = message.getBody().read(data); + assertEquals("<p>Testing subscription</p>", new String(data, 0, size)); + assertEquals("text/html", message.getContentType()); + } + + @Test + public void subscriptionCanBeUpdated() throws Exception { + // Arrange + String topicName = "testSubscriptionCanBeUpdated"; + service.createTopic(new TopicInfo(topicName)); + SubscriptionInfo originalSubscription = service.createSubscription( + topicName, new SubscriptionInfo("sub")).getValue(); + Integer expectedMaxDeliveryCount = 1024; + + // Act + SubscriptionInfo updatedSubscription = service.updateSubscription( + topicName, originalSubscription + .setMaxDeliveryCount(expectedMaxDeliveryCount)); + + // Assert + assertEquals(expectedMaxDeliveryCount, + updatedSubscription.getMaxDeliveryCount()); + } + + @Test + public void rulesCanBeCreatedOnSubscriptions() throws Exception { + // Arrange + String topicName = "TestrulesCanBeCreatedOnSubscriptions"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo("sub")); + + // Act + RuleInfo created = service.createRule(topicName, "sub", + new RuleInfo("MyRule1")).getValue(); + + // Assert + assertNotNull(created); + assertEquals("MyRule1", created.getName()); + } + + @Test + public void rulesCanBeListedAndDefaultRuleIsPrecreated() throws Exception { + // Arrange + String topicName = "TestrulesCanBeListedAndDefaultRuleIsPrecreated"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo("sub")); + service.createRule(topicName, "sub", new RuleInfo("MyRule2")); + + // Act + ListRulesResult result = service.listRules(topicName, "sub"); + + // Assert + assertNotNull(result); + assertEquals(2, result.getItems().size()); + RuleInfo rule0 = result.getItems().get(0); + RuleInfo rule1 = result.getItems().get(1); + if (rule0.getName() == "MyRule2") { + RuleInfo swap = rule1; + rule1 = rule0; + rule0 = swap; + } + + assertEquals("$Default", rule0.getName()); + assertEquals("MyRule2", rule1.getName()); + assertNotNull(result.getItems().get(0).getModel()); + } + + @Test + public void ruleDetailsMayBeFetched() throws Exception { + // Arrange + String topicName = "TestruleDetailsMayBeFetched"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo("sub")); + + // Act + RuleInfo result = service.getRule(topicName, "sub", "$Default") + .getValue(); + + // Assert + assertNotNull(result); + assertEquals("$Default", result.getName()); + } + + @Test + public void rulesMayBeDeleted() throws Exception { + // Arrange + String topicName = "TestRulesMayBeDeleted"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo("sub")); + service.createRule(topicName, "sub", new RuleInfo("MyRule4")); + service.createRule(topicName, "sub", new RuleInfo("MyRule5")); + + // Act + service.deleteRule(topicName, "sub", "MyRule5"); + service.deleteRule(topicName, "sub", "$Default"); + + // Assert + ListRulesResult result = service.listRules(topicName, "sub"); + assertNotNull(result); + assertEquals(1, result.getItems().size()); + assertEquals("MyRule4", result.getItems().get(0).getName()); + } + + @Test + public void rulesMayHaveActionAndFilter() throws ServiceException { + // Arrange + String topicName = "TestRulesMayHaveAnActionAndFilter"; + service.createTopic(new TopicInfo(topicName)); + service.createSubscription(topicName, new SubscriptionInfo("sub")); + + // Act + RuleInfo ruleOne = service.createRule(topicName, "sub", + new RuleInfo("One").withCorrelationIdFilter("my-id")) + .getValue(); + RuleInfo ruleTwo = service.createRule(topicName, "sub", + new RuleInfo("Two").withTrueFilter()).getValue(); + RuleInfo ruleThree = service.createRule(topicName, "sub", + new RuleInfo("Three").withFalseFilter()).getValue(); + RuleInfo ruleFour = service.createRule(topicName, "sub", + new RuleInfo("Four").withEmptyRuleAction()).getValue(); + RuleInfo ruleFive = service.createRule(topicName, "sub", + new RuleInfo("Five").withSqlRuleAction("SET x = 5")).getValue(); + RuleInfo ruleSix = service.createRule(topicName, "sub", + new RuleInfo("Six").withSqlExpressionFilter("x != 5")) + .getValue(); + + // Assert + assertEquals(CorrelationFilter.class, ruleOne.getFilter().getClass()); + assertEquals(TrueFilter.class, ruleTwo.getFilter().getClass()); + assertEquals(FalseFilter.class, ruleThree.getFilter().getClass()); + assertEquals(EmptyRuleAction.class, ruleFour.getAction().getClass()); + assertEquals(SqlRuleAction.class, ruleFive.getAction().getClass()); + assertEquals(SqlFilter.class, ruleSix.getFilter().getClass()); + + } + + @Test + public void messagesMayHaveCustomProperties() throws ServiceException { + // Arrange + String queueName = "TestMessagesMayHaveCustomProperties"; + service.createQueue(new QueueInfo(queueName)); + + // Act + service.sendQueueMessage(queueName, new BrokeredMessage("") + .setProperty("hello", "world").setProperty("foo", 42)); + BrokeredMessage message = service.receiveQueueMessage(queueName, + RECEIVE_AND_DELETE_5_SECONDS).getValue(); + + // Assert + assertEquals("world", message.getProperty("hello")); + assertEquals(42, message.getProperty("foo")); + } +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/CustomPropertiesMapperTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/CustomPropertiesMapperTest.java new file mode 100644 index 0000000000000..ed61438db62af --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/CustomPropertiesMapperTest.java @@ -0,0 +1,144 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import static org.junit.Assert.*; + +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; + +public class CustomPropertiesMapperTest { + private CustomPropertiesMapper mapper; + + @Before + public void init() { + mapper = new CustomPropertiesMapper(); + } + + @Test + public void stringValuesShouldComeThroughInQuotes() { + // Arrange + + // Act + String text = mapper.toString("This is a string"); + + // Assert + assertEquals("\"This is a string\"", text); + } + + @Test + public void nonStringValuesShouldNotHaveQuotes() { + // Arrange + + // Act + String text = mapper.toString(78); + + // Assert + assertEquals("78", text); + } + + @Test + public void supportedJavaTypesHaveExpectedRepresentations() { + // Arrange + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + cal.set(1971, Calendar.OCTOBER, 14, 12, 34, 56); + + // Act + + // Assert + // assertEquals("78;byte", mapper.toString((byte) 78)); + assertEquals("78", mapper.toString((byte) 78)); + assertEquals("\"a\"", mapper.toString('a')); + assertEquals("-78", mapper.toString((short) -78)); + // assertEquals("78;ushort", mapper.toString((unsigned short)78); + assertEquals("-78", mapper.toString(-78)); + // assertEquals("78;uint", mapper.toString(78)); + assertEquals("-78", mapper.toString((long) -78)); + // assertEquals("78;ulong", mapper.toString(78)); + assertEquals("78.5", mapper.toString((float) 78.5)); + assertEquals("78.5", mapper.toString(78.5)); + // assertEquals("78;decimal", mapper.toString(78)); + assertEquals("true", mapper.toString(true)); + assertEquals("false", mapper.toString(false)); + assertEquals("\"12345678-9abc-def0-9abc-def012345678\"", + mapper.toString(new UUID(0x123456789abcdef0L, + 0x9abcdef012345678L))); + assertEquals("\"Thu, 14 Oct 1971 12:34:56 GMT\"", mapper.toString(cal)); + assertEquals("\"Thu, 14 Oct 1971 12:34:56 GMT\"", + mapper.toString(cal.getTime())); + // assertEquals("78;date-seconds", mapper.toString(78)); + } + + @Test + public void valuesComeBackAsStringsWhenInQuotes() throws ParseException { + // Arrange + + // Act + Object value = mapper.fromString("\"Hello world\""); + + // Assert + assertEquals("Hello world", value); + assertEquals(String.class, value.getClass()); + } + + @Test + public void nonStringTypesWillBeParsedAsNumeric() throws ParseException { + // Arrange + + // Act + Object value = mapper.fromString("5"); + + // Assert + assertEquals(5, value); + assertEquals(Integer.class, value.getClass()); + } + + @Test + public void supportedFormatsHaveExpectedJavaTypes() throws ParseException { + // Arrange + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + cal.set(1971, Calendar.OCTOBER, 14, 12, 34, 56); + + // Act + Date dt = (Date) mapper.fromString("\"Thu, 14 Oct 1971 12:34:56 GMT\""); + + // Assert + // assertEquals("78;byte", mapper.toString((byte) 78)); + // assertEquals((byte) 78, mapper.fromString("78")); + // assertEquals('a', mapper.fromString("a;char")); + // assertEquals((short) -78, mapper.fromString("-78;short")); + // assertEquals("78;ushort", mapper.toString((unsigned short)78); + assertEquals(-78, mapper.fromString("-78")); + // assertEquals("78;uint", mapper.toString(78)); + // assertEquals((long) -78, mapper.fromString("-78;long")); + // assertEquals("78;ulong", mapper.toString(78)); + // assertEquals((float) 78.5, mapper.fromString("78.5;float")); + assertEquals(78.5, mapper.fromString("78.5")); + // assertEquals("78;decimal", mapper.toString(78)); + assertEquals(true, mapper.fromString("true")); + assertEquals(false, mapper.fromString("false")); + // assertEquals(new UUID(0x123456789abcdef0L, 0x9abcdef012345678L), + // mapper.fromString("12345678-9abc-def0-9abc-def012345678;uuid")); + + assertEquals(cal.getTime().getTime(), dt.getTime(), 1000); + // assertEquals("78;date-seconds", mapper.toString(78)); + } +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionSettingsTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionSettingsTest.java new file mode 100644 index 0000000000000..0abecc3f23c22 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/ServiceBusConnectionSettingsTest.java @@ -0,0 +1,136 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.Configuration; +import static junit.framework.Assert.*; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.servicebus.ServiceBusConfiguration; + +public class ServiceBusConnectionSettingsTest { + + @Test + public void settingsAreParsedFromConnectionString() throws Exception { + String ns = "myNamespace"; + String issuer = "myissuer"; + String secret = "mysecret"; + + String connectionString = getConnectionString(ns, issuer, secret); + + ServiceBusConnectionSettings settings = new ServiceBusConnectionSettings( + connectionString, null, null, null, null); + + assertEquals(String.format("https://%1$s.servicebus.windows.net/", ns), + settings.getUri()); + assertEquals(String.format( + "https://%1$s-sb.accesscontrol.windows.net/WRAPv0.9", ns), + settings.getWrapUri()); + assertEquals(issuer, settings.getWrapName()); + assertEquals(secret, settings.getWrapPassword()); + } + + private String getConnectionString(String ns, String issuer, String secret) { + return String + .format("Endpoint=sb://%1$s.servicebus.windows.net/;SharedSecretIssuer=%2$s;SharedSecretValue=%3$s", + ns, issuer, secret); + } + + private String getConnectionString(String ns, String stsEndpoint, + String issuer, String secret) { + return String + .format("Endpoint=sb://%1$s.servicebus.windows.net/;StsEndpoint=https://%1$s%4$s;SharedSecretIssuer=%2$s;SharedSecretValue=%3$s", + ns, issuer, secret, stsEndpoint); + } + + @Test + public void settingsAreUsedFromConnectionStringInConfig() throws Exception { + Configuration config = Configuration.load(); + ServiceBusConfiguration.configureWithConnectionString(null, config, + getConnectionString("myNamespace", "owner", "secret")); + + ServiceBusConnectionSettings settings = config + .create(ServiceBusConnectionSettings.class); + + assertEquals("https://myNamespace.servicebus.windows.net/", + settings.getUri()); + assertEquals( + "https://myNamespace-sb.accesscontrol.windows.net/WRAPv0.9", + settings.getWrapUri()); + assertEquals("owner", settings.getWrapName()); + assertEquals("secret", settings.getWrapPassword()); + } + + @Test + public void settingsAreUsedFromIndividualSettingsInConfiguration() + throws Exception { + Configuration config = Configuration.load(); + + ServiceBusConfiguration.configureWithWrapAuthentication(config, + "myNamespace", "owner", "secret", ".servicebus.windows.net/", + "-sb.accesscontrol.windows.net/WRAPv0.9"); + + ServiceBusConnectionSettings settings = config + .create(ServiceBusConnectionSettings.class); + + assertEquals("https://myNamespace.servicebus.windows.net/", + settings.getUri()); + assertEquals( + "https://myNamespace-sb.accesscontrol.windows.net/WRAPv0.9", + settings.getWrapUri()); + assertEquals("owner", settings.getWrapName()); + assertEquals("secret", settings.getWrapPassword()); + } + + @Test + public void settingsPreferConnectionStringIfBothPresentInConfiguration() + throws Exception { + Configuration config = Configuration.load(); + + ServiceBusConfiguration.configureWithWrapAuthentication(config, + "myIndividualNamespace", "individualowner", "individualsecret", + ".servicebus.windows.net/", + "-sb.accesscontrol.windows.net/WRAPv0.9"); + + ServiceBusConfiguration.configureWithConnectionString(null, config, + getConnectionString("myNamespaceCS", "ownerCS", "secretCS")); + + ServiceBusConnectionSettings settings = config + .create(ServiceBusConnectionSettings.class); + + assertEquals("https://myNamespaceCS.servicebus.windows.net/", + settings.getUri()); + assertEquals( + "https://myNamespaceCS-sb.accesscontrol.windows.net/WRAPv0.9", + settings.getWrapUri()); + assertEquals("ownerCS", settings.getWrapName()); + assertEquals("secretCS", settings.getWrapPassword()); + } + + @Test + public void canSetStSEndPointInConnectionString() throws Exception { + ServiceBusConnectionSettings settings = new ServiceBusConnectionSettings( + getConnectionString("myNs", "-some.accesscontrol.net", "owner", + "secret"), null, null, null, null); + + assertEquals("https://myNs.servicebus.windows.net/", settings.getUri()); + assertEquals("https://myNs-some.accesscontrol.net/WRAPv0.9", + settings.getWrapUri()); + assertEquals("owner", settings.getWrapName()); + assertEquals("secret", settings.getWrapPassword()); + } +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapRestProxyIntegrationTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapRestProxyIntegrationTest.java new file mode 100644 index 0000000000000..113b97b31b858 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapRestProxyIntegrationTest.java @@ -0,0 +1,66 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.Configuration; +import com.microsoft.windowsazure.core.UserAgentFilter; +import static org.junit.Assert.*; + +import java.net.URI; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.servicebus.ServiceBusConfiguration; +import com.sun.jersey.api.client.Client; + +public class WrapRestProxyIntegrationTest { + @Test + public void serviceCanBeCalledToCreateAccessToken() throws Exception { + // Arrange + Configuration config = Configuration.getInstance(); + overrideWithEnv(config, ServiceBusConfiguration.URI); + overrideWithEnv(config, ServiceBusConfiguration.WRAP_URI); + overrideWithEnv(config, ServiceBusConfiguration.WRAP_NAME); + overrideWithEnv(config, ServiceBusConfiguration.WRAP_PASSWORD); + WrapContract contract = new WrapRestProxy(config.create(Client.class), + new UserAgentFilter()); + + // Act + String serviceBusUri = (String) config + .getProperty(ServiceBusConfiguration.URI); + String uri = (String) config + .getProperty(ServiceBusConfiguration.WRAP_URI); + String name = (String) config + .getProperty(ServiceBusConfiguration.WRAP_NAME); + String password = (String) config + .getProperty(ServiceBusConfiguration.WRAP_PASSWORD); + String scope = new URI("http", new URI(serviceBusUri).getAuthority(), + new URI(serviceBusUri).getPath(), null, null).toString(); + WrapAccessTokenResult result = contract.wrapAccessToken(uri, name, + password, scope); + + // Assert + assertNotNull(result); + assertNotNull(result.getAccessToken()); + } + + private static void overrideWithEnv(Configuration config, String key) { + String value = System.getenv(key); + if (value == null) + return; + + config.setProperty(key, value); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManagerIntegrationTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManagerIntegrationTest.java similarity index 83% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManagerIntegrationTest.java rename to serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManagerIntegrationTest.java index d6ca3faf8e7b8..d8efdba155b62 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/implementation/WrapTokenManagerIntegrationTest.java +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManagerIntegrationTest.java @@ -12,16 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.implementation; +package com.microsoft.windowsazure.services.servicebus.implementation; +import com.microsoft.windowsazure.Configuration; import java.net.URI; import junit.framework.Assert; import org.junit.Test; -import com.microsoft.windowsazure.services.core.Configuration; -import com.microsoft.windowsazure.services.serviceBus.ServiceBusConfiguration; +import com.microsoft.windowsazure.services.servicebus.ServiceBusConfiguration; public class WrapTokenManagerIntegrationTest { @Test @@ -30,7 +30,8 @@ public void wrapClientWillAcquireAccessToken() throws Exception { Configuration config = Configuration.load(); overrideWithEnv(config, ServiceBusConfiguration.CONNECTION_STRING); WrapTokenManager client = config.create(WrapTokenManager.class); - ServiceBusConnectionSettings settings = config.create(ServiceBusConnectionSettings.class); + ServiceBusConnectionSettings settings = config + .create(ServiceBusConnectionSettings.class); // Act URI serviceBusURI = new URI(settings.getUri()); String accessToken = client.getAccessToken(serviceBusURI); diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManagerTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManagerTest.java new file mode 100644 index 0000000000000..65be1e34dfe89 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/implementation/WrapTokenManagerTest.java @@ -0,0 +1,178 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.implementation; + +import com.microsoft.windowsazure.core.utils.DateFactory; +import com.microsoft.windowsazure.exception.ServiceException; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +public class WrapTokenManagerTest { + private WrapContract contract; + private WrapTokenManager client; + private DateFactory dateFactory; + private Calendar calendar; + + @Before + public void init() throws Exception { + calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + + dateFactory = mock(DateFactory.class); + contract = mock(WrapContract.class); + ServiceBusConnectionSettings settings = new ServiceBusConnectionSettings( + null, null, "testurl", "testname", "testpassword"); + client = new WrapTokenManager(contract, dateFactory, settings); + + when(dateFactory.getDate()).thenAnswer(new Answer<Date>() { + @Override + public Date answer(InvocationOnMock invocation) throws Throwable { + return calendar.getTime(); + } + }); + } + + private void doIncrementingTokens() throws ServiceException { + doAnswer(new Answer<WrapAccessTokenResult>() { + int count = 0; + + @Override + public WrapAccessTokenResult answer(InvocationOnMock invocation) + throws Throwable { + ++count; + WrapAccessTokenResult wrapResponse = new WrapAccessTokenResult(); + wrapResponse.setAccessToken("testaccesstoken1-" + count); + wrapResponse.setExpiresIn(83); + return wrapResponse; + } + }).when(contract).wrapAccessToken("testurl", "testname", + "testpassword", "http://test/scope"); + + doAnswer(new Answer<WrapAccessTokenResult>() { + int count = 0; + + @Override + public WrapAccessTokenResult answer(InvocationOnMock invocation) + throws Throwable { + ++count; + WrapAccessTokenResult wrapResponse = new WrapAccessTokenResult(); + wrapResponse.setAccessToken("testaccesstoken2-" + count); + wrapResponse.setExpiresIn(83); + return wrapResponse; + } + }).when(contract).wrapAccessToken("testurl", "testname", + "testpassword", "http://test/scope2"); + } + + @Test + public void clientUsesContractToGetToken() throws ServiceException, + URISyntaxException { + // Arrange + doIncrementingTokens(); + + // Act + String accessToken = client + .getAccessToken(new URI("https://test/scope")); + + // Assert + assertNotNull(accessToken); + assertEquals("testaccesstoken1-1", accessToken); + } + + @Test + public void clientWillNotCallMultipleTimesWhileAccessTokenIsValid() + throws ServiceException, URISyntaxException { + // Arrange + doIncrementingTokens(); + + // Act + String accessToken1 = client.getAccessToken(new URI( + "https://test/scope?arg=1")); + String accessToken2 = client.getAccessToken(new URI( + "https://test/scope?arg=2")); + calendar.add(Calendar.SECOND, 40); + String accessToken3 = client.getAccessToken(new URI( + "https://test/scope?arg=3")); + + // Assert + assertEquals("testaccesstoken1-1", accessToken1); + assertEquals("testaccesstoken1-1", accessToken2); + assertEquals("testaccesstoken1-1", accessToken3); + + verify(contract, times(1)).wrapAccessToken("testurl", "testname", + "testpassword", "http://test/scope"); + } + + @Test + public void callsToDifferentPathsWillResultInDifferentAccessTokens() + throws ServiceException, URISyntaxException { + // Arrange + doIncrementingTokens(); + + // Act + String accessToken1 = client.getAccessToken(new URI( + "https://test/scope?arg=1")); + String accessToken2 = client.getAccessToken(new URI( + "https://test/scope2?arg=2")); + calendar.add(Calendar.SECOND, 40); + String accessToken3 = client.getAccessToken(new URI( + "https://test/scope?arg=3")); + + // Assert + assertEquals("testaccesstoken1-1", accessToken1); + assertEquals("testaccesstoken2-1", accessToken2); + assertEquals("testaccesstoken1-1", accessToken3); + + verify(contract, times(1)).wrapAccessToken("testurl", "testname", + "testpassword", "http://test/scope"); + verify(contract, times(1)).wrapAccessToken("testurl", "testname", + "testpassword", "http://test/scope2"); + } + + @Test + public void clientWillBeCalledWhenTokenIsHalfwayToExpiring() + throws ServiceException, URISyntaxException { + // Arrange + doIncrementingTokens(); + + // Act + String accessToken1 = client.getAccessToken(new URI( + "https://test/scope")); + String accessToken2 = client.getAccessToken(new URI( + "https://test/scope")); + calendar.add(Calendar.SECOND, 45); + String accessToken3 = client.getAccessToken(new URI( + "https://test/scope")); + + // Assert + assertEquals("testaccesstoken1-1", accessToken1); + assertEquals("testaccesstoken1-1", accessToken2); + assertEquals("testaccesstoken1-2", accessToken3); + + verify(contract, times(2)).wrapAccessToken("testurl", "testname", + "testpassword", "http://test/scope"); + } + +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/QueueInfoTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/QueueInfoTest.java new file mode 100644 index 0000000000000..06aed2f6cbb28 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/QueueInfoTest.java @@ -0,0 +1,356 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.models; + +import static org.junit.Assert.*; + +import java.util.Calendar; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.servicebus.implementation.EntityAvailabilityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.PartitioningPolicy; + +public class QueueInfoTest { + + private Duration createDuration(int milliSeconds) { + DatatypeFactory datatypeFactory; + try { + datatypeFactory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + throw new RuntimeException(e); + } + return datatypeFactory.newDuration(milliSeconds); + } + + @Test + public void testGetSetLockDuration() { + // Arrange + Duration expectedLockDuration = createDuration(100); + QueueInfo queueInfo = new QueueInfo(); + + // Act + Duration actualLockDuration = queueInfo.setLockDuration( + expectedLockDuration).getLockDuration(); + + // Assert + assertEquals(expectedLockDuration, actualLockDuration); + + } + + @Test + public void testGetSetMaxSizeInMegabytes() { + // Arrange + Long expectedMaxSizeInMegabytes = 1024L; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Long actualMaxSizeInMegabytes = queueInfo.setMaxSizeInMegabytes( + expectedMaxSizeInMegabytes).getMaxSizeInMegabytes(); + + // Assert + assertEquals(expectedMaxSizeInMegabytes, actualMaxSizeInMegabytes); + + } + + @Test + public void testGetSetRequiresDuplicateDetection() { + // Arrange + Boolean expectedRequiresDuplicateDetection = true; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Boolean actualRequiresDuplicateDetection = queueInfo + .setRequiresDuplicateDetection( + expectedRequiresDuplicateDetection) + .isRequiresDuplicateDetection(); + + // Assert + assertEquals(expectedRequiresDuplicateDetection, + actualRequiresDuplicateDetection); + + } + + @Test + public void testGetSetRequiresSession() { + // Arrange + Boolean expectedRequiresSession = true; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Boolean actualRequiresSession = queueInfo.setRequiresSession( + expectedRequiresSession).isRequiresSession(); + + // Assert + assertEquals(expectedRequiresSession, actualRequiresSession); + } + + @Test + public void testGetSetDefaultMessageTimeToLive() { + // Arrange + Duration expectedDefaultMessageTimeToLive = createDuration(100); + QueueInfo queueInfo = new QueueInfo(); + + // Act + Duration actualDefaultMessageTimeToLive = queueInfo + .setDefaultMessageTimeToLive(expectedDefaultMessageTimeToLive) + .getDefaultMessageTimeToLive(); + + // Assert + assertEquals(expectedDefaultMessageTimeToLive, + actualDefaultMessageTimeToLive); + } + + @Test + public void testGetSetDeadLetteringOnMessageExpiration() { + // Arrange + Boolean expectedDeadLetteringOnMessageExpiration = true; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Boolean actualDeadLetteringOnMessageExpiration = queueInfo + .setDeadLetteringOnMessageExpiration( + expectedDeadLetteringOnMessageExpiration) + .isDeadLetteringOnMessageExpiration(); + + // Assert + assertEquals(expectedDeadLetteringOnMessageExpiration, + actualDeadLetteringOnMessageExpiration); + } + + @Test + public void testGetSetDuplicateDetectionHistoryTimeWindow() { + // Arrange + Duration expectedDefaultMessageTimeToLive = createDuration(100); + QueueInfo queueInfo = new QueueInfo(); + + // Act + Duration actualDefaultMessageTimeToLive = queueInfo + .setDefaultMessageTimeToLive(expectedDefaultMessageTimeToLive) + .getDefaultMessageTimeToLive(); + + // Assert + assertEquals(expectedDefaultMessageTimeToLive, + actualDefaultMessageTimeToLive); + } + + @Test + public void testGetSetMaxDeliveryCount() { + // Arrange + Integer expectedMaxDeliveryCount = 1024; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Integer actualMaxDeliveryCount = queueInfo.setMaxDeliveryCount( + expectedMaxDeliveryCount).getMaxDeliveryCount(); + + // Assert + assertEquals(expectedMaxDeliveryCount, actualMaxDeliveryCount); + } + + @Test + public void testGetSetEnableBatchedOperations() { + // Arrange + Boolean expectedEnableBatchedOperations = true; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Boolean actualEnableBatchedOperations = queueInfo + .setEnableBatchedOperations(expectedEnableBatchedOperations) + .isEnableBatchedOperations(); + + // Assert + assertEquals(expectedEnableBatchedOperations, + actualEnableBatchedOperations); + } + + @Test + public void testGetSetSizeInBytes() { + // Arrange + Long expectedSizeInBytes = 1024L; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Long actualSizeInBytes = queueInfo.setSizeInBytes(expectedSizeInBytes) + .getSizeInBytes(); + + // Assert + assertEquals(expectedSizeInBytes, actualSizeInBytes); + } + + @Test + public void testGetSetMessageCount() { + // Arrange + Long expectedMessageCount = 1024L; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Long actualMessageCount = queueInfo.setMessageCount( + expectedMessageCount).getMessageCount(); + + // Assert + assertEquals(expectedMessageCount, actualMessageCount); + } + + @Test + public void testGetSetIsAnonymousAccessible() { + // Arrange + Boolean expectedIsAnonymousAccessible = true; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Boolean actualIsAnonymousAccessible = queueInfo + .setIsAnonymousAccessible(expectedIsAnonymousAccessible) + .isAnonymousAccessible(); + + // Assert + assertEquals(expectedIsAnonymousAccessible, actualIsAnonymousAccessible); + } + + @Test + public void testGetSetStatus() { + // Arrange + EntityStatus expectedEntityStatus = EntityStatus.ACTIVE; + QueueInfo queueInfo = new QueueInfo(); + + // Act + EntityStatus actualEntityStatus = queueInfo.setStatus( + expectedEntityStatus).getStatus(); + + // Assert + assertEquals(expectedEntityStatus, actualEntityStatus); + } + + @Test + public void testGetSetCreatedAt() { + // Arrange + Calendar expectedCreatedAt = Calendar.getInstance(); + QueueInfo queueInfo = new QueueInfo(); + + // Act + Calendar actualCreatedAt = queueInfo.setCreatedAt(expectedCreatedAt) + .getCreatedAt(); + + // Assert + assertEquals(expectedCreatedAt, actualCreatedAt); + } + + @Test + public void testGetSetUpdatedAt() { + // Arrange + Calendar expectedUpdatedAt = Calendar.getInstance(); + QueueInfo queueInfo = new QueueInfo(); + + // Act + Calendar actualUpdatedAt = queueInfo.setUpdatedAt(expectedUpdatedAt) + .getUpdatedAt(); + + // Assert + assertEquals(expectedUpdatedAt, actualUpdatedAt); + } + + @Test + public void testGetSetAccessedAt() { + // Arrange + Calendar expectedAccessedAt = Calendar.getInstance(); + QueueInfo queueInfo = new QueueInfo(); + + // Act + Calendar actualAccessedAt = queueInfo.setAccessedAt(expectedAccessedAt) + .getAccessedAt(); + + // Assert + assertEquals(expectedAccessedAt, actualAccessedAt); + } + + @Test + public void testGetSetUserMetadata() { + // Arrange + String expectedUserMetadata = "expectedUserMetaData"; + QueueInfo queueInfo = new QueueInfo(); + + // Act + String actualUserMetadata = queueInfo.setUserMetadata( + expectedUserMetadata).getUserMetadata(); + + // Assert + assertEquals(expectedUserMetadata, actualUserMetadata); + } + + @Test + public void testGetSetSupportOrdering() { + // Arrange + Boolean expectedIsSupportOrdering = true; + QueueInfo queueInfo = new QueueInfo(); + + // Act + Boolean actualIsSupportOrdering = queueInfo.setSupportOrdering( + expectedIsSupportOrdering).isSupportOrdering(); + + // Assert + assertEquals(expectedIsSupportOrdering, actualIsSupportOrdering); + } + + @Test + public void testGetSetAutoDeleteOnIdle() { + // Arrange + Duration expectedIsAutoDeleteOnIdle = createDuration(100); + QueueInfo queueInfo = new QueueInfo(); + + // Act + Duration actualIsAutoDeleteOnIdle = queueInfo.setAutoDeleteOnIdle( + expectedIsAutoDeleteOnIdle).getAutoDeleteOnIdle(); + + // Assert + assertEquals(expectedIsAutoDeleteOnIdle, actualIsAutoDeleteOnIdle); + } + + @Test + public void testGetSetPartioningPolicy() { + // Arrange + PartitioningPolicy expectedPartitioningPolicy = PartitioningPolicy.NO_PARTITIONING; + QueueInfo queueInfo = new QueueInfo(); + + // Act + PartitioningPolicy actualPartitioningPolicy = queueInfo + .setPartitioningPolicy(expectedPartitioningPolicy) + .getPartitioningPolicy(); + + // Assert + assertEquals(expectedPartitioningPolicy, actualPartitioningPolicy); + } + + @Test + public void testGetSetEntityAvailabilityStatus() { + // Arrange + EntityAvailabilityStatus expectedEntityAvailabilityStatus = EntityAvailabilityStatus.AVAILABLE; + QueueInfo queueInfo = new QueueInfo(); + + // Act + EntityAvailabilityStatus actualEntityAvailabilityStatus = queueInfo + .setEntityAvailabilityStatus(expectedEntityAvailabilityStatus) + .getEntityAvailabilityStatus(); + + // Assert + assertEquals(expectedEntityAvailabilityStatus, + actualEntityAvailabilityStatus); + } + +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/RuleInfoTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/RuleInfoTest.java similarity index 86% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/RuleInfoTest.java rename to serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/RuleInfoTest.java index 1e05583021658..da944b7384ab1 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/services/serviceBus/models/RuleInfoTest.java +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/RuleInfoTest.java @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.microsoft.windowsazure.services.serviceBus.models; +package com.microsoft.windowsazure.services.servicebus.models; import static org.junit.Assert.*; @@ -20,8 +20,8 @@ import org.junit.Test; -import com.microsoft.windowsazure.services.serviceBus.implementation.Filter; -import com.microsoft.windowsazure.services.serviceBus.implementation.RuleAction; +import com.microsoft.windowsazure.services.servicebus.implementation.Filter; +import com.microsoft.windowsazure.services.servicebus.implementation.RuleAction; public class RuleInfoTest { @@ -31,7 +31,7 @@ public void testGetSetFilter() { Filter expectedFilter = new Filter(); RuleInfo RuleInfo = new RuleInfo(); - // Act + // Act Filter actualFilter = RuleInfo.setFilter(expectedFilter).getFilter(); // Assert @@ -45,8 +45,9 @@ public void testGetSetAction() { RuleAction expectedAction = new RuleAction(); RuleInfo RuleInfo = new RuleInfo(); - // Act - RuleAction actualAction = RuleInfo.setAction(expectedAction).getAction(); + // Act + RuleAction actualAction = RuleInfo.setAction(expectedAction) + .getAction(); // Assert assertEquals(expectedAction, actualAction); @@ -58,7 +59,7 @@ public void testGetSetTag() { String expectedTag = "expectedTag"; RuleInfo RuleInfo = new RuleInfo(); - // Act + // Act String actualTag = RuleInfo.setTag(expectedTag).getTag(); // Assert @@ -71,7 +72,7 @@ public void testGetSetName() { String expectedName = "expectedName"; RuleInfo RuleInfo = new RuleInfo(); - // Act + // Act String actualName = RuleInfo.setName(expectedName).getName(); // Assert @@ -84,8 +85,9 @@ public void testGetSetCreatedAt() { Calendar expectedCreatedAt = Calendar.getInstance(); RuleInfo RuleInfo = new RuleInfo(); - // Act - Calendar actualCreatedAt = RuleInfo.setCreatedAt(expectedCreatedAt).getCreatedAt(); + // Act + Calendar actualCreatedAt = RuleInfo.setCreatedAt(expectedCreatedAt) + .getCreatedAt(); // Assert assertEquals(expectedCreatedAt, actualCreatedAt); diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/SubscriptionInfoTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/SubscriptionInfoTest.java new file mode 100644 index 0000000000000..718fdd6c806d8 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/SubscriptionInfoTest.java @@ -0,0 +1,283 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.models; + +import static org.junit.Assert.*; + +import java.util.Calendar; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.servicebus.implementation.EntityAvailabilityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.RuleDescription; + +public class SubscriptionInfoTest { + + private Duration createDuration(int milliSeconds) { + DatatypeFactory datatypeFactory; + try { + datatypeFactory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + throw new RuntimeException(e); + } + return datatypeFactory.newDuration(milliSeconds); + } + + @Test + public void testGetSetLockDuration() { + // Arrange + Duration expectedLockDuration = createDuration(100); + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Duration actualLockDuration = SubscriptionInfo.setLockDuration( + expectedLockDuration).getLockDuration(); + + // Assert + assertEquals(expectedLockDuration, actualLockDuration); + + } + + @Test + public void testGetSetRequiresSession() { + // Arrange + Boolean expectedRequiresSession = true; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Boolean actualRequiresSession = SubscriptionInfo.setRequiresSession( + expectedRequiresSession).isRequiresSession(); + + // Assert + assertEquals(expectedRequiresSession, actualRequiresSession); + } + + @Test + public void testGetSetDefaultMessageTimeToLive() { + // Arrange + Duration expectedDefaultMessageTimeToLive = createDuration(100); + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Duration actualDefaultMessageTimeToLive = SubscriptionInfo + .setDefaultMessageTimeToLive(expectedDefaultMessageTimeToLive) + .getDefaultMessageTimeToLive(); + + // Assert + assertEquals(expectedDefaultMessageTimeToLive, + actualDefaultMessageTimeToLive); + } + + @Test + public void testGetSetDeadLetteringOnMessageExpiration() { + // Arrange + Boolean expectedDeadLetteringOnMessageExpiration = true; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Boolean actualDeadLetteringOnMessageExpiration = SubscriptionInfo + .setDeadLetteringOnMessageExpiration( + expectedDeadLetteringOnMessageExpiration) + .isDeadLetteringOnMessageExpiration(); + + // Assert + assertEquals(expectedDeadLetteringOnMessageExpiration, + actualDeadLetteringOnMessageExpiration); + } + + @Test + public void testGetSetDeadLetteringOnFilterEvaluationExceptions() { + // Arrange + Boolean expectedDeadLetteringOnFilterEvaluationExceptions = true; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Boolean actualDeadLetteringOnFilterEvaluationExceptions = SubscriptionInfo + .setDeadLetteringOnFilterEvaluationExceptions( + expectedDeadLetteringOnFilterEvaluationExceptions) + .isDeadLetteringOnFilterEvaluationExceptions(); + + // Assert + assertEquals(expectedDeadLetteringOnFilterEvaluationExceptions, + actualDeadLetteringOnFilterEvaluationExceptions); + } + + @Test + public void testGetSetDefaultRuleDescription() { + // Arrange + RuleDescription expectedDefaultRuleDescription = new RuleDescription(); + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + RuleDescription actualDefaultRuleDescription = SubscriptionInfo + .setDefaultRuleDescription(expectedDefaultRuleDescription) + .getDefaultRuleDescription(); + + // Assert + assertEquals(expectedDefaultRuleDescription, + actualDefaultRuleDescription); + } + + @Test + public void testGetSetMessageCount() { + // Arrange + Long expectedMessageCount = 1024L; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Long actualMessageCount = SubscriptionInfo.setMessageCount( + expectedMessageCount).getMessageCount(); + + // Assert + assertEquals(expectedMessageCount, actualMessageCount); + } + + @Test + public void testGetSetMaxDeliveryCount() { + // Arrange + Integer expectedMaxDeliveryCount = 1024; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Integer actualMaxDeliveryCount = SubscriptionInfo.setMaxDeliveryCount( + expectedMaxDeliveryCount).getMaxDeliveryCount(); + + // Assert + assertEquals(expectedMaxDeliveryCount, actualMaxDeliveryCount); + } + + @Test + public void testGetSetEnableBatchedOperations() { + // Arrange + Boolean expectedEnableBatchedOperations = true; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Boolean actualEnableBatchedOperations = SubscriptionInfo + .setEnableBatchedOperations(expectedEnableBatchedOperations) + .isEnableBatchedOperations(); + + // Assert + assertEquals(expectedEnableBatchedOperations, + actualEnableBatchedOperations); + } + + @Test + public void testGetSetStatus() { + // Arrange + EntityStatus expectedEntityStatus = EntityStatus.ACTIVE; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + EntityStatus actualEntityStatus = SubscriptionInfo.setStatus( + expectedEntityStatus).getStatus(); + + // Assert + assertEquals(expectedEntityStatus, actualEntityStatus); + } + + @Test + public void testGetSetCreatedAt() { + // Arrange + Calendar expectedCreatedAt = Calendar.getInstance(); + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Calendar actualCreatedAt = SubscriptionInfo.setCreatedAt( + expectedCreatedAt).getCreatedAt(); + + // Assert + assertEquals(expectedCreatedAt, actualCreatedAt); + } + + @Test + public void testGetSetUpdatedAt() { + // Arrange + Calendar expectedUpdatedAt = Calendar.getInstance(); + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Calendar actualUpdatedAt = SubscriptionInfo.setUpdatedAt( + expectedUpdatedAt).getUpdatedAt(); + + // Assert + assertEquals(expectedUpdatedAt, actualUpdatedAt); + } + + @Test + public void testGetSetAccessedAt() { + // Arrange + Calendar expectedAccessedAt = Calendar.getInstance(); + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Calendar actualAccessedAt = SubscriptionInfo.setAccessedAt( + expectedAccessedAt).getAccessedAt(); + + // Assert + assertEquals(expectedAccessedAt, actualAccessedAt); + } + + @Test + public void testGetSetUserMetadata() { + // Arrange + String expectedUserMetadata = "expectedUserMetaData"; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + String actualUserMetadata = SubscriptionInfo.setUserMetadata( + expectedUserMetadata).getUserMetadata(); + + // Assert + assertEquals(expectedUserMetadata, actualUserMetadata); + } + + @Test + public void testGetSetAutoDeleteOnIdle() { + // Arrange + Duration expectedIsAutoDeleteOnIdle = createDuration(100); + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + Duration actualIsAutoDeleteOnIdle = SubscriptionInfo + .setAutoDeleteOnIdle(expectedIsAutoDeleteOnIdle) + .getAutoDeleteOnIdle(); + + // Assert + assertEquals(expectedIsAutoDeleteOnIdle, actualIsAutoDeleteOnIdle); + } + + @Test + public void testGetSetEntityAvailabilityStatus() { + // Arrange + EntityAvailabilityStatus expectedEntityAvailabilityStatus = EntityAvailabilityStatus.AVAILABLE; + SubscriptionInfo SubscriptionInfo = new SubscriptionInfo(); + + // Act + EntityAvailabilityStatus actualEntityAvailabilityStatus = SubscriptionInfo + .setEntityAvailabilityStatus(expectedEntityAvailabilityStatus) + .getEntityAvailabilityStatus(); + + // Assert + assertEquals(expectedEntityAvailabilityStatus, + actualEntityAvailabilityStatus); + } + +} diff --git a/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/TopicInfoTest.java b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/TopicInfoTest.java new file mode 100644 index 0000000000000..376977ae185d5 --- /dev/null +++ b/serviceBus/src/test/java/com/microsoft/windowsazure/services/servicebus/models/TopicInfoTest.java @@ -0,0 +1,313 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.services.servicebus.models; + +import static org.junit.Assert.*; + +import java.util.Calendar; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; + +import org.junit.Test; + +import com.microsoft.windowsazure.services.servicebus.implementation.EntityAvailabilityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.EntityStatus; +import com.microsoft.windowsazure.services.servicebus.implementation.PartitioningPolicy; + +public class TopicInfoTest { + + private Duration createDuration(int milliSeconds) { + DatatypeFactory datatypeFactory; + try { + datatypeFactory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + throw new RuntimeException(e); + } + return datatypeFactory.newDuration(milliSeconds); + } + + @Test + public void testGetSetDefaultMessageTimeToLive() { + // Arrange + Duration expectedDefaultMessageTimeToLive = createDuration(1024); + TopicInfo topicInfo = new TopicInfo(); + + // Act + Duration actualDefaultMessageTimeToLive = topicInfo + .setDefaultMessageTimeToLive(expectedDefaultMessageTimeToLive) + .getDefaultMessageTimeToLive(); + + // Assert + assertEquals(expectedDefaultMessageTimeToLive, + actualDefaultMessageTimeToLive); + + } + + @Test + public void testGetSetMaxSizeInMegabytes() { + // Arrange + Long expectedMaxSizeInMegabytes = 1024L; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Long actualMaxSizeInMegabytes = topicInfo.setMaxSizeInMegabytes( + expectedMaxSizeInMegabytes).getMaxSizeInMegabytes(); + + // Assert + assertEquals(expectedMaxSizeInMegabytes, actualMaxSizeInMegabytes); + + } + + @Test + public void testGetSetRequiresDuplicateDetection() { + // Arrange + Boolean expectedRequiresDuplicateDetection = true; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Boolean actualRequiresDuplicateDetection = topicInfo + .setRequiresDuplicateDetection( + expectedRequiresDuplicateDetection) + .isRequiresDuplicateDetection(); + + // Assert + assertEquals(expectedRequiresDuplicateDetection, + actualRequiresDuplicateDetection); + + } + + @Test + public void testGetSetDuplicateDetectionHistoryTimeWindow() { + // Arrange + Duration expectedDefaultMessageTimeToLive = createDuration(100); + TopicInfo topicInfo = new TopicInfo(); + + // Act + Duration actualDefaultMessageTimeToLive = topicInfo + .setDefaultMessageTimeToLive(expectedDefaultMessageTimeToLive) + .getDefaultMessageTimeToLive(); + + // Assert + assertEquals(expectedDefaultMessageTimeToLive, + actualDefaultMessageTimeToLive); + } + + @Test + public void testGetSetEnableBatchedOperations() { + // Arrange + Boolean expectedEnableBatchedOperations = true; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Boolean actualEnableBatchedOperations = topicInfo + .setEnableBatchedOperations(expectedEnableBatchedOperations) + .isEnableBatchedOperations(); + + // Assert + assertEquals(expectedEnableBatchedOperations, + actualEnableBatchedOperations); + } + + @Test + public void testGetSetSizeInBytes() { + // Arrange + Long expectedSizeInBytes = 1024L; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Long actualSizeInBytes = topicInfo.setSizeInBytes(expectedSizeInBytes) + .getSizeInBytes(); + + // Assert + assertEquals(expectedSizeInBytes, actualSizeInBytes); + } + + @Test + public void testGetSetFilteringMessageBeforePublishing() { + // Arrange + Boolean expectedFilteringMessageBeforePublishing = true; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Boolean actualFilteringMessageBeforePublishing = topicInfo + .setFilteringMessageBeforePublishing( + expectedFilteringMessageBeforePublishing) + .isFilteringMessageBeforePublishing(); + + // Assert + assertEquals(expectedFilteringMessageBeforePublishing, + actualFilteringMessageBeforePublishing); + } + + @Test + public void testGetSetAnonymousAccessible() { + // Arrange + Boolean expectedAnonymousAccessible = true; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Boolean actualAnonymousAccessible = topicInfo.setAnonymousAccessible( + expectedAnonymousAccessible).isAnonymousAccessible(); + + // Assert + assertEquals(expectedAnonymousAccessible, actualAnonymousAccessible); + } + + @Test + public void testGetSetStatus() { + // Arrange + EntityStatus expectedEntityStatus = EntityStatus.ACTIVE; + TopicInfo topicInfo = new TopicInfo(); + + // Act + EntityStatus actualEntityStatus = topicInfo.setStatus( + expectedEntityStatus).getStatus(); + + // Assert + assertEquals(expectedEntityStatus, actualEntityStatus); + } + + @Test + public void testGetSetCreatedAt() { + // Arrange + Calendar expectedCreatedAt = Calendar.getInstance(); + TopicInfo topicInfo = new TopicInfo(); + + // Act + Calendar actualCreatedAt = topicInfo.setCreatedAt(expectedCreatedAt) + .getCreatedAt(); + + // Assert + assertEquals(expectedCreatedAt, actualCreatedAt); + } + + @Test + public void testGetSetUpdatedAt() { + // Arrange + Calendar expectedUpdatedAt = Calendar.getInstance(); + TopicInfo topicInfo = new TopicInfo(); + + // Act + Calendar actualUpdatedAt = topicInfo.setUpdatedAt(expectedUpdatedAt) + .getUpdatedAt(); + + // Assert + assertEquals(expectedUpdatedAt, actualUpdatedAt); + } + + @Test + public void testGetSetAccessedAt() { + // Arrange + Calendar expectedAccessedAt = Calendar.getInstance(); + TopicInfo topicInfo = new TopicInfo(); + + // Act + Calendar actualAccessedAt = topicInfo.setAccessedAt(expectedAccessedAt) + .getAccessedAt(); + + // Assert + assertEquals(expectedAccessedAt, actualAccessedAt); + } + + @Test + public void testGetSetUserMetadata() { + // Arrange + String expectedUserMetadata = "expectedUserMetaData"; + TopicInfo topicInfo = new TopicInfo(); + + // Act + String actualUserMetadata = topicInfo.setUserMetadata( + expectedUserMetadata).getUserMetadata(); + + // Assert + assertEquals(expectedUserMetadata, actualUserMetadata); + } + + @Test + public void testGetSetSupportOrdering() { + // Arrange + Boolean expectedIsSupportOrdering = true; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Boolean actualIsSupportOrdering = topicInfo.setSupportOrdering( + expectedIsSupportOrdering).isSupportOrdering(); + + // Assert + assertEquals(expectedIsSupportOrdering, actualIsSupportOrdering); + } + + @Test + public void testGetSetSubscriptionCount() { + // Arrange + Integer expectedSubscriptionCount = 1024; + TopicInfo topicInfo = new TopicInfo(); + + // Act + Integer actualSubscriptionCount = topicInfo.setSubscriptionCount( + expectedSubscriptionCount).getSubscriptionCount(); + + // Assert + assertEquals(expectedSubscriptionCount, actualSubscriptionCount); + } + + @Test + public void testGetSetAutoDeleteOnIdle() { + // Arrange + Duration expectedIsAutoDeleteOnIdle = createDuration(100); + TopicInfo topicInfo = new TopicInfo(); + + // Act + Duration actualIsAutoDeleteOnIdle = topicInfo.setAutoDeleteOnIdle( + expectedIsAutoDeleteOnIdle).getAutoDeleteOnIdle(); + + // Assert + assertEquals(expectedIsAutoDeleteOnIdle, actualIsAutoDeleteOnIdle); + } + + @Test + public void testGetSetPartioningPolicy() { + // Arrange + PartitioningPolicy expectedPartitioningPolicy = PartitioningPolicy.NO_PARTITIONING; + TopicInfo topicInfo = new TopicInfo(); + + // Act + PartitioningPolicy actualPartitioningPolicy = topicInfo + .setPartitioningPolicy(expectedPartitioningPolicy) + .getPartitioningPolicy(); + + // Assert + assertEquals(expectedPartitioningPolicy, actualPartitioningPolicy); + } + + @Test + public void testGetSetEntityAvailabilityStatus() { + // Arrange + EntityAvailabilityStatus expectedEntityAvailabilityStatus = EntityAvailabilityStatus.AVAILABLE; + TopicInfo topicInfo = new TopicInfo(); + + // Act + EntityAvailabilityStatus actualEntityAvailabilityStatus = topicInfo + .setEntityAvailabilityStatus(expectedEntityAvailabilityStatus) + .getEntityAvailabilityStatus(); + + // Assert + assertEquals(expectedEntityAvailabilityStatus, + actualEntityAvailabilityStatus); + } + +} diff --git a/serviceBus/src/test/resources/META-INF/com.microsoft.windowsazure.properties b/serviceBus/src/test/resources/META-INF/com.microsoft.windowsazure.properties new file mode 100644 index 0000000000000..eb2c358c922c9 --- /dev/null +++ b/serviceBus/src/test/resources/META-INF/com.microsoft.windowsazure.properties @@ -0,0 +1,27 @@ +serviceBus.uri=https://%SERVICEBUS_NAMESPACE%.servicebus.windows.net/ +serviceBus.wrap.uri=https://%SERVICEBUS_NAMESPACE%-sb.accesscontrol.windows.net/WRAPv0.9 +serviceBus.wrap.name=%SERVICEBUS_SERVICEIDENTITY% +serviceBus.wrap.password=%SERVICEBUS_SHAREDSECRET% +serviceBus.connection.string=EndPoint=sb://%SERVICEBUS_NAMESPACE%.servicebus.windows.net/;SharedSecretIssuer=%SERVICEBUS_SERVICEIDENTITY%;SharedSecretValue=%SERVICEBUS_SHAREDSECRET% +blob.accountName=%BLOB_ACCOUNTNAME% +blob.accountKey=%BLOB_ACCOUNTKEY% +blob.uri=http://%BLOB_ACCOUNTNAME%.blob.core.windows.net +queue.accountName=%QUEUE_ACCOUNTNAME% +queue.accountKey=%QUEUE_ACCOUNTKEY% +queue.uri=http://%QUEUE_ACCOUNTNAME%.queue.core.windows.net +table.accountName=%TABLE_ACCOUNTNAME% +table.accountKey=%TABLE_ACCOUNTKEY% +table.uri=http://%TABLE_ACCOUNTNAME%.table.core.windows.net +media.uri=%MEDIA.URI% +media.oauth.uri=%MEDIA.OAUTH.URI% +media.oauth.client.id=%OMEDIA.AUTH.CLIENT.ID% +media.oauth.client.secret=%MEDIA.OAUTH.CLIENT.SECRET% +media.oauth.scope=urn:WindowsAzureMediaServices +management.keystore.path=%MANAGEMENT.KEYSTORE.PATH% +management.keystore.password=%MANAGEMENT.KEYSTORE.PASSWORD% +management.keystore.type=%MANAGEMENT.KEYSTORE.TYPE% +management.subscription.id=%MANAGEMENT.SUBSCRIPTION.ID% +management.uri=%MANAGEMENT.URI% +testprefix.com.microsoft.windowsazure.services.core.Configuration.connectTimeout=3 +testprefix.com.microsoft.windowsazure.services.core.Configuration.readTimeout=7 + diff --git a/serviceBus/src/test/resources/NewFile.xml b/serviceBus/src/test/resources/NewFile.xml new file mode 100644 index 0000000000000..5ebbe31bdafda --- /dev/null +++ b/serviceBus/src/test/resources/NewFile.xml @@ -0,0 +1,4 @@ +<entry xmlns="http://www.w3.org/2005/Atom"> +<content type="application/xml"> +<ns2:QueueDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"> +</ns2:QueueDescription></content></entry> diff --git a/serviceRuntime/pom.xml b/serviceRuntime/pom.xml new file mode 100644 index 0000000000000..4192fa569bc12 --- /dev/null +++ b/serviceRuntime/pom.xml @@ -0,0 +1,232 @@ +<!-- + Copyright Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.microsoft.windowsazure</groupId> + <artifactId>microsoft-azure-api-parent</artifactId> + <version>0.5.0</version> + <relativePath>../parent/pom.xml</relativePath> + </parent> + + <artifactId>microsoft-azure-api-serviceruntime</artifactId> + <packaging>jar</packaging> + + <name>Microsoft Azure Service Runtime Client API</name> + <description>Microsoft Azure Service Runtime SDK Clients</description> + <url>https://github.com/Azure/azure-sdk-for-java</url> + + <licenses> + <license> + <name>The Apache Software License, Version 2.0</name> + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> + <distribution>repo</distribution> + </license> + </licenses> + + <scm> + <url>scm:git:https://github.com/Azure/azure-sdk-for-java</url> + <connection>scm:git:git://github.com/Azure/azure-sdk-for-java.git</connection> + </scm> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <legal><![CDATA[[INFO] Any downloads listed may be third party software. Microsoft grants you no rights for third party software.]]></legal> + </properties> + + <developers> + <developer> + <id>microsoft</id> + <name>Microsoft</name> + </developer> + </developers> + + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>microsoft-azure-api-core</artifactId> + <version>0.5.0</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + </dependency> + <dependency> + <groupId>javax.inject</groupId> + <artifactId>javax.inject</artifactId> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-client</artifactId> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-json</artifactId> + </dependency> + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </dependency> + + <!-- Test dependencies --> + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-all</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcprov-jdk16</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-help-plugin</artifactId> + <version>2.1.1</version> + <executions> + <execution> + <phase>validate</phase> + <goals> + <goal>evaluate</goal> + </goals> + <configuration> + <expression>legal</expression> + </configuration> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <source>1.6</source> + <target>1.6</target> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.8</version> + <configuration> + <excludePackageNames>*.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage</excludePackageNames> + <bottom><![CDATA[<code>/** +<br/>* Copyright Microsoft Corporation +<br/>* +<br/>* Licensed under the Apache License, Version 2.0 (the "License"); +<br/>* you may not use this file except in compliance with the License. +<br/>* You may obtain a copy of the License at +<br/>* http://www.apache.org/licenses/LICENSE-2.0 +<br/>* +<br/>* Unless required by applicable law or agreed to in writing, software +<br/>* distributed under the License is distributed on an "AS IS" BASIS, +<br/>* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +<br/>* See the License for the specific language governing permissions and +<br/>* limitations under the License. +<br/>*/</code>]]></bottom> + </configuration> + </plugin> + </plugins> + <pluginManagement> + <plugins> + <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-help-plugin</artifactId> + <versionRange>[2.1.1,)</versionRange> + <goals> + <goal>evaluate</goal> + </goals> + </pluginExecutionFilter> + <action> + <ignore></ignore> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-resources-plugin</artifactId> + <version>2.4.3</version> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <version>2.12</version> + <configuration> + <includes> + <include>**/Test*.java</include> + <include>**/*Test.java</include> + <include>**/*Tests.java</include> + <include>**/*TestCase.java</include> + </includes> + </configuration> + </plugin> + </plugins> + </pluginManagement> + </build> + <reporting> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>emma-maven-plugin</artifactId> + <version>1.0-alpha-3</version> + <inherited>true</inherited> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>surefire-report-maven-plugin</artifactId> + <version>2.0-beta-1</version> + <inherited>true</inherited> + </plugin> + </plugins> + </reporting> +</project> diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireCurrentState.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireCurrentState.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireCurrentState.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireCurrentState.java index 075bafcad08b7..b82d2ea869f41 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireCurrentState.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireCurrentState.java @@ -25,7 +25,8 @@ class AcquireCurrentState extends CurrentState { private final CurrentStatus status; private final Calendar expiration; - public AcquireCurrentState(String clientId, BigInteger incarnation, CurrentStatus status, Calendar expiration) { + public AcquireCurrentState(String clientId, BigInteger incarnation, + CurrentStatus status, Calendar expiration) { super(clientId); this.incarnation = incarnation; this.status = status; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireLeaseInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireLeaseInfo.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireLeaseInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireLeaseInfo.java index 981433e5ccca8..68ebb113bcfc2 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireLeaseInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/AcquireLeaseInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.math.BigInteger; @@ -31,11 +30,13 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** - * <p>Java class for AcquireLeaseInfo complex type. + * <p> + * Java class for AcquireLeaseInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="AcquireLeaseInfo"> @@ -62,23 +63,21 @@ class AcquireLeaseInfo { @XmlElement(name = "Incarnation", required = true) @XmlSchemaType(name = "unsignedLong") - protected BigInteger incarnation; + private BigInteger incarnation; @XmlElement(name = "Status", required = true) - protected CurrentStatusEnum status; + private CurrentStatusEnum status; @XmlElement(name = "StatusDetail", required = true) - protected String statusDetail; + private String statusDetail; @XmlElement(name = "Expiration", required = true, type = String.class) - @XmlJavaTypeAdapter(Adapter1 .class) + @XmlJavaTypeAdapter(Adapter1.class) @XmlSchemaType(name = "dateTime") - protected Calendar expiration; + private Calendar expiration; /** * Gets the value of the incarnation property. * - * @return - * possible object is - * {@link BigInteger } - * + * @return possible object is {@link BigInteger } + * */ public BigInteger getIncarnation() { return incarnation; @@ -88,9 +87,8 @@ public BigInteger getIncarnation() { * Sets the value of the incarnation property. * * @param value - * allowed object is - * {@link BigInteger } - * + * allowed object is {@link BigInteger } + * */ public void setIncarnation(BigInteger value) { this.incarnation = value; @@ -99,10 +97,8 @@ public void setIncarnation(BigInteger value) { /** * Gets the value of the status property. * - * @return - * possible object is - * {@link CurrentStatusEnum } - * + * @return possible object is {@link CurrentStatusEnum } + * */ public CurrentStatusEnum getStatus() { return status; @@ -112,9 +108,8 @@ public CurrentStatusEnum getStatus() { * Sets the value of the status property. * * @param value - * allowed object is - * {@link CurrentStatusEnum } - * + * allowed object is {@link CurrentStatusEnum } + * */ public void setStatus(CurrentStatusEnum value) { this.status = value; @@ -123,10 +118,8 @@ public void setStatus(CurrentStatusEnum value) { /** * Gets the value of the statusDetail property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getStatusDetail() { return statusDetail; @@ -136,9 +129,8 @@ public String getStatusDetail() { * Sets the value of the statusDetail property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setStatusDetail(String value) { this.statusDetail = value; @@ -147,10 +139,8 @@ public void setStatusDetail(String value) { /** * Gets the value of the expiration property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public Calendar getExpiration() { return expiration; @@ -160,9 +150,8 @@ public Calendar getExpiration() { * Sets the value of the expiration property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setExpiration(Calendar value) { this.expiration = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Adapter1.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Adapter1.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Adapter1.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Adapter1.java index f6ffdd6ff61ff..81e005a76aa49 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Adapter1.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Adapter1.java @@ -19,16 +19,12 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.util.Calendar; import javax.xml.bind.annotation.adapters.XmlAdapter; -class Adapter1 - extends XmlAdapter<String, Calendar> -{ - +class Adapter1 extends XmlAdapter<String, Calendar> { public Calendar unmarshal(String value) { return (javax.xml.bind.DatatypeConverter.parseDateTime(value)); diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ChunkedGoalStateDeserializer.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ChunkedGoalStateDeserializer.java similarity index 86% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ChunkedGoalStateDeserializer.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ChunkedGoalStateDeserializer.java index 9d592a94327db..2cfac509eb20c 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ChunkedGoalStateDeserializer.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ChunkedGoalStateDeserializer.java @@ -31,9 +31,9 @@ public ChunkedGoalStateDeserializer() { @Override public void initialize(InputStream inputStream) { try { - reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); - } - catch (UnsupportedEncodingException e) { + reader = new BufferedReader(new InputStreamReader(inputStream, + "UTF-8")); + } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @@ -48,17 +48,17 @@ public GoalState deserialize() { } int length = Integer.parseInt(lengthString.toString(), 16); - char chunkData[] = new char[length]; + char[] chunkData = new char[length]; reader.read(chunkData, 0, length); - GoalState goalState = deserializer.deserialize(new String(chunkData)); + GoalState goalState = deserializer + .deserialize(new String(chunkData)); reader.readLine(); return goalState; - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); return null; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingInfo.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingInfo.java index 3dc242264b4c6..1f28b1b32e392 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for ConfigurationSettingInfo complex type. + * <p> + * Java class for ConfigurationSettingInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="ConfigurationSettingInfo"> @@ -51,17 +52,15 @@ class ConfigurationSettingInfo { @XmlAttribute(required = true) - protected String name; + private String name; @XmlAttribute(required = true) - protected String value; + private String value; /** * Gets the value of the name property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getName() { return name; @@ -71,9 +70,8 @@ public String getName() { * Sets the value of the name property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setName(String value) { this.name = value; @@ -82,10 +80,8 @@ public void setName(String value) { /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getValue() { return value; @@ -95,9 +91,8 @@ public String getValue() { * Sets the value of the value property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setValue(String value) { this.value = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingsInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingsInfo.java similarity index 80% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingsInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingsInfo.java index c649e156bc8d5..caf60530d99b7 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingsInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ConfigurationSettingsInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.util.ArrayList; @@ -29,11 +28,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for ConfigurationSettingsInfo complex type. + * <p> + * Java class for ConfigurationSettingsInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="ConfigurationSettingsInfo"> @@ -50,27 +51,26 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "ConfigurationSettingsInfo", propOrder = { - "configurationSetting" -}) +@XmlType(name = "ConfigurationSettingsInfo", propOrder = { "configurationSetting" }) class ConfigurationSettingsInfo { @XmlElement(name = "ConfigurationSetting") - protected List<ConfigurationSettingInfo> configurationSetting; + private List<ConfigurationSettingInfo> configurationSetting; /** * Gets the value of the configurationSetting property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the configurationSetting property. + * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * <CODE>set</CODE> method for the configurationSetting property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getConfigurationSetting().add(newItem); + * getConfigurationSetting().add(newItem); * </pre> * * diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentRoleInstanceInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentRoleInstanceInfo.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentRoleInstanceInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentRoleInstanceInfo.java index 2e2e0cab510ee..e33580b9122b8 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentRoleInstanceInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentRoleInstanceInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -28,11 +27,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for CurrentRoleInstanceInfo complex type. + * <p> + * Java class for CurrentRoleInstanceInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="CurrentRoleInstanceInfo"> @@ -61,27 +62,25 @@ class CurrentRoleInstanceInfo { @XmlElement(name = "ConfigurationSettings") - protected ConfigurationSettingsInfo configurationSettings; + private ConfigurationSettingsInfo configurationSettings; @XmlElement(name = "LocalResources") - protected LocalResourcesInfo localResources; + private LocalResourcesInfo localResources; @XmlElement(name = "Endpoints") - protected EndpointsInfo endpoints; + private EndpointsInfo endpoints; @XmlAttribute(required = true) - protected String id; + private String id; @XmlAttribute(required = true) - protected String roleName; + private String roleName; @XmlAttribute(required = true) - protected int faultDomain; + private int faultDomain; @XmlAttribute(required = true) - protected int updateDomain; + private int updateDomain; /** * Gets the value of the configurationSettings property. * - * @return - * possible object is - * {@link ConfigurationSettingsInfo } - * + * @return possible object is {@link ConfigurationSettingsInfo } + * */ public ConfigurationSettingsInfo getConfigurationSettings() { return configurationSettings; @@ -91,9 +90,8 @@ public ConfigurationSettingsInfo getConfigurationSettings() { * Sets the value of the configurationSettings property. * * @param value - * allowed object is - * {@link ConfigurationSettingsInfo } - * + * allowed object is {@link ConfigurationSettingsInfo } + * */ public void setConfigurationSettings(ConfigurationSettingsInfo value) { this.configurationSettings = value; @@ -102,10 +100,8 @@ public void setConfigurationSettings(ConfigurationSettingsInfo value) { /** * Gets the value of the localResources property. * - * @return - * possible object is - * {@link LocalResourcesInfo } - * + * @return possible object is {@link LocalResourcesInfo } + * */ public LocalResourcesInfo getLocalResources() { return localResources; @@ -115,9 +111,8 @@ public LocalResourcesInfo getLocalResources() { * Sets the value of the localResources property. * * @param value - * allowed object is - * {@link LocalResourcesInfo } - * + * allowed object is {@link LocalResourcesInfo } + * */ public void setLocalResources(LocalResourcesInfo value) { this.localResources = value; @@ -126,10 +121,8 @@ public void setLocalResources(LocalResourcesInfo value) { /** * Gets the value of the endpoints property. * - * @return - * possible object is - * {@link EndpointsInfo } - * + * @return possible object is {@link EndpointsInfo } + * */ public EndpointsInfo getEndpoints() { return endpoints; @@ -139,9 +132,8 @@ public EndpointsInfo getEndpoints() { * Sets the value of the endpoints property. * * @param value - * allowed object is - * {@link EndpointsInfo } - * + * allowed object is {@link EndpointsInfo } + * */ public void setEndpoints(EndpointsInfo value) { this.endpoints = value; @@ -150,10 +142,8 @@ public void setEndpoints(EndpointsInfo value) { /** * Gets the value of the id property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getId() { return id; @@ -163,9 +153,8 @@ public String getId() { * Sets the value of the id property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setId(String value) { this.id = value; @@ -174,10 +163,8 @@ public void setId(String value) { /** * Gets the value of the roleName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getRoleName() { return roleName; @@ -187,9 +174,8 @@ public String getRoleName() { * Sets the value of the roleName property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setRoleName(String value) { this.roleName = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentState.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentState.java similarity index 96% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentState.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentState.java index 1a94780bec991..381a87e90c13f 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentState.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentState.java @@ -17,7 +17,7 @@ /** * */ -class CurrentState { +public class CurrentState { private final String clientId; public CurrentState(String clientId) { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateInfo.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateInfo.java index d1a510648d227..758b8781acfff 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for CurrentStateInfo complex type. + * <p> + * Java class for CurrentStateInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="CurrentStateInfo"> @@ -48,21 +49,17 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CurrentStateInfo", propOrder = { - "statusLease" -}) +@XmlType(name = "CurrentStateInfo", propOrder = { "statusLease" }) class CurrentStateInfo { @XmlElement(name = "StatusLease") - protected StatusLeaseInfo statusLease; + private StatusLeaseInfo statusLease; /** * Gets the value of the statusLease property. * - * @return - * possible object is - * {@link StatusLeaseInfo } - * + * @return possible object is {@link StatusLeaseInfo } + * */ public StatusLeaseInfo getStatusLease() { return statusLease; @@ -72,9 +69,8 @@ public StatusLeaseInfo getStatusLease() { * Sets the value of the statusLease property. * * @param value - * allowed object is - * {@link StatusLeaseInfo } - * + * allowed object is {@link StatusLeaseInfo } + * */ public void setStatusLease(StatusLeaseInfo value) { this.statusLease = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateSerializer.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateSerializer.java similarity index 91% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateSerializer.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateSerializer.java index a49ea402dd49e..d570daaee30fd 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateSerializer.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStateSerializer.java @@ -20,5 +20,5 @@ * */ interface CurrentStateSerializer { - public void serialize(CurrentState state, OutputStream stream); + void serialize(CurrentState state, OutputStream stream); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatus.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatus.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatus.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatus.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatusEnum.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatusEnum.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatusEnum.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatusEnum.java index 47ccf5fe608a2..577ea311d0921 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatusEnum.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/CurrentStatusEnum.java @@ -19,19 +19,21 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for CurrentStatusEnum. + * <p> + * Java class for CurrentStatusEnum. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within + * this class. + * <p> + * * <pre> * <simpleType name="CurrentStatusEnum"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -49,12 +51,9 @@ enum CurrentStatusEnum { @XmlEnumValue("Started") - STARTED("Started"), - @XmlEnumValue("Busy") - BUSY("Busy"), - @XmlEnumValue("Recycle") - RECYCLE("Recycle"), - @XmlEnumValue("Stopped") + STARTED("Started"), @XmlEnumValue("Busy") + BUSY("Busy"), @XmlEnumValue("Recycle") + RECYCLE("Recycle"), @XmlEnumValue("Stopped") STOPPED("Stopped"); private final String value; @@ -67,7 +66,7 @@ public String value() { } public static CurrentStatusEnum fromValue(String v) { - for (CurrentStatusEnum c: CurrentStatusEnum.values()) { + for (CurrentStatusEnum c : CurrentStatusEnum.values()) { if (c.value.equals(v)) { return c; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/DeploymentInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/DeploymentInfo.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/DeploymentInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/DeploymentInfo.java index bf718ae02a45e..dc564be1fb5bf 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/DeploymentInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/DeploymentInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for DeploymentInfo complex type. + * <p> + * Java class for DeploymentInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="DeploymentInfo"> @@ -51,17 +52,15 @@ class DeploymentInfo { @XmlAttribute(required = true) - protected String id; + private String id; @XmlAttribute(required = true) - protected boolean emulated; + private boolean emulated; /** * Gets the value of the id property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getId() { return id; @@ -71,9 +70,8 @@ public String getId() { * Sets the value of the id property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setId(String value) { this.id = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointInfo.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointInfo.java index 27080ec5e080e..9e67bfaceab51 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for EndpointInfo complex type. + * <p> + * Java class for EndpointInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="EndpointInfo"> @@ -53,21 +54,19 @@ class EndpointInfo { @XmlAttribute(required = true) - protected String name; + private String name; @XmlAttribute(required = true) - protected String address; + private String address; @XmlAttribute(required = true) - protected int port; + private int port; @XmlAttribute(required = true) - protected ProtocolEnum protocol; + private ProtocolEnum protocol; /** * Gets the value of the name property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getName() { return name; @@ -77,9 +76,8 @@ public String getName() { * Sets the value of the name property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setName(String value) { this.name = value; @@ -88,10 +86,8 @@ public void setName(String value) { /** * Gets the value of the address property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getAddress() { return address; @@ -101,9 +97,8 @@ public String getAddress() { * Sets the value of the address property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setAddress(String value) { this.address = value; @@ -128,10 +123,8 @@ public void setPort(int value) { /** * Gets the value of the protocol property. * - * @return - * possible object is - * {@link ProtocolEnum } - * + * @return possible object is {@link ProtocolEnum } + * */ public ProtocolEnum getProtocol() { return protocol; @@ -141,9 +134,8 @@ public ProtocolEnum getProtocol() { * Sets the value of the protocol property. * * @param value - * allowed object is - * {@link ProtocolEnum } - * + * allowed object is {@link ProtocolEnum } + * */ public void setProtocol(ProtocolEnum value) { this.protocol = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointsInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointsInfo.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointsInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointsInfo.java index c7fec0149f8c9..f2205f976dd7e 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointsInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/EndpointsInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.util.ArrayList; @@ -29,11 +28,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for EndpointsInfo complex type. + * <p> + * Java class for EndpointsInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="EndpointsInfo"> @@ -50,27 +51,26 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "EndpointsInfo", propOrder = { - "endpoint" -}) +@XmlType(name = "EndpointsInfo", propOrder = { "endpoint" }) class EndpointsInfo { @XmlElement(name = "Endpoint") - protected List<EndpointInfo> endpoint; + private List<EndpointInfo> endpoint; /** * Gets the value of the endpoint property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the endpoint property. + * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * <CODE>set</CODE> method for the endpoint property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getEndpoint().add(newItem); + * getEndpoint().add(newItem); * </pre> * * diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedState.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedState.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedState.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedState.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedStateEnum.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedStateEnum.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedStateEnum.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedStateEnum.java index 84dc6e399cf6a..8c25369670c59 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedStateEnum.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ExpectedStateEnum.java @@ -19,19 +19,21 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for ExpectedStateEnum. + * <p> + * Java class for ExpectedStateEnum. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within + * this class. + * <p> + * * <pre> * <simpleType name="ExpectedStateEnum"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -47,8 +49,7 @@ enum ExpectedStateEnum { @XmlEnumValue("Started") - STARTED("Started"), - @XmlEnumValue("Stopped") + STARTED("Started"), @XmlEnumValue("Stopped") STOPPED("Stopped"); private final String value; @@ -61,7 +62,7 @@ public String value() { } public static ExpectedStateEnum fromValue(String v) { - for (ExpectedStateEnum c: ExpectedStateEnum.values()) { + for (ExpectedStateEnum c : ExpectedStateEnum.values()) { if (c.value.equals(v)) { return c; } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/FileInputChannel.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/FileInputChannel.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/FileInputChannel.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/FileInputChannel.java index 3d4d2ee09ef3e..b215253076ee3 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/FileInputChannel.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/FileInputChannel.java @@ -28,8 +28,7 @@ public FileInputChannel() { public InputStream getInputStream(String name) { try { return new FileInputStream(name); - } - catch (FileNotFoundException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/FileOutputChannel.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/FileOutputChannel.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/FileOutputChannel.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/FileOutputChannel.java index 19d28d97d8593..89da18d14c88a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/FileOutputChannel.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/FileOutputChannel.java @@ -28,8 +28,7 @@ public FileOutputChannel() { public OutputStream getOutputStream(String name) { try { return new FileOutputStream(name); - } - catch (FileNotFoundException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalState.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalState.java similarity index 96% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalState.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalState.java index 5dce2f4fc9fb3..e2ea1e14619b1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalState.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalState.java @@ -27,7 +27,8 @@ class GoalState { private final Calendar deadline; private final String currentStateEndpoint; - public GoalState(BigInteger incarnation, ExpectedState expectedState, String environmentPath, Calendar deadline, + public GoalState(BigInteger incarnation, ExpectedState expectedState, + String environmentPath, Calendar deadline, String currentStateEndpoint) { this.incarnation = incarnation; this.expectedState = expectedState; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateChangedListener.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateChangedListener.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateChangedListener.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateChangedListener.java index 1ce379942f891..bbf56f84f2996 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateChangedListener.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateChangedListener.java @@ -18,5 +18,5 @@ * */ interface GoalStateChangedListener { - public void goalStateChanged(GoalState newGoalState); + void goalStateChanged(GoalState newGoalState); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateDeserializer.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateDeserializer.java similarity index 89% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateDeserializer.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateDeserializer.java index 71bea2022a6c3..6bb1d6e964d49 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateDeserializer.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateDeserializer.java @@ -20,7 +20,7 @@ * */ interface GoalStateDeserializer { - public void initialize(InputStream inputStream); + void initialize(InputStream inputStream); - public GoalState deserialize(); + GoalState deserialize(); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateInfo.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateInfo.java index 8cdab9ef1035d..eeea99899613a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/GoalStateInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.math.BigInteger; @@ -31,11 +30,13 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - /** - * <p>Java class for GoalStateInfo complex type. + * <p> + * Java class for GoalStateInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="GoalStateInfo"> @@ -63,25 +64,23 @@ class GoalStateInfo { @XmlElement(name = "Incarnation", required = true) @XmlSchemaType(name = "unsignedLong") - protected BigInteger incarnation; + private BigInteger incarnation; @XmlElement(name = "ExpectedState", required = true) - protected ExpectedStateEnum expectedState; + private ExpectedStateEnum expectedState; @XmlElement(name = "RoleEnvironmentPath", required = true) - protected String roleEnvironmentPath; + private String roleEnvironmentPath; @XmlElement(name = "CurrentStateEndpoint", required = true) - protected String currentStateEndpoint; + private String currentStateEndpoint; @XmlElement(name = "Deadline", required = true, type = String.class) - @XmlJavaTypeAdapter(Adapter1 .class) + @XmlJavaTypeAdapter(Adapter1.class) @XmlSchemaType(name = "dateTime") - protected Calendar deadline; + private Calendar deadline; /** * Gets the value of the incarnation property. * - * @return - * possible object is - * {@link BigInteger } - * + * @return possible object is {@link BigInteger } + * */ public BigInteger getIncarnation() { return incarnation; @@ -91,9 +90,8 @@ public BigInteger getIncarnation() { * Sets the value of the incarnation property. * * @param value - * allowed object is - * {@link BigInteger } - * + * allowed object is {@link BigInteger } + * */ public void setIncarnation(BigInteger value) { this.incarnation = value; @@ -102,10 +100,8 @@ public void setIncarnation(BigInteger value) { /** * Gets the value of the expectedState property. * - * @return - * possible object is - * {@link ExpectedStateEnum } - * + * @return possible object is {@link ExpectedStateEnum } + * */ public ExpectedStateEnum getExpectedState() { return expectedState; @@ -115,9 +111,8 @@ public ExpectedStateEnum getExpectedState() { * Sets the value of the expectedState property. * * @param value - * allowed object is - * {@link ExpectedStateEnum } - * + * allowed object is {@link ExpectedStateEnum } + * */ public void setExpectedState(ExpectedStateEnum value) { this.expectedState = value; @@ -126,10 +121,8 @@ public void setExpectedState(ExpectedStateEnum value) { /** * Gets the value of the roleEnvironmentPath property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getRoleEnvironmentPath() { return roleEnvironmentPath; @@ -139,9 +132,8 @@ public String getRoleEnvironmentPath() { * Sets the value of the roleEnvironmentPath property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setRoleEnvironmentPath(String value) { this.roleEnvironmentPath = value; @@ -150,10 +142,8 @@ public void setRoleEnvironmentPath(String value) { /** * Gets the value of the currentStateEndpoint property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getCurrentStateEndpoint() { return currentStateEndpoint; @@ -163,9 +153,8 @@ public String getCurrentStateEndpoint() { * Sets the value of the currentStateEndpoint property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setCurrentStateEndpoint(String value) { this.currentStateEndpoint = value; @@ -174,10 +163,8 @@ public void setCurrentStateEndpoint(String value) { /** * Gets the value of the deadline property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public Calendar getDeadline() { return deadline; @@ -187,9 +174,8 @@ public Calendar getDeadline() { * Sets the value of the deadline property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setDeadline(Calendar value) { this.deadline = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/InputChannel.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/InputChannel.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/InputChannel.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/InputChannel.java index 287281391853b..9de368bd2b319 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/InputChannel.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/InputChannel.java @@ -20,5 +20,5 @@ * */ interface InputChannel { - public abstract InputStream getInputStream(String name); + InputStream getInputStream(String name); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResource.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResource.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResource.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResource.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourceInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourceInfo.java similarity index 84% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourceInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourceInfo.java index 2f835312652b2..8961794ca604b 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourceInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourceInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for LocalResourceInfo complex type. + * <p> + * Java class for LocalResourceInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="LocalResourceInfo"> @@ -52,19 +53,17 @@ class LocalResourceInfo { @XmlAttribute(required = true) - protected String name; + private String name; @XmlAttribute(required = true) - protected String path; + private String path; @XmlAttribute(required = true) - protected int sizeInMB; + private int sizeInMB; /** * Gets the value of the name property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getName() { return name; @@ -74,9 +73,8 @@ public String getName() { * Sets the value of the name property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setName(String value) { this.name = value; @@ -85,10 +83,8 @@ public void setName(String value) { /** * Gets the value of the path property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getPath() { return path; @@ -98,9 +94,8 @@ public String getPath() { * Sets the value of the path property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setPath(String value) { this.path = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourcesInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourcesInfo.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourcesInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourcesInfo.java index fe827403e6105..28b7d7b0851a4 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourcesInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/LocalResourcesInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.util.ArrayList; @@ -29,11 +28,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for LocalResourcesInfo complex type. + * <p> + * Java class for LocalResourcesInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="LocalResourcesInfo"> @@ -50,27 +51,26 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "LocalResourcesInfo", propOrder = { - "localResource" -}) +@XmlType(name = "LocalResourcesInfo", propOrder = { "localResource" }) class LocalResourcesInfo { @XmlElement(name = "LocalResource") - protected List<LocalResourceInfo> localResource; + private List<LocalResourceInfo> localResource; /** * Gets the value of the localResource property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the localResource property. + * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * <CODE>set</CODE> method for the localResource property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getLocalResource().add(newItem); + * getLocalResource().add(newItem); * </pre> * * diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ObjectFactory.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ObjectFactory.java new file mode 100644 index 0000000000000..7868c6bef2ab8 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ObjectFactory.java @@ -0,0 +1,277 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.11.14 at 04:34:45 PM PST +// + +package com.microsoft.windowsazure.serviceruntime; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlRegistry; +import javax.xml.namespace.QName; + +/** + * This object contains factory methods for each Java content interface and Java + * element interface generated in the com.microsoft.windowsazure.serviceruntime + * package. + * <p> + * An ObjectFactory allows you to programatically construct new instances of the + * Java representation for XML content. The Java representation of XML content + * can consist of schema derived interfaces and classes representing the binding + * of schema type definitions, element declarations and model groups. Factory + * methods for each of these are provided in this class. + * + */ +@XmlRegistry +class ObjectFactory { + + private static final QName GOAL_STATE_QNAME = new QName("", "GoalState"); + private static final QName ROLE_ENVIRONMENT_QNAME = new QName("", + "RoleEnvironment"); + private static final QName CURRENT_STATE_QNAME = new QName("", + "CurrentState"); + private static final QName RUNTIME_SERVER_DISCOVERY_QNAME = new QName("", + "RuntimeServerDiscovery"); + + /** + * Create a new ObjectFactory that can be used to create new instances of + * schema derived classes for package: + * com.microsoft.windowsazure.serviceruntime + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link StatusLeaseInfo.Release } + * + */ + public StatusLeaseInfo.Release createStatusLeaseInfoRelease() { + return new StatusLeaseInfo.Release(); + } + + /** + * Create an instance of {@link RuntimeServerEndpointsInfo } + * + */ + public RuntimeServerEndpointsInfo createRuntimeServerEndpointsInfo() { + return new RuntimeServerEndpointsInfo(); + } + + /** + * Create an instance of {@link RuntimeServerEndpointInfo } + * + */ + public RuntimeServerEndpointInfo createRuntimeServerEndpointInfo() { + return new RuntimeServerEndpointInfo(); + } + + /** + * Create an instance of {@link RuntimeServerDiscoveryInfo } + * + */ + public RuntimeServerDiscoveryInfo createRuntimeServerDiscoveryInfo() { + return new RuntimeServerDiscoveryInfo(); + } + + /** + * Create an instance of {@link GoalStateInfo } + * + */ + public GoalStateInfo createGoalStateInfo() { + return new GoalStateInfo(); + } + + /** + * Create an instance of {@link LocalResourcesInfo } + * + */ + public LocalResourcesInfo createLocalResourcesInfo() { + return new LocalResourcesInfo(); + } + + /** + * Create an instance of {@link ConfigurationSettingInfo } + * + */ + public ConfigurationSettingInfo createConfigurationSettingInfo() { + return new ConfigurationSettingInfo(); + } + + /** + * Create an instance of {@link CurrentStateInfo } + * + */ + public CurrentStateInfo createCurrentStateInfo() { + return new CurrentStateInfo(); + } + + /** + * Create an instance of {@link CurrentRoleInstanceInfo } + * + */ + public CurrentRoleInstanceInfo createCurrentRoleInstanceInfo() { + return new CurrentRoleInstanceInfo(); + } + + /** + * Create an instance of {@link LocalResourceInfo } + * + */ + public LocalResourceInfo createLocalResourceInfo() { + return new LocalResourceInfo(); + } + + /** + * Create an instance of {@link RolesInfo } + * + */ + public RolesInfo createRolesInfo() { + return new RolesInfo(); + } + + /** + * Create an instance of {@link StatusLeaseInfo } + * + */ + public StatusLeaseInfo createStatusLeaseInfo() { + return new StatusLeaseInfo(); + } + + /** + * Create an instance of {@link DeploymentInfo } + * + */ + public DeploymentInfo createDeploymentInfo() { + return new DeploymentInfo(); + } + + /** + * Create an instance of {@link RoleInstancesInfo } + * + */ + public RoleInstancesInfo createRoleInstancesInfo() { + return new RoleInstancesInfo(); + } + + /** + * Create an instance of {@link RoleInfo } + * + */ + public RoleInfo createRoleInfo() { + return new RoleInfo(); + } + + /** + * Create an instance of {@link ConfigurationSettingsInfo } + * + */ + public ConfigurationSettingsInfo createConfigurationSettingsInfo() { + return new ConfigurationSettingsInfo(); + } + + /** + * Create an instance of {@link EndpointsInfo } + * + */ + public EndpointsInfo createEndpointsInfo() { + return new EndpointsInfo(); + } + + /** + * Create an instance of {@link AcquireLeaseInfo } + * + */ + public AcquireLeaseInfo createAcquireLeaseInfo() { + return new AcquireLeaseInfo(); + } + + /** + * Create an instance of {@link EndpointInfo } + * + */ + public EndpointInfo createEndpointInfo() { + return new EndpointInfo(); + } + + /** + * Create an instance of {@link RoleEnvironmentInfo } + * + */ + public RoleEnvironmentInfo createRoleEnvironmentInfo() { + return new RoleEnvironmentInfo(); + } + + /** + * Create an instance of {@link RoleInstanceInfo } + * + */ + public RoleInstanceInfo createRoleInstanceInfo() { + return new RoleInstanceInfo(); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link GoalStateInfo } + * {@code >} + * + */ + @XmlElementDecl(namespace = "", name = "GoalState") + public JAXBElement<GoalStateInfo> createGoalState(GoalStateInfo value) { + return new JAXBElement<GoalStateInfo>(GOAL_STATE_QNAME, + GoalStateInfo.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <} + * {@link RoleEnvironmentInfo }{@code >} + * + */ + @XmlElementDecl(namespace = "", name = "RoleEnvironment") + public JAXBElement<RoleEnvironmentInfo> createRoleEnvironment( + RoleEnvironmentInfo value) { + return new JAXBElement<RoleEnvironmentInfo>(ROLE_ENVIRONMENT_QNAME, + RoleEnvironmentInfo.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <} + * {@link CurrentStateInfo }{@code >} + * + */ + @XmlElementDecl(namespace = "", name = "CurrentState") + public JAXBElement<CurrentStateInfo> createCurrentState( + CurrentStateInfo value) { + return new JAXBElement<CurrentStateInfo>(CURRENT_STATE_QNAME, + CurrentStateInfo.class, null, value); + } + + /** + * Create an instance of {@link JAXBElement }{@code <} + * {@link RuntimeServerDiscoveryInfo }{@code >} + * + */ + @XmlElementDecl(namespace = "", name = "RuntimeServerDiscovery") + public JAXBElement<RuntimeServerDiscoveryInfo> createRuntimeServerDiscovery( + RuntimeServerDiscoveryInfo value) { + return new JAXBElement<RuntimeServerDiscoveryInfo>( + RUNTIME_SERVER_DISCOVERY_QNAME, + RuntimeServerDiscoveryInfo.class, null, value); + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/OutputChannel.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/OutputChannel.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/OutputChannel.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/OutputChannel.java index 10afcce3714a7..480d8dd6bd19d 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/OutputChannel.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/OutputChannel.java @@ -20,5 +20,5 @@ * */ interface OutputChannel { - public abstract OutputStream getOutputStream(String name); + OutputStream getOutputStream(String name); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeClient.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeClient.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeClient.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeClient.java index bc64390fa745b..62419b9a9e015 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeClient.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeClient.java @@ -21,8 +21,10 @@ class Protocol1RuntimeClient implements RuntimeClient { private final Protocol1RuntimeGoalStateClient goalStateClient; private final Protocol1RuntimeCurrentStateClient currentStateClient; - public Protocol1RuntimeClient(Protocol1RuntimeGoalStateClient goalStateClient, - Protocol1RuntimeCurrentStateClient currentStateClient, String endpoint) { + public Protocol1RuntimeClient( + Protocol1RuntimeGoalStateClient goalStateClient, + Protocol1RuntimeCurrentStateClient currentStateClient, + String endpoint) { this.goalStateClient = goalStateClient; this.currentStateClient = currentStateClient; @@ -35,7 +37,8 @@ public GoalState getCurrentGoalState() throws InterruptedException { } @Override - public RoleEnvironmentData getRoleEnvironmentData() throws InterruptedException { + public RoleEnvironmentData getRoleEnvironmentData() + throws InterruptedException { return goalStateClient.getRoleEnvironmentData(); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClient.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClient.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClient.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClient.java index 50386d173b70f..5963f0296d3fc 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClient.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClient.java @@ -26,7 +26,8 @@ class Protocol1RuntimeCurrentStateClient implements RuntimeCurrentStateClient { private final OutputChannel outputChannel; private final AtomicReference<String> endpoint; - public Protocol1RuntimeCurrentStateClient(CurrentStateSerializer serializer, OutputChannel outputChannel) { + public Protocol1RuntimeCurrentStateClient( + CurrentStateSerializer serializer, OutputChannel outputChannel) { this.serializer = serializer; this.outputChannel = outputChannel; this.endpoint = new AtomicReference<String>(); @@ -38,14 +39,14 @@ public void setEndpoint(String endpoint) { @Override public void setCurrentState(CurrentState state) { - OutputStream outputStream = outputChannel.getOutputStream(endpoint.get()); + OutputStream outputStream = outputChannel.getOutputStream(endpoint + .get()); serializer.serialize(state, outputStream); try { outputStream.close(); - } - catch (IOException e) { + } catch (IOException e) { throw new RoleEnvironmentNotAvailableException(e); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClient.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClient.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClient.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClient.java index 0f159c54eb7bd..a2ff1e191fd92 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClient.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClient.java @@ -37,8 +37,10 @@ class Protocol1RuntimeGoalStateClient implements RuntimeGoalStateClient { private AtomicReference<GoalState> currentGoalState; private AtomicReference<RoleEnvironmentData> currentEnvironmentData; - public Protocol1RuntimeGoalStateClient(Protocol1RuntimeCurrentStateClient currentStateClient, - GoalStateDeserializer goalStateDeserializer, RoleEnvironmentDataDeserializer roleEnvironmentDeserializer, + public Protocol1RuntimeGoalStateClient( + Protocol1RuntimeCurrentStateClient currentStateClient, + GoalStateDeserializer goalStateDeserializer, + RoleEnvironmentDataDeserializer roleEnvironmentDeserializer, InputChannel inputChannel) { this.currentStateClient = currentStateClient; this.goalStateDeserializer = goalStateDeserializer; @@ -58,19 +60,23 @@ public GoalState getCurrentGoalState() throws InterruptedException { return currentGoalState.get(); } - public synchronized RoleEnvironmentData getRoleEnvironmentData() throws InterruptedException { + public synchronized RoleEnvironmentData getRoleEnvironmentData() + throws InterruptedException { ensureGoalStateRetrieved(); if (currentEnvironmentData.get() == null) { GoalState current = currentGoalState.get(); if (current.getEnvironmentPath() == null) { - throw new InterruptedException("No role environment data for the current goal state."); + throw new InterruptedException( + "No role environment data for the current goal state."); } - InputStream environmentStream = inputChannel.getInputStream(current.getEnvironmentPath()); + InputStream environmentStream = inputChannel.getInputStream(current + .getEnvironmentPath()); - currentEnvironmentData.set(roleEnvironmentDeserializer.deserialize(environmentStream)); + currentEnvironmentData.set(roleEnvironmentDeserializer + .deserialize(environmentStream)); } return currentEnvironmentData.get(); @@ -123,7 +129,8 @@ public void run() { currentEnvironmentData.set(null); } - currentStateClient.setEndpoint(currentGoalState.get().getCurrentStateEndpoint()); + currentStateClient.setEndpoint(currentGoalState.get() + .getCurrentStateEndpoint()); goalStateLatch.countDown(); @@ -140,7 +147,8 @@ public void run() { currentEnvironmentData.set(null); } - currentStateClient.setEndpoint(currentGoalState.get().getCurrentStateEndpoint()); + currentStateClient.setEndpoint(currentGoalState.get() + .getCurrentStateEndpoint()); for (GoalStateChangedListener listener : listeners) { listener.goalStateChanged(currentGoalState.get()); diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ProtocolEnum.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ProtocolEnum.java new file mode 100644 index 0000000000000..de423ca98fb12 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ProtocolEnum.java @@ -0,0 +1,93 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.11.14 at 04:34:45 PM PST +// + +package com.microsoft.windowsazure.serviceruntime; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +/** + * <p> + * Java class for ProtocolEnum. + * + * <p> + * The following schema fragment specifies the expected content contained within + * this class. + * <p> + * + * <pre> + * <simpleType name="ProtocolEnum"> + * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> + * <enumeration value="ip"/> + * <enumeration value="tcp"/> + * <enumeration value="tls"/> + * <enumeration value="http"/> + * <enumeration value="https"/> + * <enumeration value="wcf:tcp"/> + * <enumeration value="wcf:tls"/> + * <enumeration value="wcf:http"/> + * <enumeration value="wcf:https"/> + * <enumeration value="wcf:https:certificate"/> + * <enumeration value="udp"/> + * <enumeration value="raw"/> + * </restriction> + * </simpleType> + * </pre> + * + */ +@XmlType(name = "ProtocolEnum") +@XmlEnum +enum ProtocolEnum { + + @XmlEnumValue("ip") + IP("ip"), @XmlEnumValue("tcp") + TCP("tcp"), @XmlEnumValue("tls") + TLS("tls"), @XmlEnumValue("http") + HTTP("http"), @XmlEnumValue("https") + HTTPS("https"), @XmlEnumValue("wcf:tcp") + WCF_TCP("wcf:tcp"), @XmlEnumValue("wcf:tls") + WCF_TLS("wcf:tls"), @XmlEnumValue("wcf:http") + WCF_HTTP("wcf:http"), @XmlEnumValue("wcf:https") + WCF_HTTPS("wcf:https"), @XmlEnumValue("wcf:https:certificate") + WCF_HTTPS_CERTIFICATE("wcf:https:certificate"), @XmlEnumValue("udp") + UDP("udp"), @XmlEnumValue("raw") + RAW("raw"); + private final String value; + + ProtocolEnum(String v) { + value = v; + } + + public String value() { + return value; + } + + public static ProtocolEnum fromValue(String v) { + for (ProtocolEnum c : ProtocolEnum.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ReleaseCurrentState.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ReleaseCurrentState.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/ReleaseCurrentState.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/ReleaseCurrentState.java diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Role.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Role.java new file mode 100644 index 0000000000000..84906b8482792 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/Role.java @@ -0,0 +1,64 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import java.util.Map; + +/** + * Represents a role that is defined as part of a hosted service. + */ +public final class Role { + private final String name; + private final Map<String, RoleInstance> instances; + + /** + * Constructor + * + * @param name + * @param instances + */ + Role(String name, Map<String, RoleInstance> instances) { + this.name = name; + this.instances = instances; + } + + /** + * Returns the collection of instances for the role. + * <p> + * The number of instances of a role to be deployed to Windows Azure is + * specified in the service's configuration file. + * <p> + * A role must define at least one internal endpoint in order for its set of + * instances to be known at runtime. + * + * @return A read-only <code>java.util.Map</code> object that contains the + * instances for the role, or <code>null</code> if the instances + * could not be retrieved. + */ + public Map<String, RoleInstance> getInstances() { + return instances; + } + + /** + * Returns the name of the role as it is declared in the service definition + * file. + * + * @return A <code>String</code> object that represents the name of the role + * as it is declared in the service definition file. + */ + public String getName() { + return name; + } +} diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironment.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironment.java new file mode 100644 index 0000000000000..d0ed83814986c --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironment.java @@ -0,0 +1,649 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; + +/** + * Represents the Windows Azure environment in which an instance of a role is + * running. + */ +public final class RoleEnvironment { + private static final String VERSION_ENDPOINT_ENVIRONMENT_NAME = "WaRuntimeEndpoint"; + private static final String VERSION_ENDPOINT_FIXED_PATH = "\\\\.\\pipe\\WindowsAzureRuntime"; + private static final String CLIENT_ID; + + private static RuntimeClient runtimeClient; + private static AtomicReference<GoalState> currentGoalState; + private static AtomicReference<RoleEnvironmentData> currentEnvironmentData; + private static List<RoleEnvironmentChangingListener> changingListeners; + private static List<RoleEnvironmentChangedListener> changedListeners; + private static List<RoleEnvironmentStoppingListener> stoppingListeners; + private static AtomicReference<CurrentState> lastState; + private static final Calendar MAX_DATE_TIME; + + static { + try { + JAXBContext.newInstance(RoleEnvironment.class.getPackage() + .getName()); + } catch (JAXBException e) { + e.printStackTrace(); + } + CLIENT_ID = UUID.randomUUID().toString(); + MAX_DATE_TIME = javax.xml.bind.DatatypeConverter + .parseDateTime("9999-12-31T23:59:59.9999999"); + } + + private RoleEnvironment() { + }; + + private static synchronized void initialize() { + if (runtimeClient == null) { + String endpoint = System.getenv(VERSION_ENDPOINT_ENVIRONMENT_NAME); + + if (endpoint == null) { + endpoint = VERSION_ENDPOINT_FIXED_PATH; + } + + RuntimeKernel kernel = RuntimeKernel.getKernel(); + + try { + runtimeClient = kernel.getRuntimeVersionManager() + .getRuntimeClient(endpoint); + } catch (Throwable t) { + throw new RoleEnvironmentNotAvailableException(t); + } + + changingListeners = new LinkedList<RoleEnvironmentChangingListener>(); + changedListeners = new LinkedList<RoleEnvironmentChangedListener>(); + stoppingListeners = new LinkedList<RoleEnvironmentStoppingListener>(); + + try { + currentGoalState = new AtomicReference<GoalState>( + runtimeClient.getCurrentGoalState()); + currentEnvironmentData = new AtomicReference<RoleEnvironmentData>( + runtimeClient.getRoleEnvironmentData()); + } catch (InterruptedException e) { + throw new RoleEnvironmentNotAvailableException(e); + } + + lastState = new AtomicReference<CurrentState>(); + + runtimeClient + .addGoalStateChangedListener(new GoalStateChangedListener() { + @Override + public void goalStateChanged(GoalState newGoalState) { + switch (newGoalState.getExpectedState()) { + case STARTED: + if (newGoalState.getIncarnation() + .compareTo( + currentGoalState.get() + .getIncarnation()) > 0) { + processGoalStateChange(newGoalState); + } + break; + case STOPPED: + raiseStoppingEvent(); + + CurrentState stoppedState = new AcquireCurrentState( + CLIENT_ID, + newGoalState.getIncarnation(), + CurrentStatus.STOPPED, MAX_DATE_TIME); + + runtimeClient.setCurrentState(stoppedState); + break; + default: + throw new IllegalArgumentException(); + } + } + }); + } else { + try { + currentGoalState.set(runtimeClient.getCurrentGoalState()); + currentEnvironmentData.set(runtimeClient + .getRoleEnvironmentData()); + } catch (InterruptedException e) { + throw new RoleEnvironmentNotAvailableException(e); + } + } + } + + private static void processGoalStateChange(GoalState newGoalState) { + List<RoleEnvironmentChange> changes = new LinkedList<RoleEnvironmentChange>(); + RoleEnvironmentChangingEvent changingEvent = new RoleEnvironmentChangingEvent( + changes); + CurrentState last = lastState.get(); + + calculateChanges(changes); + + if (changes.isEmpty()) { + acceptLatestIncarnation(newGoalState, last); + } else { + for (RoleEnvironmentChangingListener listener : changingListeners) { + try { + listener.roleEnvironmentChanging(changingEvent); + } catch (Throwable t) { + t.printStackTrace(); + } + } + + if (changingEvent.isCancelled()) { + CurrentState recycleState = new AcquireCurrentState(CLIENT_ID, + newGoalState.getIncarnation(), CurrentStatus.RECYCLE, + MAX_DATE_TIME); + + runtimeClient.setCurrentState(recycleState); + + return; + } + + acceptLatestIncarnation(newGoalState, last); + + try { + currentEnvironmentData.set(runtimeClient + .getRoleEnvironmentData()); + } catch (InterruptedException e) { + throw new RoleEnvironmentNotAvailableException(e); + } + + for (RoleEnvironmentChangedListener listener : changedListeners) { + try { + listener.roleEnvironmentChanged(new RoleEnvironmentChangedEvent( + changes)); + } catch (Throwable t) { + t.printStackTrace(); + } + } + } + } + + private static void acceptLatestIncarnation(GoalState newGoalState, + CurrentState last) { + if (last != null && last instanceof AcquireCurrentState) { + AcquireCurrentState acquireState = (AcquireCurrentState) last; + + CurrentState acceptState = new AcquireCurrentState(CLIENT_ID, + newGoalState.getIncarnation(), acquireState.getStatus(), + acquireState.getExpiration()); + + runtimeClient.setCurrentState(acceptState); + } + + currentGoalState.set(newGoalState); + } + + private static void calculateChanges(List<RoleEnvironmentChange> changes) { + RoleEnvironmentData current = currentEnvironmentData.get(); + RoleEnvironmentData newData; + + try { + newData = runtimeClient.getRoleEnvironmentData(); + } catch (InterruptedException e) { + throw new RoleEnvironmentNotAvailableException(e); + } + + Map<String, String> currentConfig = current.getConfigurationSettings(); + Map<String, String> newConfig = newData.getConfigurationSettings(); + Map<String, Role> currentRoles = current.getRoles(); + Map<String, Role> newRoles = newData.getRoles(); + + for (String setting : currentConfig.keySet()) { + if (newConfig.containsKey(setting)) { + if (!newConfig.get(setting).equals(currentConfig.get(setting))) { + changes.add(new RoleEnvironmentConfigurationSettingChange( + setting)); + } + } else { + changes.add(new RoleEnvironmentConfigurationSettingChange( + setting)); + } + } + + for (String setting : newConfig.keySet()) { + if (!currentConfig.containsKey(setting)) { + changes.add(new RoleEnvironmentConfigurationSettingChange( + setting)); + } + } + + Set<String> changedRoleSet = new HashSet<String>(); + + for (String role : currentRoles.keySet()) { + if (newRoles.containsKey(role)) { + Role currentRole = currentRoles.get(role); + Role newRole = newRoles.get(role); + + for (String instance : currentRole.getInstances().keySet()) { + if (newRole.getInstances().containsKey(instance)) { + RoleInstance currentInstance = currentRole + .getInstances().get(instance); + RoleInstance newInstance = newRole.getInstances().get( + instance); + + if (currentInstance.getUpdateDomain() == newInstance + .getUpdateDomain() + && currentInstance.getFaultDomain() == newInstance + .getFaultDomain()) { + for (String endpoint : currentInstance + .getInstanceEndpoints().keySet()) { + if (newInstance.getInstanceEndpoints() + .containsKey(endpoint)) { + RoleInstanceEndpoint currentEndpoint = currentInstance + .getInstanceEndpoints().get( + endpoint); + RoleInstanceEndpoint newEndpoint = newInstance + .getInstanceEndpoints().get( + endpoint); + + if (!currentEndpoint.getProtocol().equals( + newEndpoint.getProtocol()) + || !currentEndpoint.getIpEndPoint() + .equals(newEndpoint + .getIpEndPoint())) { + changedRoleSet.add(role); + } + } else { + changedRoleSet.add(role); + } + } + } else { + changedRoleSet.add(role); + } + } else { + changedRoleSet.add(role); + } + } + } else { + changedRoleSet.add(role); + } + } + + for (String role : newRoles.keySet()) { + if (currentRoles.containsKey(role)) { + Role currentRole = currentRoles.get(role); + Role newRole = newRoles.get(role); + + for (String instance : newRole.getInstances().keySet()) { + if (currentRole.getInstances().containsKey(instance)) { + RoleInstance currentInstance = currentRole + .getInstances().get(instance); + RoleInstance newInstance = newRole.getInstances().get( + instance); + + if (currentInstance.getUpdateDomain() == newInstance + .getUpdateDomain() + && currentInstance.getFaultDomain() == newInstance + .getFaultDomain()) { + for (String endpoint : newInstance + .getInstanceEndpoints().keySet()) { + if (currentInstance.getInstanceEndpoints() + .containsKey(endpoint)) { + RoleInstanceEndpoint currentEndpoint = currentInstance + .getInstanceEndpoints().get( + endpoint); + RoleInstanceEndpoint newEndpoint = newInstance + .getInstanceEndpoints().get( + endpoint); + + if (!currentEndpoint.getProtocol().equals( + newEndpoint.getProtocol()) + || !currentEndpoint.getIpEndPoint() + .equals(newEndpoint + .getIpEndPoint())) { + changedRoleSet.add(role); + } + } else { + changedRoleSet.add(role); + } + } + } else { + changedRoleSet.add(role); + } + } else { + changedRoleSet.add(role); + } + } + } else { + changedRoleSet.add(role); + } + } + + for (String role : changedRoleSet) { + changes.add(new RoleEnvironmentTopologyChange(role)); + } + } + + private static synchronized void raiseStoppingEvent() { + for (RoleEnvironmentStoppingListener listener : stoppingListeners) { + try { + listener.roleEnvironmentStopping(); + } catch (Throwable t) { + t.printStackTrace(); + } + } + } + + /** + * Returns a {@link RoleInstance} object that represents the role instance + * in which this code is currently executing. + * + * @return A <code>RoleInstance</code> object that represents the role + * instance in which this code is currently executing. + */ + public static RoleInstance getCurrentRoleInstance() { + initialize(); + + return currentEnvironmentData.get().getCurrentInstance(); + } + + /** + * Returns the deployment ID that uniquely identifies the deployment in + * which this role instance is running. + * + * @return A <code>String</code> object that represents the deployment ID. + */ + public static String getDeploymentId() { + initialize(); + + return currentEnvironmentData.get().getDeploymentId(); + } + + /** + * Indicates whether the role instance is running in the Windows Azure + * environment. + * + * @return <code>true</code> if this instance is running in the development + * fabric or in the Windows Azure environment in the cloud; + * otherwise, <code>false</code>. + */ + public static boolean isAvailable() { + try { + initialize(); + } catch (RoleEnvironmentNotAvailableException ex) { + } + + return runtimeClient != null; + } + + /** + * Indicates whether the role instance is running in the development fabric. + * + * @return <code>true</code> if this instance is running in the development + * fabric; otherwise, <code>false</code>. + */ + public static boolean isEmulated() { + initialize(); + + return currentEnvironmentData.get().isEmulated(); + } + + /** + * Returns the set of {@link Role} objects defined for your service. + * <p> + * Roles are defined in the service definition file. + * + * @return A <code>java.util.Map</code> object containing the set of + * {@link Role} objects that represent the roles defined for your + * service. + */ + public static Map<String, Role> getRoles() { + initialize(); + + return currentEnvironmentData.get().getRoles(); + } + + /** + * Retrieves the settings in the service configuration file. + * <p> + * A role's configuration settings are defined in the service definition + * file. Values for configuration settings are set in the service + * configuration file. + * + * @return A <code>java.util.Map</code> object containing the + * <code>String</code> objects that represent the configuration + * settings. + */ + public static Map<String, String> getConfigurationSettings() { + initialize(); + + return currentEnvironmentData.get().getConfigurationSettings(); + } + + /** + * Retrieves the set of named local storage resources. + * + * @return A <code>java.util.Map</code> object containing the + * <code>String</code> objects that represent the local storage + * resources. + */ + public static Map<String, LocalResource> getLocalResources() { + initialize(); + + return currentEnvironmentData.get().getLocalResources(); + } + + /** + * Requests that the current role instance be stopped and restarted. + * <p> + * Before the role instance is recycled, the Windows Azure load balancer + * takes the role instance out of rotation. This ensures that no new + * requests are routed to the instance while it is restarting. + * + * A call to <code>RequestRecycle</code> initiates the normal shutdown + * cycle. Windows Azure raises the <code>Stopping</code> event and calls the + * <code>OnStop</code> method so that you can run the necessary code to + * prepare the instance to be recycled. + */ + public static void requestRecycle() { + initialize(); + + CurrentState recycleState = new AcquireCurrentState(CLIENT_ID, + currentGoalState.get().getIncarnation(), CurrentStatus.RECYCLE, + MAX_DATE_TIME); + + runtimeClient.setCurrentState(recycleState); + } + + /** + * Sets the status of the role instance. + * <p> + * An instance may indicate that it is in one of two states: Ready or Busy. + * If an instance's state is Ready, it is prepared to receive requests from + * the load balancer. If the instance's state is Busy, it will not receive + * requests from the load balancer. + * + * @param status + * A {@link RoleInstanceStatus} value that indicates whether the + * instance is ready or busy. + * @param expirationUtc + * A <code>java.util.Date</code> value that specifies the + * expiration date and time of the status. + * + */ + public static void setStatus(RoleInstanceStatus status, Date expirationUtc) { + initialize(); + + CurrentStatus currentStatus = CurrentStatus.STARTED; + + switch (status) { + case Busy: + currentStatus = CurrentStatus.BUSY; + break; + case Ready: + currentStatus = CurrentStatus.STARTED; + default: + throw new IllegalArgumentException(); + } + + Calendar expiration = Calendar.getInstance(); + expiration.setTime(expirationUtc); + + CurrentState newState = new AcquireCurrentState(CLIENT_ID, + currentGoalState.get().getIncarnation(), currentStatus, + expiration); + + lastState.set(newState); + + runtimeClient.setCurrentState(newState); + } + + /** + * Clears the status of the role instance. + * <p> + * An instance may indicate that it has completed communicating status by + * calling this method. + * + */ + public static void clearStatus() { + initialize(); + + CurrentState newState = new ReleaseCurrentState(CLIENT_ID); + + lastState.set(newState); + + runtimeClient.setCurrentState(newState); + } + + /** + * Adds an event listener for the <code>Changed</code> event, which occurs + * after a configuration change has been applied to a role instance. + * <p> + * A <code>Changed</code> event is encapsulated in a + * {@link RoleEnvironmentChangedEvent} object. + * + * @param listener + * A {@link RoleEnvironmentChangedListener} object that + * represents the event listener to add. + * + * @see #removeRoleEnvironmentChangedListener + */ + public static synchronized void addRoleEnvironmentChangedListener( + RoleEnvironmentChangedListener listener) { + initialize(); + + changedListeners.add(listener); + } + + /** + * Removes an event listener for the <code>Changed</code> event. + * + * @param listener + * A {@link RoleEnvironmentChangedListener} object that + * represents the event listener to remove. + * + * @see #addRoleEnvironmentChangedListener + */ + public static synchronized void removeRoleEnvironmentChangedListener( + RoleEnvironmentChangedListener listener) { + initialize(); + + changedListeners.remove(listener); + } + + /** + * Adds an event listener for the <code>Changing</code> event, which occurs + * before a change to the service configuration is applied to the running + * instances of the role. + * <p> + * Service configuration changes are applied on-the-fly to running role + * instances. Configuration changes include changes to the service + * configuration changes and changes to the number of instances in the + * service. + * <p> + * This event occurs after the new configuration file has been submitted to + * Windows Azure but before the changes have been applied to each running + * role instance. This event can be cancelled for a given instance to + * prevent the configuration change. + * <p> + * Note that cancelling this event causes the instance to be automatically + * recycled. When the instance is recycled, the configuration change is + * applied when it restarts. + * <p> + * A <code>Changing</code> event is encapsulated in a + * {@link RoleEnvironmentChangingEvent} object. + * + * @param listener + * A {@link RoleEnvironmentChangingListener} object that + * represents the event listener to add. + * + * @see #removeRoleEnvironmentChangingListener + */ + public static synchronized void addRoleEnvironmentChangingListener( + RoleEnvironmentChangingListener listener) { + initialize(); + + changingListeners.add(listener); + } + + /** + * Removes an event listener for the <code>Changing</code> event. + * + * @param listener + * A {@link RoleEnvironmentChangingListener} object that + * represents the event listener to remove. + * + * @see #addRoleEnvironmentChangingListener + */ + public static void removeRoleEnvironmentChangingListener( + RoleEnvironmentChangingListener listener) { + initialize(); + + changingListeners.remove(listener); + } + + /** + * Adds an event listener for the <code>Stopping</code> event, which occurs + * wheen the role is stopping. + * + * @param listener + * A {@link RoleEnvironmentStoppingListener} object that + * represents the event listener to add. + * + * @see #removeRoleEnvironmentStoppingListener + */ + public static synchronized void addRoleEnvironmentStoppingListener( + RoleEnvironmentStoppingListener listener) { + initialize(); + + stoppingListeners.add(listener); + } + + /** + * Removes an event listener for the <code>Stopping</code> event. + * + * @param listener + * A {@link RoleEnvironmentStoppingListener} object that + * represents the event listener to remove. + * + * @see #addRoleEnvironmentStoppingListener + */ + public static synchronized void removeRoleEnvironmentStoppingListener( + RoleEnvironmentStoppingListener listener) { + initialize(); + + stoppingListeners.remove(listener); + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChange.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChange.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChange.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChange.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedEvent.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedEvent.java similarity index 95% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedEvent.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedEvent.java index 9f24a1ba276e4..06b13f43a44a9 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedEvent.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedEvent.java @@ -37,8 +37,8 @@ public class RoleEnvironmentChangedEvent { * Returns a collection of the configuration changes that were applied to * the role instance. * - * @return A <code>java.util.Collection</code> object containing the {@link RoleEnvironmentChange} objects that - * represent the + * @return A <code>java.util.Collection</code> object containing the + * {@link RoleEnvironmentChange} objects that represent the * configuration changes that were applied to the role instance. * * @see RoleEnvironmentChange diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedListener.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedListener.java similarity index 86% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedListener.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedListener.java index a70a6c2073c34..e85438fbcf787 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedListener.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangedListener.java @@ -17,7 +17,8 @@ /** * Represents the listener for the environment changed event. * <p> - * The environment changed event is encapsulated in a {@link RoleEnvironmentChangedEvent} object. + * The environment changed event is encapsulated in a + * {@link RoleEnvironmentChangedEvent} object. */ public interface RoleEnvironmentChangedListener { @@ -31,6 +32,5 @@ public interface RoleEnvironmentChangedListener { * * @see RoleEnvironmentChangingListener#roleEnvironmentChanging */ - public void roleEnvironmentChanged(RoleEnvironmentChangedEvent event); - + void roleEnvironmentChanged(RoleEnvironmentChangedEvent event); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingEvent.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingEvent.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingEvent.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingEvent.java index 47ea45eaddc5d..0591f9175771e 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingEvent.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingEvent.java @@ -21,15 +21,18 @@ * Occurs before a change to the service configuration is applied to the running * instances of the role. * <p> - * Service configuration changes are applied on-the-fly to running role instances. Configuration changes include changes - * to the service configuration changes and changes to the number of instances in the service. + * Service configuration changes are applied on-the-fly to running role + * instances. Configuration changes include changes to the service configuration + * changes and changes to the number of instances in the service. * <p> - * This event occurs after the new configuration file has been submitted to Windows Azure but before the changes have - * been applied to each running role instance. This event can be cancelled for a given instance to prevent the + * This event occurs after the new configuration file has been submitted to + * Windows Azure but before the changes have been applied to each running role + * instance. This event can be cancelled for a given instance to prevent the * configuration change. * <p> - * Note that cancelling this event causes the instance to be automatically recycled. When the instance is recycled, the - * configuration change is applied when it restarts. + * Note that cancelling this event causes the instance to be automatically + * recycled. When the instance is recycled, the configuration change is applied + * when it restarts. * * @see RoleEnvironmentChangingListener * @see RoleEnvironmentChangedEvent @@ -47,8 +50,8 @@ public class RoleEnvironmentChangingEvent { /** * Cancel the configuration change. * <p> - * Cancellation causes the role instance to be immediately recycled. The configuration changes are applied when the - * instance restarts. + * Cancellation causes the role instance to be immediately recycled. The + * configuration changes are applied when the instance restarts. * */ public void cancel() { @@ -63,8 +66,8 @@ boolean isCancelled() { * Returns a collection of the configuration changes that are about to be * applied to the role instance. * - * @return A <code>java.util.Collection</code> object containing {@link RoleEnvironmentChange} objects that - * represent the + * @return A <code>java.util.Collection</code> object containing + * {@link RoleEnvironmentChange} objects that represent the * configuration changes that are about to be applied to the role * instance. * diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingListener.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingListener.java new file mode 100644 index 0000000000000..ee68d364e1542 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentChangingListener.java @@ -0,0 +1,51 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +/** + * Represents the listener for the environment changing event. + * <p> + * The environment changing event is encapsulated in an + * {@link com.microsoft.windowsazure.serviceruntime.RoleEnvironmentChangingEvent} + * object. + */ +public interface RoleEnvironmentChangingListener { + + /** + * Occurs before a change to the service configuration is applied to the + * running instances of the role. + * <p> + * Service configuration changes are applied on-the-fly to running role + * instances. Configuration changes include changes to the service + * configuration changes and changes to the number of instances in the + * service. + * <p> + * This event occurs after the new configuration file has been submitted to + * Windows Azure but before the changes have been applied to each running + * role instance. This event can be cancelled for a given instance to + * prevent the configuration change. + * <p> + * Note that cancelling this event causes the instance to be automatically + * recycled. When the instance is recycled, the configuration change is + * applied when it restarts. + * + * @param event + * A {@link RoleEnvironmentChangingEvent} object that represents + * the environment changing event. + * + * @see RoleEnvironmentChangedListener#roleEnvironmentChanged + */ + void roleEnvironmentChanging(RoleEnvironmentChangingEvent event); +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentConfigurationSettingChange.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentConfigurationSettingChange.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentConfigurationSettingChange.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentConfigurationSettingChange.java index 98cb83df93714..66c0361df1556 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentConfigurationSettingChange.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentConfigurationSettingChange.java @@ -19,7 +19,8 @@ * * @see RoleEnvironmentTopologyChange */ -public class RoleEnvironmentConfigurationSettingChange extends RoleEnvironmentChange { +public class RoleEnvironmentConfigurationSettingChange extends + RoleEnvironmentChange { private String settingName; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentData.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentData.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentData.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentData.java index 77cd512331652..ad1df7efa1cdd 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentData.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentData.java @@ -27,8 +27,10 @@ class RoleEnvironmentData { private final Map<String, Role> roles; private final boolean isEmulated; - public RoleEnvironmentData(String deploymentId, Map<String, String> configurationSettings, - Map<String, LocalResource> localResources, RoleInstance currentInstance, Map<String, Role> roles, + public RoleEnvironmentData(String deploymentId, + Map<String, String> configurationSettings, + Map<String, LocalResource> localResources, + RoleInstance currentInstance, Map<String, Role> roles, boolean isEmulated) { this.deploymentId = deploymentId; this.configurationSettings = configurationSettings; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentDataDeserializer.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentDataDeserializer.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentDataDeserializer.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentDataDeserializer.java index a551898a69166..f19db19040479 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentDataDeserializer.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentDataDeserializer.java @@ -20,5 +20,5 @@ * */ interface RoleEnvironmentDataDeserializer { - public RoleEnvironmentData deserialize(InputStream stream); + RoleEnvironmentData deserialize(InputStream stream); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentInfo.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentInfo.java index 8c14d2406b326..5f432fd1570a3 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RoleEnvironmentInfo complex type. + * <p> + * Java class for RoleEnvironmentInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RoleEnvironmentInfo"> @@ -56,19 +57,17 @@ class RoleEnvironmentInfo { @XmlElement(name = "Deployment", required = true) - protected DeploymentInfo deployment; + private DeploymentInfo deployment; @XmlElement(name = "CurrentInstance", required = true) - protected CurrentRoleInstanceInfo currentInstance; + private CurrentRoleInstanceInfo currentInstance; @XmlElement(name = "Roles") - protected RolesInfo roles; + private RolesInfo roles; /** * Gets the value of the deployment property. * - * @return - * possible object is - * {@link DeploymentInfo } - * + * @return possible object is {@link DeploymentInfo } + * */ public DeploymentInfo getDeployment() { return deployment; @@ -78,9 +77,8 @@ public DeploymentInfo getDeployment() { * Sets the value of the deployment property. * * @param value - * allowed object is - * {@link DeploymentInfo } - * + * allowed object is {@link DeploymentInfo } + * */ public void setDeployment(DeploymentInfo value) { this.deployment = value; @@ -89,10 +87,8 @@ public void setDeployment(DeploymentInfo value) { /** * Gets the value of the currentInstance property. * - * @return - * possible object is - * {@link CurrentRoleInstanceInfo } - * + * @return possible object is {@link CurrentRoleInstanceInfo } + * */ public CurrentRoleInstanceInfo getCurrentInstance() { return currentInstance; @@ -102,9 +98,8 @@ public CurrentRoleInstanceInfo getCurrentInstance() { * Sets the value of the currentInstance property. * * @param value - * allowed object is - * {@link CurrentRoleInstanceInfo } - * + * allowed object is {@link CurrentRoleInstanceInfo } + * */ public void setCurrentInstance(CurrentRoleInstanceInfo value) { this.currentInstance = value; @@ -113,10 +108,8 @@ public void setCurrentInstance(CurrentRoleInstanceInfo value) { /** * Gets the value of the roles property. * - * @return - * possible object is - * {@link RolesInfo } - * + * @return possible object is {@link RolesInfo } + * */ public RolesInfo getRoles() { return roles; @@ -126,9 +119,8 @@ public RolesInfo getRoles() { * Sets the value of the roles property. * * @param value - * allowed object is - * {@link RolesInfo } - * + * allowed object is {@link RolesInfo } + * */ public void setRoles(RolesInfo value) { this.roles = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentNotAvailableException.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentNotAvailableException.java similarity index 92% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentNotAvailableException.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentNotAvailableException.java index bf0155fe25f4e..47402157ef940 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentNotAvailableException.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentNotAvailableException.java @@ -22,7 +22,8 @@ public class RoleEnvironmentNotAvailableException extends RuntimeException { private static final long serialVersionUID = -6218741025124056882L; /** - * Creates an instance of the <code>RoleEnvironmentNotAvailableException</code> class. + * Creates an instance of the + * <code>RoleEnvironmentNotAvailableException</code> class. * * @param t * A <code>java.lang.Throwable</code> object that represents the diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentStoppingListener.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentStoppingListener.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentStoppingListener.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentStoppingListener.java index d00d8081c77d6..09aded98fd708 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentStoppingListener.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentStoppingListener.java @@ -21,11 +21,12 @@ public interface RoleEnvironmentStoppingListener { /** * Occurs when the role instance is about to be stopped. * <p> - * This event is raised after the instance has been taken out of the load balancer's rotation before the - * <code>OnStop</code> method is called. You can use this event to run code that is required for the role instance - * to shut down in an orderly fashion. + * This event is raised after the instance has been taken out of the load + * balancer's rotation before the <code>OnStop</code> method is called. You + * can use this event to run code that is required for the role instance to + * shut down in an orderly fashion. */ - public void roleEnvironmentStopping(); + void roleEnvironmentStopping(); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTopologyChange.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTopologyChange.java similarity index 96% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTopologyChange.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTopologyChange.java index f7709f3da541a..dd56af84bf6b1 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTopologyChange.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTopologyChange.java @@ -17,7 +17,8 @@ /** * Represents a change to the topology of the service. * <p> - * The service's topology refers to the number of instances deployed for each role that the service defines. + * The service's topology refers to the number of instances deployed for each + * role that the service defines. */ public class RoleEnvironmentTopologyChange extends RoleEnvironmentChange { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInfo.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInfo.java index 98e36249cfcd2..13d40d942f767 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -28,11 +27,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RoleInfo complex type. + * <p> + * Java class for RoleInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RoleInfo"> @@ -53,20 +54,18 @@ @XmlType(name = "RoleInfo", propOrder = { }) -class RoleInfo { +public class RoleInfo { @XmlElement(name = "Instances", required = true) - protected RoleInstancesInfo instances; + private RoleInstancesInfo instances; @XmlAttribute(required = true) - protected String name; + private String name; /** * Gets the value of the instances property. * - * @return - * possible object is - * {@link RoleInstancesInfo } - * + * @return possible object is {@link RoleInstancesInfo } + * */ public RoleInstancesInfo getInstances() { return instances; @@ -76,9 +75,8 @@ public RoleInstancesInfo getInstances() { * Sets the value of the instances property. * * @param value - * allowed object is - * {@link RoleInstancesInfo } - * + * allowed object is {@link RoleInstancesInfo } + * */ public void setInstances(RoleInstancesInfo value) { this.instances = value; @@ -87,10 +85,8 @@ public void setInstances(RoleInstancesInfo value) { /** * Gets the value of the name property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getName() { return name; @@ -100,9 +96,8 @@ public String getName() { * Sets the value of the name property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setName(String value) { this.name = value; diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstance.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstance.java new file mode 100644 index 0000000000000..db73e9fc2b694 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstance.java @@ -0,0 +1,103 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import java.util.Map; + +/** + * Represents an instance of a role. + */ +public final class RoleInstance { + private final String id; + private final int faultDomain; + private final int updateDomain; + private final Map<String, RoleInstanceEndpoint> endpoints; + private Role role; + + /** + * Constructor + * + * @param id + * @param faultDomain + * @param updateDomain + * @param endpoints + */ + RoleInstance(String id, int faultDomain, int updateDomain, + Map<String, RoleInstanceEndpoint> endpoints) { + this.id = id; + this.faultDomain = faultDomain; + this.updateDomain = updateDomain; + this.endpoints = endpoints; + } + + void setRole(Role role) { + this.role = role; + } + + /** + * Returns an integer value that indicates the fault domain in which this + * instance resides. + * + * @return The fault domain in which this instance resides. + */ + public int getFaultDomain() { + return faultDomain; + } + + /** + * Returns the ID of this instance. + * <p> + * The returned ID is unique to the application domain of the role's + * instance. If an instance is terminated and has been configured to restart + * automatically, the restarted instance will have the same ID as the + * terminated instance. + * + * @return A <code>String</code> object that represents the ID of this + * instance. + */ + public String getId() { + return id; + } + + /** + * Returns an integer value that indicates the update domain in which this + * instance resides. + * + * @return The update domain in which this instance resides. + */ + public int getUpdateDomain() { + return updateDomain; + } + + /** + * Returns the {@link Role} object associated with this instance. + * + * @return The <code>Role</code> object associated with this instance + */ + public Role getRole() { + return role; + } + + /** + * Returns the set of endpoints associated with this role instance. + * + * @return A <code>Map</code> object of {@link RoleInstanceEndpoint} objects + * that represent the set of endpoints associated with this role + * instance. + */ + public Map<String, RoleInstanceEndpoint> getInstanceEndpoints() { + return endpoints; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceEndpoint.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceEndpoint.java similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceEndpoint.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceEndpoint.java diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceInfo.java similarity index 85% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceInfo.java index ef81ccbcf049b..1e6c507dfbff7 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -28,11 +27,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RoleInstanceInfo complex type. + * <p> + * Java class for RoleInstanceInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RoleInstanceInfo"> @@ -58,21 +59,19 @@ class RoleInstanceInfo { @XmlElement(name = "Endpoints", required = true) - protected EndpointsInfo endpoints; + private EndpointsInfo endpoints; @XmlAttribute(required = true) - protected String id; + private String id; @XmlAttribute(required = true) - protected int faultDomain; + private int faultDomain; @XmlAttribute(required = true) - protected int updateDomain; + private int updateDomain; /** * Gets the value of the endpoints property. * - * @return - * possible object is - * {@link EndpointsInfo } - * + * @return possible object is {@link EndpointsInfo } + * */ public EndpointsInfo getEndpoints() { return endpoints; @@ -82,9 +81,8 @@ public EndpointsInfo getEndpoints() { * Sets the value of the endpoints property. * * @param value - * allowed object is - * {@link EndpointsInfo } - * + * allowed object is {@link EndpointsInfo } + * */ public void setEndpoints(EndpointsInfo value) { this.endpoints = value; @@ -93,10 +91,8 @@ public void setEndpoints(EndpointsInfo value) { /** * Gets the value of the id property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getId() { return id; @@ -106,9 +102,8 @@ public String getId() { * Sets the value of the id property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setId(String value) { this.id = value; diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceStatus.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceStatus.java new file mode 100644 index 0000000000000..ca0a2677e7fd6 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstanceStatus.java @@ -0,0 +1,32 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +/** + * Defines role instance status values, such as Busy and Ready. + * <p> + * The {@link RoleEnvironment#setStatus} method uses a value from this + * enumeration. + */ +public enum RoleInstanceStatus { + /** + * The role instance is unavailable for requests. + */ + Busy, + /** + * The role instance is ready to accept requests. + */ + Ready +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstancesInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstancesInfo.java similarity index 81% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstancesInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstancesInfo.java index ce1e0a1b36ae9..b0d73add645b9 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstancesInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RoleInstancesInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.util.ArrayList; @@ -29,11 +28,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RoleInstancesInfo complex type. + * <p> + * Java class for RoleInstancesInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RoleInstancesInfo"> @@ -50,27 +51,26 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "RoleInstancesInfo", propOrder = { - "instance" -}) +@XmlType(name = "RoleInstancesInfo", propOrder = { "instance" }) class RoleInstancesInfo { @XmlElement(name = "Instance") - protected List<RoleInstanceInfo> instance; + private List<RoleInstanceInfo> instance; /** * Gets the value of the instance property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the instance property. + * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * <CODE>set</CODE> method for the instance property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getInstance().add(newItem); + * getInstance().add(newItem); * </pre> * * diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RolesInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RolesInfo.java similarity index 79% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RolesInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RolesInfo.java index cf0d27cff09e2..fd5b94fa62189 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RolesInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RolesInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.util.ArrayList; @@ -29,11 +28,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RolesInfo complex type. + * <p> + * Java class for RolesInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RolesInfo"> @@ -50,33 +51,31 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "RolesInfo", propOrder = { - "role" -}) +@XmlType(name = "RolesInfo", propOrder = { "role" }) class RolesInfo { @XmlElement(name = "Role") - protected List<RoleInfo> role; + private List<RoleInfo> role; /** * Gets the value of the role property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the role property. + * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * <CODE>set</CODE> method for the role property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getRole().add(newItem); + * getRole().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link RoleInfo } + * Objects of the following type(s) are allowed in the list {@link RoleInfo } * * */ diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClient.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClient.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClient.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClient.java index db615c19f24e5..7b0fac5f5195a 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClient.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClient.java @@ -17,6 +17,7 @@ /** * */ -interface RuntimeClient extends RuntimeGoalStateClient, RuntimeCurrentStateClient { +interface RuntimeClient extends RuntimeGoalStateClient, + RuntimeCurrentStateClient { } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClientFactory.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClientFactory.java similarity index 88% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClientFactory.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClientFactory.java index 23934f16847b3..2a80a6af28c87 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClientFactory.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeClientFactory.java @@ -18,7 +18,7 @@ * */ interface RuntimeClientFactory { - public String getVersion(); + String getVersion(); - public RuntimeClient createRuntimeClient(String path); + RuntimeClient createRuntimeClient(String path); } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeCurrentStateClient.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeCurrentStateClient.java similarity index 93% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeCurrentStateClient.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeCurrentStateClient.java index aa07d24e26152..480752e66157d 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeCurrentStateClient.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeCurrentStateClient.java @@ -18,5 +18,5 @@ * */ interface RuntimeCurrentStateClient { - public void setCurrentState(CurrentState state); + void setCurrentState(CurrentState state); } diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeGoalStateClient.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeGoalStateClient.java new file mode 100644 index 0000000000000..824ebf1f9d895 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeGoalStateClient.java @@ -0,0 +1,29 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +/** + * + */ +interface RuntimeGoalStateClient { + GoalState getCurrentGoalState() throws InterruptedException; + + RoleEnvironmentData getRoleEnvironmentData() + throws InterruptedException; + + void addGoalStateChangedListener(GoalStateChangedListener listener); + + void removeGoalStateChangedListener(GoalStateChangedListener listener); +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeKernel.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeKernel.java similarity index 87% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeKernel.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeKernel.java index 2189b14c8a625..5abf564aca784 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeKernel.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeKernel.java @@ -17,7 +17,7 @@ /** * */ -class RuntimeKernel { +public final class RuntimeKernel { private static RuntimeKernel theKernel; private final CurrentStateSerializer currentStateSerializer; @@ -35,13 +35,16 @@ private RuntimeKernel() { this.goalStateDeserializer = new ChunkedGoalStateDeserializer(); this.inputChannel = new FileInputChannel(); this.outputChannel = new FileOutputChannel(); - this.protocol1RuntimeCurrentStateClient = new Protocol1RuntimeCurrentStateClient(currentStateSerializer, - outputChannel); + this.protocol1RuntimeCurrentStateClient = new Protocol1RuntimeCurrentStateClient( + currentStateSerializer, outputChannel); this.roleEnvironmentDataDeserializer = new XmlRoleEnvironmentDataDeserializer(); - this.protocol1RuntimeGoalStateClient = new Protocol1RuntimeGoalStateClient(protocol1RuntimeCurrentStateClient, - goalStateDeserializer, roleEnvironmentDataDeserializer, inputChannel); - this.runtimeVersionProtocolClient = new RuntimeVersionProtocolClient(inputChannel); - this.runtimeVersionManager = new RuntimeVersionManager(runtimeVersionProtocolClient); + this.protocol1RuntimeGoalStateClient = new Protocol1RuntimeGoalStateClient( + protocol1RuntimeCurrentStateClient, goalStateDeserializer, + roleEnvironmentDataDeserializer, inputChannel); + this.runtimeVersionProtocolClient = new RuntimeVersionProtocolClient( + inputChannel); + this.runtimeVersionManager = new RuntimeVersionManager( + runtimeVersionProtocolClient); } public static RuntimeKernel getKernel() { diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerDiscoveryInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerDiscoveryInfo.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerDiscoveryInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerDiscoveryInfo.java index 95d8d15c81b41..bae5519a23739 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerDiscoveryInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerDiscoveryInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RuntimeServerDiscoveryInfo complex type. + * <p> + * Java class for RuntimeServerDiscoveryInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RuntimeServerDiscoveryInfo"> @@ -51,18 +52,16 @@ @XmlType(name = "RuntimeServerDiscoveryInfo", propOrder = { }) -class RuntimeServerDiscoveryInfo { +public class RuntimeServerDiscoveryInfo { @XmlElement(name = "RuntimeServerEndpoints", required = true) - protected RuntimeServerEndpointsInfo runtimeServerEndpoints; + private RuntimeServerEndpointsInfo runtimeServerEndpoints; /** * Gets the value of the runtimeServerEndpoints property. * - * @return - * possible object is - * {@link RuntimeServerEndpointsInfo } - * + * @return possible object is {@link RuntimeServerEndpointsInfo } + * */ public RuntimeServerEndpointsInfo getRuntimeServerEndpoints() { return runtimeServerEndpoints; @@ -72,9 +71,8 @@ public RuntimeServerEndpointsInfo getRuntimeServerEndpoints() { * Sets the value of the runtimeServerEndpoints property. * * @param value - * allowed object is - * {@link RuntimeServerEndpointsInfo } - * + * allowed object is {@link RuntimeServerEndpointsInfo } + * */ public void setRuntimeServerEndpoints(RuntimeServerEndpointsInfo value) { this.runtimeServerEndpoints = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointInfo.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointInfo.java index 70813f42b9fcf..77fbf20e85bfe 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -27,11 +26,13 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RuntimeServerEndpointInfo complex type. + * <p> + * Java class for RuntimeServerEndpointInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RuntimeServerEndpointInfo"> @@ -51,17 +52,15 @@ class RuntimeServerEndpointInfo { @XmlAttribute(required = true) - protected String version; + private String version; @XmlAttribute(required = true) - protected String path; + private String path; /** * Gets the value of the version property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVersion() { return version; @@ -71,9 +70,8 @@ public String getVersion() { * Sets the value of the version property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setVersion(String value) { this.version = value; @@ -82,10 +80,8 @@ public void setVersion(String value) { /** * Gets the value of the path property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getPath() { return path; @@ -95,9 +91,8 @@ public String getPath() { * Sets the value of the path property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setPath(String value) { this.path = value; diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointsInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointsInfo.java similarity index 80% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointsInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointsInfo.java index 4de26b3436725..e9acacdecbe08 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointsInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeServerEndpointsInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import java.util.ArrayList; @@ -29,11 +28,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for RuntimeServerEndpointsInfo complex type. + * <p> + * Java class for RuntimeServerEndpointsInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="RuntimeServerEndpointsInfo"> @@ -50,27 +51,26 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "RuntimeServerEndpointsInfo", propOrder = { - "runtimeServerEndpoint" -}) +@XmlType(name = "RuntimeServerEndpointsInfo", propOrder = { "runtimeServerEndpoint" }) class RuntimeServerEndpointsInfo { @XmlElement(name = "RuntimeServerEndpoint") - protected List<RuntimeServerEndpointInfo> runtimeServerEndpoint; + private List<RuntimeServerEndpointInfo> runtimeServerEndpoint; /** * Gets the value of the runtimeServerEndpoint property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the runtimeServerEndpoint property. + * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * <CODE>set</CODE> method for the runtimeServerEndpoint property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getRuntimeServerEndpoint().add(newItem); + * getRuntimeServerEndpoint().add(newItem); * </pre> * * @@ -86,5 +86,4 @@ public List<RuntimeServerEndpointInfo> getRuntimeServerEndpoint() { } return this.runtimeServerEndpoint; } - -} +} \ No newline at end of file diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManager.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManager.java similarity index 82% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManager.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManager.java index 09931c8a5f854..39f9207c09f65 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManager.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManager.java @@ -38,21 +38,25 @@ public String getVersion() { public RuntimeClient createRuntimeClient(String path) { RuntimeKernel kernel = RuntimeKernel.getKernel(); - return new Protocol1RuntimeClient(kernel.getProtocol1RuntimeGoalStateClient(), kernel + return new Protocol1RuntimeClient(kernel + .getProtocol1RuntimeGoalStateClient(), kernel .getProtocol1RuntimeCurrentStateClient(), path); } }); } public RuntimeClient getRuntimeClient(String versionEndpoint) { - Map<String, String> versionMap = protocolClient.getVersionMap(versionEndpoint); + Map<String, String> versionMap = protocolClient + .getVersionMap(versionEndpoint); for (RuntimeClientFactory factory : supportedVersionList) { if (versionMap.containsKey(factory.getVersion())) { - return factory.createRuntimeClient(versionMap.get(factory.getVersion())); + return factory.createRuntimeClient(versionMap.get(factory + .getVersion())); } } - throw new RuntimeException("Server does not support any known protocol versions."); + throw new RuntimeException( + "Server does not support any known protocol versions."); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionProtocolClient.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionProtocolClient.java similarity index 86% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionProtocolClient.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionProtocolClient.java index 1895b03ac9144..81ca676914a30 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionProtocolClient.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionProtocolClient.java @@ -36,7 +36,9 @@ public RuntimeVersionProtocolClient(InputChannel inputChannel) { public Map<String, String> getVersionMap(String connectionPath) { try { Map<String, String> versions = new HashMap<String, String>(); - JAXBContext context = JAXBContext.newInstance(RuntimeServerDiscoveryInfo.class.getPackage().getName()); + JAXBContext context = JAXBContext + .newInstance(RuntimeServerDiscoveryInfo.class.getPackage() + .getName()); Unmarshaller unmarshaller = context.createUnmarshaller(); InputStream input = inputChannel.getInputStream(connectionPath); @@ -44,14 +46,13 @@ public Map<String, String> getVersionMap(String connectionPath) { RuntimeServerDiscoveryInfo discoveryInfo = ((JAXBElement<RuntimeServerDiscoveryInfo>) unmarshaller .unmarshal(input)).getValue(); - for (RuntimeServerEndpointInfo endpointInfo : discoveryInfo.getRuntimeServerEndpoints() - .getRuntimeServerEndpoint()) { + for (RuntimeServerEndpointInfo endpointInfo : discoveryInfo + .getRuntimeServerEndpoints().getRuntimeServerEndpoint()) { versions.put(endpointInfo.getVersion(), endpointInfo.getPath()); } return versions; - } - catch (JAXBException e) { + } catch (JAXBException e) { throw new RuntimeException(e); } } diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/StatusLeaseInfo.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/StatusLeaseInfo.java similarity index 78% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/StatusLeaseInfo.java rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/StatusLeaseInfo.java index 8c67f9c094ab6..134b9eadce349 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/StatusLeaseInfo.java +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/StatusLeaseInfo.java @@ -19,7 +19,6 @@ // Generated on: 2011.11.14 at 04:34:45 PM PST // - package com.microsoft.windowsazure.serviceruntime; import javax.xml.bind.annotation.XmlAccessType; @@ -28,11 +27,13 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; - /** - * <p>Java class for StatusLeaseInfo complex type. + * <p> + * Java class for StatusLeaseInfo complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within + * this class. * * <pre> * <complexType name="StatusLeaseInfo"> @@ -58,26 +59,21 @@ * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "StatusLeaseInfo", propOrder = { - "acquire", - "release" -}) +@XmlType(name = "StatusLeaseInfo", propOrder = { "acquire", "release" }) class StatusLeaseInfo { @XmlElement(name = "Acquire") - protected AcquireLeaseInfo acquire; + private AcquireLeaseInfo acquire; @XmlElement(name = "Release") - protected StatusLeaseInfo.Release release; + private StatusLeaseInfo.Release release; @XmlAttribute(name = "ClientId", required = true) - protected String clientId; + private String clientId; /** * Gets the value of the acquire property. * - * @return - * possible object is - * {@link AcquireLeaseInfo } - * + * @return possible object is {@link AcquireLeaseInfo } + * */ public AcquireLeaseInfo getAcquire() { return acquire; @@ -87,9 +83,8 @@ public AcquireLeaseInfo getAcquire() { * Sets the value of the acquire property. * * @param value - * allowed object is - * {@link AcquireLeaseInfo } - * + * allowed object is {@link AcquireLeaseInfo } + * */ public void setAcquire(AcquireLeaseInfo value) { this.acquire = value; @@ -98,10 +93,8 @@ public void setAcquire(AcquireLeaseInfo value) { /** * Gets the value of the release property. * - * @return - * possible object is - * {@link StatusLeaseInfo.Release } - * + * @return possible object is {@link StatusLeaseInfo.Release } + * */ public StatusLeaseInfo.Release getRelease() { return release; @@ -111,9 +104,8 @@ public StatusLeaseInfo.Release getRelease() { * Sets the value of the release property. * * @param value - * allowed object is - * {@link StatusLeaseInfo.Release } - * + * allowed object is {@link StatusLeaseInfo.Release } + * */ public void setRelease(StatusLeaseInfo.Release value) { this.release = value; @@ -122,10 +114,8 @@ public void setRelease(StatusLeaseInfo.Release value) { /** * Gets the value of the clientId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getClientId() { return clientId; @@ -135,19 +125,20 @@ public String getClientId() { * Sets the value of the clientId property. * * @param value - * allowed object is - * {@link String } - * + * allowed object is {@link String } + * */ public void setClientId(String value) { this.clientId = value; } - /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained + * within this class. * * <pre> * <complexType> @@ -164,7 +155,6 @@ public void setClientId(String value) { @XmlType(name = "") public static class Release { - } } diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlCurrentStateSerializer.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlCurrentStateSerializer.java new file mode 100644 index 0000000000000..a0377a8e841e9 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlCurrentStateSerializer.java @@ -0,0 +1,78 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import java.io.OutputStream; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; + +/** + * + */ +class XmlCurrentStateSerializer implements CurrentStateSerializer { + public XmlCurrentStateSerializer() { + } + + public void serialize(CurrentState state, OutputStream stream) { + try { + JAXBContext context = JAXBContext.newInstance(GoalStateInfo.class + .getPackage().getName()); + Marshaller marshaller = context.createMarshaller(); + + ObjectFactory factory = new ObjectFactory(); + CurrentStateInfo info = factory.createCurrentStateInfo(); + StatusLeaseInfo leaseInfo = factory.createStatusLeaseInfo(); + + leaseInfo.setClientId(state.getClientId()); + + if (state instanceof AcquireCurrentState) { + AcquireCurrentState acquireState = (AcquireCurrentState) state; + AcquireLeaseInfo acquire = factory.createAcquireLeaseInfo(); + + acquire.setExpiration(acquireState.getExpiration()); + acquire.setIncarnation(acquireState.getIncarnation()); + + switch (acquireState.getStatus()) { + case BUSY: + acquire.setStatus(CurrentStatusEnum.BUSY); + break; + case RECYCLE: + acquire.setStatus(CurrentStatusEnum.RECYCLE); + break; + case STARTED: + acquire.setStatus(CurrentStatusEnum.STARTED); + break; + case STOPPED: + acquire.setStatus(CurrentStatusEnum.STOPPED); + break; + default: + throw new IllegalArgumentException(); + } + + leaseInfo.setAcquire(acquire); + } else if (state instanceof ReleaseCurrentState) { + leaseInfo.setRelease(factory.createStatusLeaseInfoRelease()); + } + + info.setStatusLease(leaseInfo); + + marshaller.marshal(factory.createCurrentState(info), stream); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + } +} diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializer.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializer.java new file mode 100644 index 0000000000000..50c5099271eb4 --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializer.java @@ -0,0 +1,55 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import java.io.StringReader; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.xml.sax.InputSource; + +/** + * + */ +class XmlGoalStateDeserializer { + public XmlGoalStateDeserializer() { + } + + public GoalState deserialize(String document) { + try { + JAXBContext context = JAXBContext.newInstance(GoalStateInfo.class + .getPackage().getName()); + Unmarshaller unmarshaller = context.createUnmarshaller(); + InputSource source = new InputSource(new StringReader(document)); + + @SuppressWarnings("unchecked") + GoalStateInfo goalStateInfo = ((JAXBElement<GoalStateInfo>) unmarshaller + .unmarshal(source)).getValue(); + + return new GoalState(goalStateInfo.getIncarnation(), + Enum.valueOf(ExpectedState.class, + goalStateInfo.getExpectedState().toString()), + goalStateInfo.getRoleEnvironmentPath(), + goalStateInfo.getDeadline(), + goalStateInfo.getCurrentStateEndpoint()); + + } catch (JAXBException e) { + throw new RuntimeException(e); + } + } +} diff --git a/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java new file mode 100644 index 0000000000000..bd579902be52a --- /dev/null +++ b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/XmlRoleEnvironmentDataDeserializer.java @@ -0,0 +1,183 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +/** + * + */ +class XmlRoleEnvironmentDataDeserializer implements + RoleEnvironmentDataDeserializer { + public XmlRoleEnvironmentDataDeserializer() { + } + + @Override + public RoleEnvironmentData deserialize(InputStream stream) { + try { + JAXBContext context = JAXBContext + .newInstance(RoleEnvironmentInfo.class.getPackage() + .getName()); + Unmarshaller unmarshaller = context.createUnmarshaller(); + + @SuppressWarnings("unchecked") + RoleEnvironmentInfo environmentInfo = ((JAXBElement<RoleEnvironmentInfo>) unmarshaller + .unmarshal(stream)).getValue(); + + Map<String, String> configurationSettings = translateConfigurationSettings(environmentInfo); + Map<String, LocalResource> localResources = translateLocalResources(environmentInfo); + RoleInstance currentInstance = translateCurrentInstance(environmentInfo); + Map<String, Role> roles = translateRoles(environmentInfo, + currentInstance, environmentInfo.getCurrentInstance() + .getRoleName()); + + return new RoleEnvironmentData(environmentInfo.getDeployment() + .getId(), configurationSettings, localResources, + currentInstance, roles, environmentInfo.getDeployment() + .isEmulated()); + } catch (JAXBException e) { + throw new RuntimeException(e); + } + } + + private Map<String, String> translateConfigurationSettings( + RoleEnvironmentInfo environmentInfo) { + Map<String, String> configurationSettings = new HashMap<String, String>(); + + for (ConfigurationSettingInfo settingInfo : environmentInfo + .getCurrentInstance().getConfigurationSettings() + .getConfigurationSetting()) { + configurationSettings.put(settingInfo.getName(), + settingInfo.getValue()); + } + + return configurationSettings; + } + + private Map<String, LocalResource> translateLocalResources( + RoleEnvironmentInfo environmentInfo) { + Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); + + for (LocalResourceInfo resourceInfo : environmentInfo + .getCurrentInstance().getLocalResources().getLocalResource()) { + localResources.put(resourceInfo.getName(), new LocalResource( + resourceInfo.getSizeInMB(), resourceInfo.getName(), + resourceInfo.getPath())); + } + + return localResources; + } + + private Map<String, Role> translateRoles( + RoleEnvironmentInfo environmentInfo, RoleInstance currentInstance, + String currentRole) { + Map<String, Role> roles = new HashMap<String, Role>(); + + for (RoleInfo roleInfo : environmentInfo.getRoles().getRole()) { + Map<String, RoleInstance> instances = translateRoleInstances(roleInfo + .getInstances()); + + if (roleInfo.getName().equals(currentRole)) { + instances.put(currentInstance.getId(), currentInstance); + } + + Role role = new Role(roleInfo.getName(), instances); + + for (RoleInstance instance : role.getInstances().values()) { + instance.setRole(role); + } + + roles.put(roleInfo.getName(), role); + } + + if (!roles.containsKey(currentRole)) { + Map<String, RoleInstance> instances = new HashMap<String, RoleInstance>(); + + instances.put(currentInstance.getId(), currentInstance); + + Role singleRole = new Role(currentRole, instances); + + currentInstance.setRole(singleRole); + + roles.put(currentRole, singleRole); + } + + return roles; + } + + private Map<String, RoleInstance> translateRoleInstances( + RoleInstancesInfo instancesInfo) { + Map<String, RoleInstance> roleInstances = new HashMap<String, RoleInstance>(); + + for (RoleInstanceInfo instanceInfo : instancesInfo.getInstance()) { + RoleInstance instance = new RoleInstance(instanceInfo.getId(), + instanceInfo.getFaultDomain(), + instanceInfo.getUpdateDomain(), + translateRoleInstanceEndpoints(instanceInfo.getEndpoints())); + + for (RoleInstanceEndpoint endpoint : instance + .getInstanceEndpoints().values()) { + endpoint.setRoleInstance(instance); + } + + roleInstances.put(instance.getId(), instance); + } + + return roleInstances; + } + + private Map<String, RoleInstanceEndpoint> translateRoleInstanceEndpoints( + EndpointsInfo endpointsInfo) { + Map<String, RoleInstanceEndpoint> endpoints = new HashMap<String, RoleInstanceEndpoint>(); + + for (EndpointInfo endpointInfo : endpointsInfo.getEndpoint()) { + RoleInstanceEndpoint endpoint = new RoleInstanceEndpoint( + endpointInfo.getProtocol().toString(), + new InetSocketAddress(endpointInfo.getAddress(), + endpointInfo.getPort())); + + endpoints.put(endpointInfo.getName(), endpoint); + } + + return endpoints; + } + + private RoleInstance translateCurrentInstance( + RoleEnvironmentInfo environmentInfo) { + CurrentRoleInstanceInfo currentInstanceInfo = environmentInfo + .getCurrentInstance(); + RoleInstance currentInstance = new RoleInstance( + currentInstanceInfo.getId(), + currentInstanceInfo.getFaultDomain(), + currentInstanceInfo.getUpdateDomain(), + translateRoleInstanceEndpoints(environmentInfo + .getCurrentInstance().getEndpoints())); + + for (RoleInstanceEndpoint endpoint : currentInstance + .getInstanceEndpoints().values()) { + endpoint.setRoleInstance(currentInstance); + } + + return currentInstance; + } +} diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/overview.html b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/overview.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/overview.html rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/overview.html diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/package.html b/serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/package.html similarity index 100% rename from microsoft-azure-api/src/main/java/com/microsoft/windowsazure/serviceruntime/package.html rename to serviceRuntime/src/main/java/com/microsoft/windowsazure/serviceruntime/package.html diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java new file mode 100644 index 0000000000000..c449c0178fe74 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/AlterClassWithProperties.java @@ -0,0 +1,31 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +import java.util.Map; + +import com.microsoft.windowsazure.core.Builder; + +public class AlterClassWithProperties implements + Builder.Alteration<ClassWithProperties> { + @Override + public ClassWithProperties alter(String profile, + ClassWithProperties instance, Builder builder, + Map<String, Object> properties) { + instance.setFoo(instance.getFoo() + " - changed"); + return instance; + } + +} diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorMultipleInject.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorMultipleInject.java new file mode 100644 index 0000000000000..9ba40b3f15043 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorMultipleInject.java @@ -0,0 +1,27 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +import javax.inject.Inject; + +public class ClassWithMultipleCtorMultipleInject { + @Inject + public ClassWithMultipleCtorMultipleInject() { + } + + @Inject + public ClassWithMultipleCtorMultipleInject(String x) { + } +} diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorNoInject.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorNoInject.java new file mode 100644 index 0000000000000..e0568c1a118ae --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithMultipleCtorNoInject.java @@ -0,0 +1,23 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +public class ClassWithMultipleCtorNoInject { + public ClassWithMultipleCtorNoInject() { + } + + public ClassWithMultipleCtorNoInject(String x) { + } +} diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithNamedParameter.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithNamedParameter.java new file mode 100644 index 0000000000000..329ef2977c421 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithNamedParameter.java @@ -0,0 +1,35 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +import javax.inject.Inject; +import javax.inject.Named; + +public class ClassWithNamedParameter { + private String hello; + + @Inject + public ClassWithNamedParameter(@Named("Foo") String hello) { + this.hello = hello; + } + + public String getHello() { + return hello; + } + + public void setHello(String hello) { + this.hello = hello; + } +} diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithProperties.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithProperties.java new file mode 100644 index 0000000000000..acb256a9aa9ba --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithProperties.java @@ -0,0 +1,55 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +public class ClassWithProperties { + String foo; + String bar; + + public ClassWithProperties() { + foo = "one"; + bar = "two"; + } + + /** + * @return the foo + */ + public String getFoo() { + return foo; + } + + /** + * @param foo + * the foo to set + */ + public void setFoo(String foo) { + this.foo = foo; + } + + /** + * @return the bar + */ + public String getBar() { + return bar; + } + + /** + * @param bar + * the bar to set + */ + public void setBar(String bar) { + this.bar = bar; + } +} diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithSingleCtorNoInject.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithSingleCtorNoInject.java new file mode 100644 index 0000000000000..82dc255982b55 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/ClassWithSingleCtorNoInject.java @@ -0,0 +1,21 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +public class ClassWithSingleCtorNoInject { + public ClassWithSingleCtorNoInject() { + + } +} diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java new file mode 100644 index 0000000000000..a2834ea1c52f7 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/configuration/builder/DefaultBuilderTest.java @@ -0,0 +1,203 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.configuration.builder; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import com.microsoft.windowsazure.core.DefaultBuilder; + +public class DefaultBuilderTest { + + Map<String, Object> properties; + DefaultBuilder builder; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Before + public void init() { + properties = new HashMap<String, Object>(); + builder = new DefaultBuilder(); + } + + @Test + public void namedAnnotationsComeFromBuildProperties() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + + // Act + Map<String, Object> properties = new HashMap<String, Object>(); + properties.put("Foo", "world"); + ClassWithNamedParameter cwnp = builder.build("", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("world", cwnp.getHello()); + } + + @Test + public void namedAnnotationReportsMissingProperty() throws Exception { + // Arrange + thrown.expect(RuntimeException.class); + + builder.add(ClassWithNamedParameter.class); + + // Act + ClassWithNamedParameter cwnp = builder.build("", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("world", cwnp.getHello()); + } + + @Test + public void singleCtorWithNoInjectShouldBeUsed() throws Exception { + // Arrange + builder.add(ClassWithSingleCtorNoInject.class); + + // Act + ClassWithSingleCtorNoInject result = builder.build("", + ClassWithSingleCtorNoInject.class, + ClassWithSingleCtorNoInject.class, properties); + + // Assert + Assert.assertNotNull(result); + } + + @Test + public void multipleCtorWithNoInjectShouldFail() throws Exception { + // Arrange + thrown.expect(RuntimeException.class); + + builder.add(ClassWithMultipleCtorNoInject.class); + + // Act + ClassWithMultipleCtorNoInject result = builder.build("", + ClassWithMultipleCtorNoInject.class, + ClassWithMultipleCtorNoInject.class, properties); + + // Assert + Assert.assertTrue("Exception must occur", false); + Assert.assertNull("Result should be null", result); + } + + @Test + public void multipleCtorWithMultipleInjectShouldFail() throws Exception { + // Arrange + thrown.expect(RuntimeException.class); + + builder.add(ClassWithMultipleCtorMultipleInject.class); + + // Act + ClassWithMultipleCtorMultipleInject result = builder.build("", + ClassWithMultipleCtorMultipleInject.class, + ClassWithMultipleCtorMultipleInject.class, properties); + + // Assert + Assert.assertTrue("Exception must occur", false); + Assert.assertNull("Result should be null", result); + } + + @Test + public void alterationExecutesWhenInstanceCreated() throws Exception { + // Arrange + builder.add(ClassWithProperties.class); + builder.alter(ClassWithProperties.class, ClassWithProperties.class, + new AlterClassWithProperties()); + + // Act + ClassWithProperties result = builder.build("", + ClassWithProperties.class, ClassWithProperties.class, + properties); + + // Assert + Assert.assertEquals("one - changed", result.getFoo()); + } + + @Test + public void namedParametersUseProfileBasedKeysFirst() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + properties.put("Foo", "fallback"); + properties.put("testing.Foo", "Profile foo value"); + + // Act + ClassWithNamedParameter result = builder.build("testing", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("Profile foo value", result.getHello()); + } + + @Test + public void namedParametersFallBackToNonProfileBasedKeys() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + properties.put("Foo", "fallback"); + properties.put("testing.Foo", "Profile foo value"); + + // Act + ClassWithNamedParameter result1 = builder.build("", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result2 = builder.build("production", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result3 = builder.build("testing.custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("fallback", result1.getHello()); + Assert.assertEquals("fallback", result2.getHello()); + Assert.assertEquals("fallback", result3.getHello()); + } + + @Test + public void namedParamatersFallBackFromLeftToRight() throws Exception { + // Arrange + builder.add(ClassWithNamedParameter.class); + properties.put("Foo", "fallback"); + properties.put("custom.Foo", "custom.Foo value"); + properties.put("testing.custom.Foo", "testing.custom.Foo value"); + + // Act + ClassWithNamedParameter result1 = builder.build("custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result2 = builder.build("production.custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + ClassWithNamedParameter result3 = builder.build("testing.custom", + ClassWithNamedParameter.class, ClassWithNamedParameter.class, + properties); + + // Assert + Assert.assertEquals("custom.Foo value", result1.getHello()); + Assert.assertEquals("custom.Foo value", result2.getHello()); + Assert.assertEquals("testing.custom.Foo value", result3.getHello()); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/FileInputChannelTests.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/FileInputChannelTests.java similarity index 86% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/FileInputChannelTests.java rename to serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/FileInputChannelTests.java index 25f95aa4759fa..f506c302cc30f 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/FileInputChannelTests.java +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/FileInputChannelTests.java @@ -34,19 +34,19 @@ public void getInputStreamOpensFile() { InputChannel inputChannel = new FileInputChannel(); try { - File tempFile = File.createTempFile("getInputStreamOpensFile", null); + File tempFile = File + .createTempFile("getInputStreamOpensFile", null); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); String expectedData = "test content"; writer.write(expectedData); writer.close(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputChannel.getInputStream(tempFile - .getAbsolutePath()))); + BufferedReader reader = new BufferedReader(new InputStreamReader( + inputChannel.getInputStream(tempFile.getAbsolutePath()))); assertThat(reader.readLine(), equalTo(expectedData)); - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/MockInputChannel.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/MockInputChannel.java similarity index 93% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/MockInputChannel.java rename to serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/MockInputChannel.java index 2cf8df32691ff..884accdf41418 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/MockInputChannel.java +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/MockInputChannel.java @@ -30,8 +30,7 @@ public MockInputChannel(String channelData) { try { data = channelData.getBytes("UTF-8"); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { e.printStackTrace(); } @@ -45,7 +44,8 @@ public MockInputChannel(String chunks[]) { for (String chunk : chunks) { try { - byte chunkLengthData[] = Integer.toHexString(chunk.length()).getBytes("US-ASCII"); + byte chunkLengthData[] = Integer.toHexString(chunk.length()) + .getBytes("US-ASCII"); byte chunkData[] = chunk.getBytes("UTF-8"); int chunkLength = chunkLengthData.length + chunkData.length + 4; @@ -53,8 +53,7 @@ public MockInputChannel(String chunks[]) { chunkBytes.add(chunkData); finalLength += chunkLength; - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClientTests.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClientTests.java similarity index 91% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClientTests.java rename to serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClientTests.java index 27979f239fc3b..2a5d63bafd0bc 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClientTests.java +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeCurrentStateClientTests.java @@ -29,7 +29,8 @@ public class Protocol1RuntimeCurrentStateClientTests { @Test public void setCurrentStateSerializesToEndpoint() { - final CurrentState expectedState = new AcquireCurrentState(null, null, null, null); + final CurrentState expectedState = new AcquireCurrentState(null, null, + null, null); final OutputStream expectedStream = new ByteArrayOutputStream(); final String expectedEndpoint = "endpoint"; final AtomicBoolean serializeCalled = new AtomicBoolean(false); @@ -53,8 +54,8 @@ public OutputStream getOutputStream(String name) { } }; - Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(serializer, - outputChannel); + Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient( + serializer, outputChannel); currentStateClient.setEndpoint(expectedEndpoint); @@ -65,7 +66,8 @@ public OutputStream getOutputStream(String name) { @Test public void streamCloseFailureThrowsNotAvailableException() { - final CurrentState expectedState = new AcquireCurrentState(null, null, null, null); + final CurrentState expectedState = new AcquireCurrentState(null, null, + null, null); final OutputStream expectedStream = new OutputStream() { @Override public void write(int arg0) throws IOException { @@ -99,15 +101,14 @@ public OutputStream getOutputStream(String name) { } }; - Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient(serializer, - outputChannel); + Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient( + serializer, outputChannel); currentStateClient.setEndpoint(expectedEndpoint); try { currentStateClient.setCurrentState(expectedState); - } - catch (RoleEnvironmentNotAvailableException e) { + } catch (RoleEnvironmentNotAvailableException e) { return; } diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java new file mode 100644 index 0000000000000..f52d014883502 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/Protocol1RuntimeGoalStateClientTests.java @@ -0,0 +1,274 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.io.InputStream; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Test; + +/** + * + */ +public class Protocol1RuntimeGoalStateClientTests { + private final List<GoalState> goalStates = new LinkedList<GoalState>(); + + @Test + public void addGoalStateChangedListenerAddsListener() { + Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient( + null, null); + + GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); + + RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { + @Override + public RoleEnvironmentData deserialize(InputStream stream) { + return null; + } + }; + + InputChannel inputChannel = new MockInputChannel( + new String[] { + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>1</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>", + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>2</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>" }); + + Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient( + currentStateClient, goalStateDeserializer, + roleEnvironmentDeserializer, inputChannel); + + client.addGoalStateChangedListener(new GoalStateChangedListener() { + @Override + public void goalStateChanged(GoalState newGoalState) { + goalStates.add(newGoalState); + } + }); + + goalStates.clear(); + + try { + client.getCurrentGoalState(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + assertThat(goalStates.size(), is(1)); + assertThat(goalStates.get(0).getIncarnation().intValue(), is(2)); + } + + @Test + public void goalStateClientRestartsThread() { + Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient( + null, null); + + GoalStateDeserializer goalStateDeserializer = new GoalStateDeserializer() { + private final ChunkedGoalStateDeserializer deserializer = new ChunkedGoalStateDeserializer(); + + @Override + public void initialize(InputStream inputStream) { + deserializer.initialize(inputStream); + } + + @Override + public GoalState deserialize() { + GoalState goalState = deserializer.deserialize(); + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + goalStates.add(goalState); + + return goalState; + } + }; + + RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { + @Override + public RoleEnvironmentData deserialize(InputStream stream) { + return null; + } + }; + + InputChannel inputChannel = new MockInputChannel( + new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>1</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>" }); + + Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient( + currentStateClient, goalStateDeserializer, + roleEnvironmentDeserializer, inputChannel); + + goalStates.clear(); + + try { + client.getCurrentGoalState(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + try { + client.getCurrentGoalState(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + assertThat(goalStates.size(), is(3)); + } + + @Test + public void getRoleEnvironmentDataReturnsDeserializedData() { + Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient( + null, null); + + GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); + + final RoleEnvironmentData data = new RoleEnvironmentData(null, null, + null, null, null, false); + + RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { + @Override + public RoleEnvironmentData deserialize(InputStream stream) { + return data; + } + }; + + InputChannel inputChannel = new MockInputChannel( + new String[] { "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>1</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>" }); + + Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient( + currentStateClient, goalStateDeserializer, + roleEnvironmentDeserializer, inputChannel); + + try { + assertThat(client.getRoleEnvironmentData(), is(data)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Test + public void removeGoalStateChangedListenerRemovesListener() { + Protocol1RuntimeCurrentStateClient currentStateClient = new Protocol1RuntimeCurrentStateClient( + null, null); + + GoalStateDeserializer goalStateDeserializer = new ChunkedGoalStateDeserializer(); + + RoleEnvironmentDataDeserializer roleEnvironmentDeserializer = new RoleEnvironmentDataDeserializer() { + @Override + public RoleEnvironmentData deserialize(InputStream stream) { + return null; + } + }; + + InputChannel inputChannel = new MockInputChannel( + new String[] { + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>1</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>", + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>2</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>" }); + + Protocol1RuntimeGoalStateClient client = new Protocol1RuntimeGoalStateClient( + currentStateClient, goalStateDeserializer, + roleEnvironmentDeserializer, inputChannel); + + GoalStateChangedListener listener = new GoalStateChangedListener() { + @Override + public void goalStateChanged(GoalState newGoalState) { + goalStates.add(newGoalState); + } + }; + + client.addGoalStateChangedListener(listener); + client.removeGoalStateChangedListener(listener); + + goalStates.clear(); + + try { + client.getCurrentGoalState(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + assertThat(goalStates.size(), is(0)); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTests.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTests.java similarity index 80% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTests.java rename to serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTests.java index 5e34f5d49e85c..7b571a2a0a269 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTests.java +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/RoleEnvironmentTests.java @@ -35,12 +35,12 @@ public void setupTests() { horrificEnvironmentModification("\\\\.\\pipe\\578cb0d1-a330-4019-b634-755aa3d1e9d2"); } - //@Test + // @Test public void roleEnvironmentIsAvailable() { assertThat(RoleEnvironment.isAvailable(), is(true)); } - //@Test + // @Test public void roleEnvironmentSetStateSetsState() { Calendar exp = Calendar.getInstance(TimeZone.getTimeZone("GMT+0:00")); @@ -52,26 +52,23 @@ public void roleEnvironmentSetStateSetsState() { @SuppressWarnings({ "unchecked", "rawtypes" }) public void horrificEnvironmentModification(String endpoint) { try { - Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); - Field field = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); + Class processEnvironmentClass = Class + .forName("java.lang.ProcessEnvironment"); + Field field = processEnvironmentClass + .getDeclaredField("theCaseInsensitiveEnvironment"); field.setAccessible(true); Object obj = field.get(null); Map<String, String> map = (Map<String, String>) obj; map.put("WaRuntimeEndpoint", endpoint); - } - catch (SecurityException e) { + } catch (SecurityException e) { e.printStackTrace(); - } - catch (NoSuchFieldException e) { + } catch (NoSuchFieldException e) { e.printStackTrace(); - } - catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { e.printStackTrace(); - } - catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { e.printStackTrace(); - } - catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { e.printStackTrace(); } } diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManagerTests.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManagerTests.java new file mode 100644 index 0000000000000..b8bfdf882d667 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/RuntimeVersionManagerTests.java @@ -0,0 +1,127 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.serviceruntime; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.hamcrest.Matchers.*; + +/** + * + */ +public class RuntimeVersionManagerTests { + @Test + public void getRuntimeClientForV1CanParseGoalState() { + RuntimeVersionManager manager = createVersionManagerWithGoalState( + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>1</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>", "2011-03-08"); + + RuntimeClient runtimeClient = manager.getRuntimeClient(""); + GoalState goalState = null; + + try { + goalState = runtimeClient.getCurrentGoalState(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + Calendar expectedDeadline = GregorianCalendar.getInstance(TimeZone + .getTimeZone("GMT+00:00")); + + expectedDeadline.clear(); + expectedDeadline.set(2011, 2, 8, 3, 27, 44); + + assertThat(goalState.getIncarnation(), equalTo(BigInteger.ONE)); + assertThat(goalState.getExpectedState(), equalTo(ExpectedState.STARTED)); + assertThat(goalState.getEnvironmentPath(), equalTo("envpath")); + assertThat(goalState.getCurrentStateEndpoint(), equalTo("statepath")); + assertThat(goalState.getDeadline().getTimeInMillis(), + equalTo(expectedDeadline.getTimeInMillis())); + } + + @Test + public void getRuntimeClientThrowsWhenNoSupportedVersionsFound() { + RuntimeVersionManager manager = createVersionManagerWithGoalState( + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + + "<GoalState>" + + "<Incarnation>1</Incarnation>" + + "<ExpectedState>Started</ExpectedState>" + + "<RoleEnvironmentPath>envpath</RoleEnvironmentPath>" + + "<CurrentStateEndpoint>statepath</CurrentStateEndpoint>" + + "<Deadline>2011-03-08T03:27:44.0Z</Deadline>" + + "</GoalState>", "notSupported"); + + try { + manager.getRuntimeClient(""); + } catch (RuntimeException ex) { + return; + } + + fail(); + } + + private RuntimeVersionManager createVersionManagerWithGoalState( + String goalStateXml, String version) { + File tempGoalState; + + try { + tempGoalState = File.createTempFile("tempGoalState", null); + FileOutputStream output = new FileOutputStream(tempGoalState); + + InputChannel goalStateChannel = new MockInputChannel( + new String[] { goalStateXml }); + BufferedInputStream input = new BufferedInputStream( + goalStateChannel.getInputStream("")); + + byte buffer[] = new byte[1024]; + int length = 0; + + while ((length = input.read(buffer)) > 0) { + output.write(buffer, 0, length); + } + + input.close(); + output.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + + InputChannel inputChannel = new MockInputChannel( + "<?xml version=\"1.0\"?>" + "<RuntimeServerDiscovery>" + + "<RuntimeServerEndpoints>" + + "<RuntimeServerEndpoint version=\"" + version + + "\" path=\"" + tempGoalState.getAbsolutePath() + + "\" />" + "</RuntimeServerEndpoints>" + + "</RuntimeServerDiscovery>"); + RuntimeVersionProtocolClient protocolClient = new RuntimeVersionProtocolClient( + inputChannel); + return new RuntimeVersionManager(protocolClient); + } +} diff --git a/microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializerTests.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializerTests.java similarity index 100% rename from microsoft-azure-api/src/test/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializerTests.java rename to serviceRuntime/src/test/java/com/microsoft/windowsazure/serviceruntime/XmlGoalStateDeserializerTests.java diff --git a/serviceRuntime/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java b/serviceRuntime/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java new file mode 100644 index 0000000000000..bc45bc68ef0f4 --- /dev/null +++ b/serviceRuntime/src/test/java/com/microsoft/windowsazure/utils/ServiceExceptionFactoryTest.java @@ -0,0 +1,105 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.utils; + +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; +import java.net.SocketTimeoutException; + +import org.junit.Test; + +import com.microsoft.windowsazure.core.ServiceTimeoutException; +import com.microsoft.windowsazure.exception.ServiceException; +import com.microsoft.windowsazure.exception.ServiceExceptionFactory; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class ServiceExceptionFactoryTest { + @Test + public void serviceNameAndMessageAndCauseAppearInException() { + // Arrange + ClientResponse response = new ClientResponse(404, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException cause = new UniformInterfaceException( + response); + + // Act + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException("this is a test", cause)); + + // Assert + assertNotNull(exception); + assertEquals("testing", exception.getServiceName()); + assertEquals("this is a test", exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void httpStatusCodeAndReasonPhraseAppearInException() { + // Arrange + ClientResponse response = new ClientResponse(404, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException cause = new UniformInterfaceException( + response); + + // Act + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException("this is a test", cause)); + + // Assert + assertNotNull(exception); + assertEquals(404, exception.getHttpStatusCode()); + assertEquals("Not Found", exception.getHttpReasonPhrase()); + } + + @Test + public void informationWillPassUpIfServiceExceptionIsRootCauseOfClientHandlerExceptions() { + // Arrange + ClientResponse response = new ClientResponse(503, null, + new ByteArrayInputStream(new byte[0]), null); + UniformInterfaceException rootCause = new UniformInterfaceException( + response); + ServiceException originalDescription = ServiceExceptionFactory.process( + "underlying", new ServiceException(rootCause)); + ClientHandlerException wrappingException = new ClientHandlerException( + originalDescription); + + // Act + ServiceException exception = ServiceExceptionFactory.process("actual", + new ServiceException(wrappingException)); + + // Assert + assertEquals(503, exception.getHttpStatusCode()); + assertEquals("underlying", exception.getServiceName()); + } + + @Test + public void socketTimeoutWillPassUpIfInsideClientHandlerException() { + String expectedMessage = "connect timeout"; + SocketTimeoutException rootCause = new SocketTimeoutException( + expectedMessage); + ClientHandlerException wrappingException = new ClientHandlerException( + rootCause); + + ServiceException exception = ServiceExceptionFactory.process("testing", + new ServiceException(wrappingException)); + + assertSame(ServiceTimeoutException.class, exception.getClass()); + assertEquals(expectedMessage, exception.getMessage()); + assertEquals("testing", exception.getServiceName()); + } +} diff --git a/serviceRuntime/src/test/resources/NewFile.xml b/serviceRuntime/src/test/resources/NewFile.xml new file mode 100644 index 0000000000000..5ebbe31bdafda --- /dev/null +++ b/serviceRuntime/src/test/resources/NewFile.xml @@ -0,0 +1,4 @@ +<entry xmlns="http://www.w3.org/2005/Atom"> +<content type="application/xml"> +<ns2:QueueDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"> +</ns2:QueueDescription></content></entry> diff --git a/serviceRuntime/src/test/resources/certificate/server.crt b/serviceRuntime/src/test/resources/certificate/server.crt new file mode 100644 index 0000000000000..45100ad45f501 --- /dev/null +++ b/serviceRuntime/src/test/resources/certificate/server.crt @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICqTCCAhICCQDm00hjjGf/ITANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdSZWRtb25kMRMwEQYDVQQKEwpNaWNy +b3NvZnQgMRYwFAYDVQQLEw1XaW5kb3dzIEF6dXJlMRUwEwYDVQQDEwxBbGJlcnQg +Q2hlbmcxJTAjBgkqhkiG9w0BCQEWFmdvbmdjaGVuQG1pY3Jvc29mdC5jb20wIBcN +MTMwMzA2MDAxNzU2WhgPMTkyMzA5MTIyMDMxNDhaMIGXMQswCQYDVQQGEwJVUzEL +MAkGA1UECBMCV0ExEDAOBgNVBAcTB1JlZG1vbmQxEzARBgNVBAoTCk1pY3Jvc29m +dCAxFjAUBgNVBAsTDVdpbmRvd3MgQXp1cmUxFTATBgNVBAMTDEFsYmVydCBDaGVu +ZzElMCMGCSqGSIb3DQEJARYWZ29uZ2NoZW5AbWljcm9zb2Z0LmNvbTCBnzANBgkq +hkiG9w0BAQEFAAOBjQAwgYkCgYEAxct8f2TOECFGtZs5zJN9Vmtk6Jeo2ThbJ8XO +0GPgjKjfLGUgUHrUKSpaHrObaEQWtU9/qdCmctHep5veulGApZ6cBKjL+7xKGQfP +KHq+6nsvF2EutZenPvsFDb7msezcT+Ut1yMnCUd9sjcD0/g2AO5CpplnUR7MOIaq +j/ifsNMCAwEAATANBgkqhkiG9w0BAQUFAAOBgQCAY9QBsXtEfDTZ6Gmplkd2mGGf +aFxRXtEtEXxBrEjhq3c2F8le1ZpMysWfmgpsImZODf3rPN5+UMmL2cqxF0RU+7kG +qPSo8egxg33IfEMTeH5WYHr8ilOxBfw25nnUGr7Cym0m0JAmh5xR47vmEb/EHIXf +iFKpK6o4bjjnszUV2g== +-----END CERTIFICATE----- diff --git a/serviceRuntime/src/test/resources/certificate/server.der b/serviceRuntime/src/test/resources/certificate/server.der new file mode 100644 index 0000000000000..e34ad905b9f15 Binary files /dev/null and b/serviceRuntime/src/test/resources/certificate/server.der differ diff --git a/serviceRuntime/src/test/resources/media/MPEG4-H264.mp4 b/serviceRuntime/src/test/resources/media/MPEG4-H264.mp4 new file mode 100644 index 0000000000000..54c15e4ec7532 Binary files /dev/null and b/serviceRuntime/src/test/resources/media/MPEG4-H264.mp4 differ diff --git a/tasks/.gitignore b/tasks/.gitignore new file mode 100644 index 0000000000000..7370c55e27ae9 --- /dev/null +++ b/tasks/.gitignore @@ -0,0 +1,3 @@ +packages +restore.config +nuget.exe diff --git a/tasks/generate.groovy b/tasks/generate.groovy new file mode 100644 index 0000000000000..d2a80f992b601 --- /dev/null +++ b/tasks/generate.groovy @@ -0,0 +1,164 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// +// List of spec DLLs and generation detail +// Add to this list to add new specs +// +def hydraSpecs = [ + [ + specificationDllFileName: "Microsoft.WindowsAzure.Management.Compute.Specification.dll", + clientType: "Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient", + generatedCodeDestinationRootDirectoryName: "management-compute" + ], + [ + specificationDllFileName: "Microsoft.WindowsAzure.Management.Specification.dll", + clientType: 'Microsoft.WindowsAzure.Management.ManagementClient', + generatedCodeDestinationRootDirectoryName: 'management' + ], + [ + specificationDllFileName: "Microsoft.WindowsAzure.Management.Network.Specification.dll", + clientType: "Microsoft.WindowsAzure.Management.Network.NetworkManagementClient", + generatedCodeDestinationRootDirectoryName: 'management-network' + ], + [ + specificationDllFileName: "Microsoft.WindowsAzure.Management.Sql.Specification.dll", + clientType: "Microsoft.WindowsAzure.Management.Sql.SqlManagementClient", + generatedCodeDestinationRootDirectoryName: "management-sql" + ], + [ + specificationDllFileName: "Microsoft.WindowsAzure.Management.Storage.Specification.dll", + clientType: "Microsoft.WindowsAzure.Management.Storage.StorageManagementClient", + generatedCodeDestinationRootDirectoryName: "management-storage" + ], + [ + specificationDllFileName: "Microsoft.WindowsAzure.Management.WebSites.Specification.dll", + clientType: "Microsoft.WindowsAzure.Management.WebSites.WebSiteManagementClient", + generatedCodeDestinationRootDirectoryName: "management-websites" + ] +] + +////////////////////////////////////////////////////////////////////// +// +// Implementation below here + +// Check for required environment variables +def ensureEnvironment() +{ + def env = System.getenv() + def notSet = [] + + ['PRIVATE_FEED_USER_NAME', 'PRIVATE_FEED_PASSWORD', 'PRIVATE_FEED_URL'].each { + if (!env.containsKey(it)) { notSet.add(it) } + } + + if (notSet) { + throw new Exception("Required environment variables not set: ${notSet}") + } +} + +// Download a file from a url +def download(address) +{ + def file = new FileOutputStream(address.tokenize("/")[-1]) + def out = new BufferedOutputStream(file) + out << new URL(address).openStream() + out.close() +} + +// Calculates if a CLR exe should run directly or via mono +def exePrefix() { + def isWindows = System.properties['os.name'].toLowerCase().contains('windows') + if (isWindows) { + return [] + } + ["mono", '--runtime=v4.0.30319'] +} + +// Run an executable with the given command line arguments +def run(String exePath, String... args) +{ + def commands = [exePrefix(), exePath, args].flatten() + commands.execute() +} + +// Execute nuget.exe with the given command line arguments +def nuget(String... args) { run('./nuget.exe', args) } + +// Execute hydra.exe with the given command line arguments +def hydra(String hydraExePath, String... args) +{ + def commands = [exePrefix(), hydraExePath, args].flatten() + commands.execute() +} + +// Generate code for the given specInfo +def generate(hydraExePath, specInfo) +{ + def specDLL = findFileInPackagesDirectory(specInfo.specificationDllFileName) + hydra(hydraExePath, '-f', 'java', '-s', 'namespace', + '-c', specInfo.clientType, + '-d', "../${specInfo.generatedCodeDestinationRootDirectoryName}/src/main/java/com", + specDLL) +} + +// Run nuget.exe to restore required nuget packages +def restorePackages() +{ + def env = System.getenv() + try { + nuget('sources', 'add', + '-name', 'download', + '-source', env['PRIVATE_FEED_URL'], + '-configfile', './restore.config') + nuget('sources', 'update', + '-name', 'download', + '-username', env['PRIVATE_FEED_USER_NAME'], + '-password', env['PRIVATE_FEED_PASSWORD'], + '-configfile', './restore.config') + nuget('restore', 'packages.config', + '-packagesdirectory', './packages', + '-configfile', './restore.config') + } + finally { + // Need to wait a bit, config file stays open while nuget.exe shuts down + Thread.sleep(1000) + new File('./restore.config').delete() + } +} + +// Find a file with the given file name (case insensitive match) somewhere under packages +def findFileInPackagesDirectory(pattern) +{ + def path + new File('packages').traverse([nameFilter: ~"(?i)${pattern}\$"], { path = it.toString() }) + path + +} + +// +// Main logic here +// +ensureEnvironment() +download("http://www.nuget.org/nuget.exe") +restorePackages() +def hydraPath = findFileInPackagesDirectory('hydra.exe') +hydraSpecs.each { + System.out.println("generating code for ${it.specificationDllFileName}") + generate hydraPath, it +} diff --git a/tasks/packages.config b/tasks/packages.config new file mode 100644 index 0000000000000..cd88d5ed18ea9 --- /dev/null +++ b/tasks/packages.config @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Hydra.Generator" version="1.0.5217.25852-prerelease" targetFramework="portable-net45+sl50+wp80+win" /> + <package id="Microsoft.WindowsAzure.Management.Compute.Specification" version="1.0.5226.23603-prerelease" targetFramework="portable-net45+sl50+wp80+win" /> + <package id="Microsoft.WindowsAzure.Management.Specification" version="1.0.5226.28122-prerelease" targetFramework="portable-net45+sl50+wp80+win" /> + <package id="Microsoft.WindowsAzure.Management.Sql.Specification" version="1.0.5192.8225-prerelease" targetFramework="portable-net45+sl50+wp80+win" /> + <package id="Microsoft.WindowsAzure.Management.Storage.Specification" version="1.0.5192.8225-prerelease" targetFramework="portable-net45+sl50+wp80+win" /> + <package id="Microsoft.WindowsAzure.Management.WebSites.Specification" version="2.0.5226.28128-prerelease" targetFramework="portable-net45+sl50+wp80+win" /> + <package id="Microsoft.WindowsAzure.Management.Network.Specification" version="1.0.5226.28124-prerelease" targetFramework="portable-net45+sl50+wp80+win" /> +</packages> \ No newline at end of file diff --git a/tasks/runJDiff.cmd b/tasks/runJDiff.cmd new file mode 100644 index 0000000000000..f628ae15f9475 --- /dev/null +++ b/tasks/runJDiff.cmd @@ -0,0 +1,131 @@ +:: set global variables JDIFF, Branch location, etc +set JDIFF=[JDiff Path] +set OLDBRANCH=[Old branch path] +set NEWBRANCH=[New branch path] + +:: set API name +set OLDRUNTIMEAPI=microsoft-azure-runtime-api-old +set NEWRUNTIMEAPI=microsoft-azure-runtime-api-new +set OLDSERVICEBUSAPI=microsoft-azure-servicebus-api-old +set NEWSERVICEBUSAPI=microsoft-azure-servicebus-api-new +set OLDMEDIASERVICEAPI=microsoft-azure-media-api-old +set NEWMEDIASERVICEAPI=microsoft-azure-media-api-new +set OLDMANAGEMENTAPI=microsoft-azure-management-api-old +set NEWMANAGEMENTAPI=microsoft-azure-management-api-new +set OLDCOREAPI=microsoft-azure-core-api-old +set NEWCOREAPI=microsoft-azure-core-api-new +set NEWCOMPUTEMANAGEMENTAPI=microsoft-azure-management-compute-api-new +set NEWSQLMANAGEMENTAPI=microsoft-azure-management-sql-api-new +set NEWNETWORKMANAGEMENTAPI=microsoft-azure-management-network-api-new +set NEWSTORAGEMANAGEMENTAPI=microsoft-azure-management-storage-api-new +set NEWWEBSITEMANAGEMENTAPI=microsoft-azure-management-website-api-new + +:: set the paths +set OLDBRANCHPATH=%OLDBRANCH%\microsoft-azure-api\src\main\java +set NEWRUNTIMEPATH=%NEWBRANCH%\serviceruntime\src\main\java +set NEWSERVICEBUSPATH=%NEWBRANCH%\servicebus\src\main\java +set NEWMEDIASERVICEPATH=%NEWBRANCH%\media\src\main\java +set NEWMANAGEMENTPATH=%NEWBRANCH%\management\src\main\java +set NEWCOREPATH=%NEWBRANCH%\core\src\main\java +set NEWCOMPUTEMANAGEMENTPATH=%NEWBRANCH%\management-compute\src\main\java +set NEWNETWORKMANAGEMENTPATH=%NEWBRANCH%\management-network\src\main\java +set NEWSQLMANAGEMENTPATH=%NEWBRANCH%\management-sql\src\main\java +set NEWSTORAGEMANAGEMENTPATH=%NEWBRANCH%\management-storage\src\main\java +set NEWWEBSITEMANAGEMENTPATH=%NEWBRANCH%\management-website\src\main\java + +set OLDSERVICEBUSPATH=%OLDBRANCHPATH% + +:: set the namespace +set RUNTIMENAMESPACE=com.microsoft.windowsazure.serviceruntime +set OLDSERVICEBUSNAMESPACE=com.microsoft.windowsazure.services.serviceBus +set NEWSERVICEBUSNAMESPACE=com.microsoft.windowsazure.services.servicebus +set MEDIASERVICENAMESPACE=com.microsoft.windowsazure.services.media +set OLDMANAGEMENTNAMESPACE=com.microsoft.windowsazure.services.management +set NEWMANAGEMENTNAMESPACE=com.microsoft.windowsazure.management +set OLDCORENAMESPACE=com.microsoft.windowsazure.services.core +set NEWCORENAMESPACE=com.microsoft.windowsazure.core +set NEWCOMPUTEMANAGEMENTNAMESPACE=com.microsoft.windowsazure.management.compute +set NEWNETWORKMANAGEMENTNAMESPACE=com.microsoft.windowsazure.management.network +set NEWSQLMANAGEMENTNAMESPACE=com.microsoft.windowsazure.management.sql +set NEWSTORAGEMANAGEMENTNAMESPACE=com.microsoft.windowsazure.management.storage +set NEWWEBSITEMANAGEMENTNAMESPACE=com.microsoft.windowsazure.management.website com.microsoft.windowsazure.management.websites + +:: First, generate the javadoc for the old code. +:: Service Bus +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %OLDSERVICEBUSAPI% -sourcepath %OLDSERVICEBUSPATH% %OLDSERVICEBUSNAMESPACE% +:: Media Services +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %OLDMEDIASERVICEAPI% -sourcepath %OLDBRANCHPATH% %MEDIASERVICENAMESPACE% +:: Service Runtime +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %OLDRUNTIMEAPI% -sourcepath %OLDBRANCHPATH% %RUNTIMENAMESPACE% +:: Management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %OLDMANAGEMENTAPI% -sourcepath %OLDBRANCHPATH% %OLDMANAGEMENTNAMESPACE% +:: Core +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %OLDCOREAPI% -sourcepath %OLDBRANCHPATH% %OLDCORENAMESPACE% + +:: Second, generate the java doc for the new code. +:: Service Bus +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWSERVICEBUSAPI% -sourcepath %NEWSERVICEBUSPATH% %NEWSERVICEBUSNAMESPACE% +:: Media Services +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWMEDIASERVICEAPI% -sourcepath %NEWMEDIASERVICEPATH% %MEDIASERVICENAMESPACE% +:: Service Runtime +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWRUNTIMEAPI% -sourcepath %NEWRUNTIMEPATH% %RUNTIMENAMESPACE% +:: Management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWMANAGEMENTAPI% -sourcepath %NEWMANAGEMENTPATH% %NEWMANAGEMENTNAMESPACE% +:: Core +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWCOREAPI% -sourcepath %NEWCOREPATH% %NEWCORENAMESPACE% + +:: Compute Management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWCOMPUTEMANAGEMENTAPI% -sourcepath %NEWCOMPUTEMANAGEMENTPATH% %NEWCOMPUTEMANAGEMENTNAMESPACE% + +:: Network Management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWNETWORKMANAGEMENTAPI% -sourcepath %NEWNETWORKMANAGEMENTPATH% %NEWNETWORKMANAGEMENTNAMESPACE% + +:: SQL Management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWSQLMANAGEMENTAPI% -sourcepath %NEWSQLMANAGEMENTPATH% %NEWSQLMANAGEMENTNAMESPACE% + +:: Storage Management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWSTORAGEMANAGEMENTAPI% -sourcepath %NEWSTORAGEMANAGEMENTPATH% %NEWSTORAGEMANAGEMENTNAMESPACE% + +:: Website Management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -apiname %NEWWEBSITEMANAGEMENTAPI% -sourcepath %NEWWEBSITEMANAGEMENTPATH% %NEWWEBSITEMANAGEMENTNAMESPACE% + + +:: Third, create the sub directory +:: Service Runtime +set RUNTIMEOUTPUT=jdiff\serviceruntime +mkdir RUNTIMEOUTPUT +set RUNTIMEOUTPUTCHANGES=jdiff\serviceruntime\changes +mkdir RUNTIMEOUTPUTCHANGES +:: Service Bus +set SERVICEBUSOUTPUT=jdiff\servicebus +mkdir SERVICEBUSOUTPUT +set SERVICEBUSOUTPUTCHANGES=jdiff\servicebus\changes +mkdir SERVICEBUSOUTPUTCHANGES +:: Media Services +set MEDIASERVICEOUTPUT=jdiff\mediaservice +mkdir MEDIASERVICEOUTPUT +set MEDIASERVICEOUTPUTCHANGES=jdiff\mediaservice\changes +mkdir MEDIASERVICEOUTPUTCHANGES +:: Management +set MANAGEMENTOUTPUT=jdiff\management +mkdir MANAGEMENTOUTPUT +set MANAGEMENTOUTPUTCHANGES=jdiff\management\changes +mkdir MANAGEMENTOUTPUTCHANGES +:: Core +set COREOUTPUT=jdiff\core +mkdir COREOUTPUT +set COREOUTPUTCHANGES=jdiff\core\changes +mkdir COREOUTPUTCHANGES + +:: Fourth, perform the jdiff comparison +:: service bus +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -d %SERVICEBUSOUTPUT% -stats -oldapi %OLDSERVICEBUSAPI% -newapi %NEWSERVICEBUSAPI% d:\software\jdiff\Null.java +:: runtime +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -d %RUNTIMEOUTPUT% -stats -oldapi %OLDRUNTIMEAPI% -newapi %NEWRUNTIMEAPI% d:\software\jdiff\Null.java +:: media service +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -d %MEDIASERVICEOUTPUT% -stats -oldapi %OLDMEDIASERVICEAPI% -newapi %NEWMEDIASERVICEAPI% d:\software\jdiff\Null.java +:: management +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -d %MANAGEMENTOUTPUT% -stats -oldapi %OLDMANAGEMENTAPI% -newapi %NEWMANAGEMENTAPI% d:\software\jdiff\Null.java +:: core +javadoc -doclet jdiff.JDiff -docletpath %JDIFF% -d %COREOUTPUT% -stats -oldapi %OLDCOREAPI% -newapi %NEWCOREAPI% d:\software\jdiff\Null.java + diff --git a/tracing-util/pom.xml b/tracing-util/pom.xml new file mode 100644 index 0000000000000..22628a314ce17 --- /dev/null +++ b/tracing-util/pom.xml @@ -0,0 +1,148 @@ +<!-- + Copyright Microsoft Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.microsoft.windowsazure</groupId> + <artifactId>microsoft-azure-api-parent</artifactId> + <version>0.5.0</version> + <relativePath>../parent/pom.xml</relativePath> + </parent> + + <artifactId>microsoft-azure-api-tracing-util</artifactId> + <packaging>jar</packaging> + + <name>Microsoft Azure Util Logger tracing</name> + <description>API for Tracing with util logger in the Microsoft Azure Clients</description> + <url>https://github.com/Azure/azure-sdk-for-java</url> + + <licenses> + <license> + <name>The Apache Software License, Version 2.0</name> + <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> + <distribution>repo</distribution> + </license> + </licenses> + + <scm> + <url>scm:git:https://github.com/Azure/azure-sdk-for-java</url> + <connection>scm:git:git://github.com/Azure/azure-sdk-for-java.git</connection> + </scm> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <legal><![CDATA[[INFO] Any downloads listed may be third party software. Microsoft grants you no rights for third party software.]]></legal> + </properties> + + <developers> + <developer> + <id>microsoft</id> + <name>Microsoft</name> + </developer> + </developers> + + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>microsoft-azure-api-core</artifactId> + <version>0.5.0</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + <dependency> + <groupId>javax.inject</groupId> + <artifactId>javax.inject</artifactId> + </dependency> + + <!-- Test dependencies --> + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-all</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcprov-jdk16</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-help-plugin</artifactId> + <version>2.1.1</version> + <executions> + <execution> + <phase>validate</phase> + <goals> + <goal>evaluate</goal> + </goals> + <configuration> + <expression>legal</expression> + </configuration> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <source>1.6</source> + <target>1.6</target> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.8</version> + <configuration> + <excludePackageNames>*.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.storage</excludePackageNames> + <bottom><![CDATA[<code>/** +<br/>* Copyright Microsoft Corporation +<br/>* +<br/>* Licensed under the Apache License, Version 2.0 (the "License"); +<br/>* you may not use this file except in compliance with the License. +<br/>* You may obtain a copy of the License at +<br/>* http://www.apache.org/licenses/LICENSE-2.0 +<br/>* +<br/>* Unless required by applicable law or agreed to in writing, software +<br/>* distributed under the License is distributed on an "AS IS" BASIS, +<br/>* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +<br/>* See the License for the specific language governing permissions and +<br/>* limitations under the License. +<br/>*/</code>]]></bottom> + </configuration> + </plugin> + + </plugins> + </build> +</project> diff --git a/tracing-util/src/main/java/com/microsoft/windowsazure/core/tracing/util/JavaTracingInterceptor.java b/tracing-util/src/main/java/com/microsoft/windowsazure/core/tracing/util/JavaTracingInterceptor.java new file mode 100644 index 0000000000000..a188a538161e6 --- /dev/null +++ b/tracing-util/src/main/java/com/microsoft/windowsazure/core/tracing/util/JavaTracingInterceptor.java @@ -0,0 +1,142 @@ +/** + * + * Copyright (c) Microsoft and contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.microsoft.windowsazure.core.tracing.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; + +import com.microsoft.windowsazure.tracing.CloudTracingInterceptor; + +/** + * + * @author andrerod + * + */ +/// <summary> +/// Implementation for CloudTracingInterceptor that works using log4net framework. +/// </summary> +public class JavaTracingInterceptor implements CloudTracingInterceptor { + private Logger logger; + + /** + * Initializes a new instance of the JavaTracingInterceptor. + */ + public JavaTracingInterceptor() { + logger = Logger.getLogger(this.getClass().getName()); + } + + /** + * Trace information. + * + * @param message + * The information to trace. + */ + public void information(String message) { + logger.log(Level.INFO, message); + } + + /** + * Probe configuration for the value of a setting. + * + * @param source + * The configuration source. + * @param name + * The name of the setting. + * @param value + * The value of the setting in the source. + */ + public void configuration(String source, String name, String value) { + logger.log(Level.CONFIG, String.format("Configuration: source=%s, name=%s, value=%s", source, name, value)); + } + + /** + * Enter a method. + * + * @param invocationId + * Method invocation identifier. + * @param instance + * The instance with the method. + * @param method + * Name of the method. + * @param parameters + * Method parameters. + */ + public void enter(String invocationId, Object instance, String method, + HashMap<String, Object> parameters) { + ArrayList<Object> valuesList = new ArrayList<Object>(parameters.values()); + logger.entering(instance.getClass().getName(), method, valuesList.toArray()); + } + + /** + * Send an HTTP request. + * + * @param invocationId + * Method invocation identifier. + * @param request + * The request about to be sent. + */ + public void sendRequest(String invocationId, HttpRequest request) { + String requestAsString = request == null ? "" : request.toString(); + logger.log(Level.INFO, String.format("invocationId: %s\r\nrequest: %s", invocationId, requestAsString)); + } + + /** + * Receive an HTTP response. + * + * @param invocationId + * Method invocation identifier. + * @param response + * The response instance. + */ + public void receiveResponse(String invocationId, HttpResponse response) { + String responseAsString = response == null ? "" : response.toString(); + logger.log(Level.INFO, String.format("invocationId: %s\r\nrequest: %s", invocationId, responseAsString)); + } + + /** + * Raise an error. + * + * @param invocationId + * Method invocation identifier. + * @param exception + * The error. + */ + public void error(String invocationId, Exception exception) { + logger.log(Level.SEVERE, String.format("invocationId: %s", invocationId), exception); + } + + /** + * Exit a method. Note: Exit will not be called in the event of an error. + * + * @param invocationId + * Method invocation identifier. + * @param returnValue + * Method return value. + */ + public void exit(String invocationId, Object returnValue) { + logger.log(Level.INFO, String.format("Exit with invocation id %s, the return value is %s", + invocationId, + returnValue)); + } +} \ No newline at end of file diff --git a/tracing-util/src/main/java/com/microsoft/windowsazure/core/tracing/util/package.html b/tracing-util/src/main/java/com/microsoft/windowsazure/core/tracing/util/package.html new file mode 100644 index 0000000000000..94f59f10dda26 --- /dev/null +++ b/tracing-util/src/main/java/com/microsoft/windowsazure/core/tracing/util/package.html @@ -0,0 +1,5 @@ +<html> +<head /> +<body>This package contains the classes for a java tracing interceptor. +</body> +</html> diff --git a/tracing-util/src/test/java/com/microsoft/windowsazure/core/tracing/util/JavaTracingInterceptorTest.java b/tracing-util/src/test/java/com/microsoft/windowsazure/core/tracing/util/JavaTracingInterceptorTest.java new file mode 100644 index 0000000000000..ff3a6dae62e83 --- /dev/null +++ b/tracing-util/src/test/java/com/microsoft/windowsazure/core/tracing/util/JavaTracingInterceptorTest.java @@ -0,0 +1,58 @@ +/** + * Copyright Microsoft Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.microsoft.windowsazure.core.tracing.util; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.apache.http.HttpRequest; +import org.apache.http.client.methods.HttpPost; +import org.junit.Test; + +import com.microsoft.windowsazure.tracing.CloudTracing; + +public class JavaTracingInterceptorTest +{ + private ByteArrayOutputStream logContent; + + @Test + public void testInformationSendRequest() + { + // Arrange + logContent = new ByteArrayOutputStream(); + System.setErr(new PrintStream(logContent)); + + CloudTracing.addTracingInterceptor(new JavaTracingInterceptor()); + + HttpRequest httpRequest = new HttpPost("http://www.bing.com"); + + // Set Headers + httpRequest.setHeader("Content-Type", "application/xml"); + httpRequest.setHeader("x-ms-version", "2012-03-01"); + + // Act + CloudTracing.sendRequest("test", httpRequest); + + // Assert + String result = logContent.toString(); + assertTrue(result.contains("INFO: invocationId: test\r\nrequest: POST http://www.bing.com HTTP/1.1")); + + CloudTracing.information("hello there"); + result = logContent.toString(); + assertTrue(result.contains("INFO: hello there")); + } +}